@real-router/search-schema-plugin 0.3.0 → 0.3.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-router/search-schema-plugin",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "type": "commonjs",
5
5
  "description": "Runtime search parameter validation via Standard Schema for Real-Router",
6
6
  "main": "./dist/cjs/index.js",
@@ -18,8 +18,7 @@
18
18
  }
19
19
  },
20
20
  "files": [
21
- "dist",
22
- "src"
21
+ "dist"
23
22
  ],
24
23
  "repository": {
25
24
  "type": "git",
@@ -46,7 +45,7 @@
46
45
  "homepage": "https://github.com/greydragon888/real-router",
47
46
  "sideEffects": false,
48
47
  "dependencies": {
49
- "@real-router/core": "^0.56.0"
48
+ "@real-router/core": "^0.57.0"
50
49
  },
51
50
  "scripts": {
52
51
  "test": "vitest",
package/src/constants.ts DELETED
@@ -1,3 +0,0 @@
1
- // packages/search-schema-plugin/src/constants.ts
2
-
3
- export const ERROR_PREFIX = "[search-schema-plugin]";
package/src/factory.ts DELETED
@@ -1,25 +0,0 @@
1
- import { getPluginApi, getRoutesApi } from "@real-router/core/api";
2
-
3
- import { SearchSchemaPlugin } from "./plugin";
4
- import { validateOptions } from "./validation";
5
-
6
- import type { SearchSchemaPluginOptions } from "./types";
7
- import type { PluginFactory, Plugin } from "@real-router/core";
8
-
9
- export function searchSchemaPlugin(
10
- options: SearchSchemaPluginOptions = {},
11
- ): PluginFactory {
12
- validateOptions(options);
13
-
14
- const frozenOptions: SearchSchemaPluginOptions = Object.freeze({
15
- ...options,
16
- });
17
-
18
- return (router): Plugin => {
19
- const pluginApi = getPluginApi(router);
20
- const routesApi = getRoutesApi(router);
21
- const plugin = new SearchSchemaPlugin(pluginApi, routesApi, frozenOptions);
22
-
23
- return plugin.getPlugin();
24
- };
25
- }
package/src/helpers.ts DELETED
@@ -1,40 +0,0 @@
1
- // packages/search-schema-plugin/src/helpers.ts
2
-
3
- import type { StandardSchemaV1Issue } from "./types";
4
- import type { Params } from "@real-router/core";
5
-
6
- /**
7
- * Extract top-level keys from validation issues.
8
- * Only processes issues with a non-empty path — issues without path
9
- * affect the whole object and can't be stripped by key.
10
- */
11
- export function getInvalidKeys(
12
- issues: readonly StandardSchemaV1Issue[],
13
- ): Set<string> {
14
- const keys = new Set<string>();
15
-
16
- for (const issue of issues) {
17
- if (issue.path && issue.path.length > 0) {
18
- const segment = issue.path[0];
19
- const key =
20
- typeof segment === "object" && "key" in segment ? segment.key : segment;
21
-
22
- keys.add(String(key));
23
- }
24
- }
25
-
26
- return keys;
27
- }
28
-
29
- /** Create a shallow copy of params without the specified keys. */
30
- export function omitKeys(params: Params, keys: Set<string>): Params {
31
- const result: Params = {};
32
-
33
- for (const key of Object.keys(params)) {
34
- if (!keys.has(key)) {
35
- result[key] = params[key];
36
- }
37
- }
38
-
39
- return result;
40
- }
package/src/index.ts DELETED
@@ -1,16 +0,0 @@
1
- import type { StandardSchemaV1 } from "./types";
2
-
3
- export { searchSchemaPlugin } from "./factory";
4
-
5
- declare module "@real-router/core" {
6
- interface Route {
7
- searchSchema?: StandardSchemaV1;
8
- }
9
- }
10
-
11
- export type {
12
- SearchSchemaPluginOptions,
13
- StandardSchemaV1,
14
- StandardSchemaV1Issue,
15
- StandardSchemaV1Result,
16
- } from "./types";
package/src/plugin.ts DELETED
@@ -1,215 +0,0 @@
1
- import { ERROR_PREFIX } from "./constants";
2
- import { getInvalidKeys, omitKeys } from "./helpers";
3
-
4
- import type {
5
- SearchSchemaPluginOptions,
6
- StandardSchemaV1,
7
- StandardSchemaV1Issue,
8
- } from "./types";
9
- import type { Params, Plugin, TreeChangedEvent } from "@real-router/core";
10
- import type { PluginApi, RoutesApi } from "@real-router/core/api";
11
-
12
- export class SearchSchemaPlugin {
13
- readonly #pluginApi: PluginApi;
14
- readonly #routesApi: RoutesApi;
15
- readonly #mode: "development" | "production";
16
- readonly #strict: boolean;
17
- readonly #onError:
18
- | ((
19
- routeName: string,
20
- params: Params,
21
- issues: readonly StandardSchemaV1Issue[],
22
- ) => Params)
23
- | undefined;
24
- readonly #removeForwardStateInterceptor: () => void;
25
- readonly #removeChangesSubscription: () => void;
26
-
27
- constructor(
28
- pluginApi: PluginApi,
29
- routesApi: RoutesApi,
30
- options: SearchSchemaPluginOptions,
31
- ) {
32
- this.#pluginApi = pluginApi;
33
- this.#routesApi = routesApi;
34
- this.#mode = options.mode ?? "development";
35
- this.#strict = options.strict ?? false;
36
- this.#onError = options.onError;
37
-
38
- this.#validateExistingDefaultParams();
39
-
40
- this.#removeForwardStateInterceptor = this.#pluginApi.addInterceptor(
41
- "forwardState",
42
- (next, routeName, routeParams) => {
43
- const result = next(routeName, routeParams);
44
-
45
- return this.#validateState(result);
46
- },
47
- );
48
-
49
- // Dev-time defaultParams validation for runtime tree mutations. Replaces the
50
- // old `add` interceptor: TREE_CHANGED additionally covers `update` (changed
51
- // defaultParams) and `replace` (new route set) — the gap the interceptor
52
- // could not reach. Production mode skips the subscription entirely.
53
- this.#removeChangesSubscription =
54
- this.#mode === "development"
55
- ? this.#routesApi.subscribeChanges((event) => {
56
- this.#onTreeChanged(event);
57
- })
58
- : () => {};
59
- }
60
-
61
- getPlugin(): Plugin {
62
- return {
63
- teardown: () => {
64
- this.#removeForwardStateInterceptor();
65
- this.#removeChangesSubscription();
66
- },
67
- };
68
- }
69
-
70
- #onTreeChanged(event: TreeChangedEvent): void {
71
- switch (event.op) {
72
- case "add":
73
- case "replace": {
74
- // `added` is FLAT (full dotted names, descendants included).
75
- for (const route of event.added) {
76
- this.#validateSingleRouteDefaultParams(route.name);
77
- }
78
-
79
- break;
80
- }
81
- case "update": {
82
- // Only a defaultParams change can newly violate the schema.
83
- if (event.patch.defaultParams !== undefined) {
84
- this.#validateSingleRouteDefaultParams(event.name);
85
- }
86
-
87
- break;
88
- }
89
- // "remove" / "clear": the routes are gone — nothing to validate.
90
- }
91
- }
92
-
93
- #getSchema(routeName: string): StandardSchemaV1 | undefined {
94
- return this.#pluginApi.getRouteConfig(routeName)?.searchSchema as
95
- | StandardSchemaV1
96
- | undefined;
97
- }
98
-
99
- #validateState(result: { name: string; params: Params }): {
100
- name: string;
101
- params: Params;
102
- } {
103
- const schema = this.#getSchema(result.name);
104
-
105
- if (!schema) {
106
- return result;
107
- }
108
-
109
- const validation = schema["~standard"].validate(result.params);
110
-
111
- if (validation instanceof Promise) {
112
- throw new TypeError(
113
- `${ERROR_PREFIX} Async schema validation is not supported. Route "${result.name}" returned a Promise from ~standard.validate().`,
114
- );
115
- }
116
-
117
- if ("value" in validation) {
118
- const params = this.#strict
119
- ? (validation.value as Params)
120
- : { ...result.params, ...(validation.value as Params) };
121
-
122
- return { ...result, params };
123
- }
124
-
125
- if (this.#onError) {
126
- return {
127
- ...result,
128
- params: this.#onError(result.name, result.params, validation.issues),
129
- };
130
- }
131
-
132
- if (this.#mode === "development") {
133
- console.error(
134
- `${ERROR_PREFIX} Route "${result.name}": invalid search params`,
135
- validation.issues,
136
- );
137
- }
138
-
139
- const invalidKeys = getInvalidKeys(validation.issues);
140
- const stripped = omitKeys(result.params, invalidKeys);
141
- const route = this.#routesApi.get(result.name);
142
- const defaults = route?.defaultParams;
143
- const restored = defaults ? { ...defaults, ...stripped } : stripped;
144
-
145
- return { ...result, params: restored };
146
- }
147
-
148
- #validateExistingDefaultParams(): void {
149
- if (this.#mode !== "development") {
150
- return;
151
- }
152
-
153
- const tree = this.#pluginApi.getTree() as unknown as
154
- | { fullName?: string; children?: ReadonlyMap<string, unknown> }
155
- | undefined;
156
-
157
- /* v8 ignore next -- @preserve: getTree() always returns a RouteTree, defensive check */
158
- if (!tree) {
159
- return;
160
- }
161
-
162
- this.#walkTree(tree);
163
- }
164
-
165
- #walkTree(node: {
166
- fullName?: string;
167
- children?: ReadonlyMap<string, unknown>;
168
- }): void {
169
- if (node.fullName) {
170
- this.#validateSingleRouteDefaultParams(node.fullName);
171
- }
172
-
173
- /* v8 ignore next 3 -- @preserve: children is always a Map in RouteTree */
174
- if (node.children instanceof Map) {
175
- for (const child of node.children.values()) {
176
- if (child && typeof child === "object") {
177
- this.#walkTree(
178
- child as {
179
- fullName?: string;
180
- children?: ReadonlyMap<string, unknown>;
181
- },
182
- );
183
- }
184
- }
185
- }
186
- }
187
-
188
- #validateSingleRouteDefaultParams(routeName: string): void {
189
- const schema = this.#getSchema(routeName);
190
-
191
- if (!schema) {
192
- return;
193
- }
194
-
195
- const route = this.#routesApi.get(routeName);
196
- const defaultParams = route?.defaultParams;
197
-
198
- if (!defaultParams) {
199
- return;
200
- }
201
-
202
- const validation = schema["~standard"].validate(defaultParams);
203
-
204
- if (validation instanceof Promise) {
205
- return;
206
- }
207
-
208
- if ("issues" in validation) {
209
- console.warn(
210
- `${ERROR_PREFIX} Route "${routeName}": defaultParams do not pass searchSchema`,
211
- validation.issues,
212
- );
213
- }
214
- }
215
- }
package/src/types.ts DELETED
@@ -1,91 +0,0 @@
1
- // packages/search-schema-plugin/src/types.ts
2
-
3
- import type { Params } from "@real-router/core";
4
-
5
- // =============================================================================
6
- // Standard Schema V1 (inline — zero external deps)
7
- // https://github.com/standard-schema/standard-schema
8
- // =============================================================================
9
-
10
- /** A single validation issue from Standard Schema V1. */
11
- export interface StandardSchemaV1Issue {
12
- readonly message: string;
13
- readonly path?:
14
- | readonly (PropertyKey | { readonly key: PropertyKey })[]
15
- | undefined;
16
- }
17
-
18
- /** Validation result — either success or failure. */
19
- export type StandardSchemaV1Result<Output = unknown> =
20
- | { readonly value: Output }
21
- | { readonly issues: readonly StandardSchemaV1Issue[] };
22
-
23
- /**
24
- * Standard Schema V1 interface.
25
- *
26
- * Supported by Zod 3.24+, Valibot 1.0+, ArkType.
27
- * The plugin doesn't depend on any specific schema library.
28
- */
29
- export interface StandardSchemaV1<Input = unknown, Output = Input> {
30
- readonly "~standard": {
31
- readonly version: 1;
32
- readonly vendor: string;
33
- readonly validate: (
34
- value: unknown,
35
- ) =>
36
- | StandardSchemaV1Result<Output>
37
- | Promise<StandardSchemaV1Result<Output>>;
38
- readonly types?:
39
- | {
40
- readonly input: Input;
41
- readonly output: Output;
42
- }
43
- | undefined;
44
- };
45
- }
46
-
47
- // =============================================================================
48
- // Plugin Options
49
- // =============================================================================
50
-
51
- export interface SearchSchemaPluginOptions {
52
- /**
53
- * Error handling mode.
54
- * - "development" (default): strip invalid + console.error
55
- * - "production": silent strip
56
- *
57
- * For recovery of invalid params use defaultParams (strip + merge + diagnostics).
58
- * For filling absent params use .default() in schema (no diagnostics).
59
- * .catch() is not recommended — suppresses errors, mode: "development" won't see the issue.
60
- */
61
- readonly mode?: "development" | "production";
62
-
63
- /**
64
- * Strip search params not described in schema.
65
- * - false (default): unknown params pass through
66
- * - true: unknown params are removed
67
- *
68
- * Per-route override: .strict() / .passthrough() in Zod schema.
69
- */
70
- readonly strict?: boolean;
71
-
72
- /**
73
- * Custom error handler (overrides mode completely).
74
- * Must return cleaned params.
75
- *
76
- * Contract:
77
- * - Returned params are used as-is, without re-validation.
78
- * Responsibility for correctness is on the callback author.
79
- * (Re-validation would risk infinite loops.)
80
- * - Exceptions from onError propagate up without suppression.
81
- * Consistent with interceptor behavior in core.
82
- * - When onError is set, neither console.error (mode: "development"),
83
- * nor silent strip (mode: "production") are executed.
84
- * All responsibility for diagnostics and recovery is on the callback.
85
- */
86
- readonly onError?: (
87
- routeName: string,
88
- params: Params,
89
- issues: readonly StandardSchemaV1Issue[],
90
- ) => Params;
91
- }
package/src/validation.ts DELETED
@@ -1,25 +0,0 @@
1
- import { ERROR_PREFIX } from "./constants";
2
-
3
- import type { SearchSchemaPluginOptions } from "./types";
4
-
5
- const VALID_MODES = new Set(["development", "production"]);
6
-
7
- export function validateOptions(options: SearchSchemaPluginOptions): void {
8
- if (options.mode !== undefined && !VALID_MODES.has(options.mode)) {
9
- throw new TypeError(
10
- `${ERROR_PREFIX} Invalid mode: "${options.mode}". Must be "development" or "production".`,
11
- );
12
- }
13
-
14
- if (options.strict !== undefined && typeof options.strict !== "boolean") {
15
- throw new TypeError(
16
- `${ERROR_PREFIX} Invalid strict option: expected boolean, got ${typeof options.strict}.`,
17
- );
18
- }
19
-
20
- if (options.onError !== undefined && typeof options.onError !== "function") {
21
- throw new TypeError(
22
- `${ERROR_PREFIX} Invalid onError: expected function, got ${typeof options.onError}.`,
23
- );
24
- }
25
- }