@real-router/search-schema-plugin 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +1 -1
- package/package.json +3 -4
- package/src/constants.ts +0 -3
- package/src/factory.ts +0 -25
- package/src/helpers.ts +0 -40
- package/src/index.ts +0 -16
- package/src/plugin.ts +0 -215
- package/src/types.ts +0 -91
- package/src/validation.ts +0 -25
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@real-router/core/api");const t=`[search-schema-plugin]`;function n(e){let t=new Set;for(let n of e)if(n.path&&n.path.length>0){let e=n.path[0],r=typeof e==`object`&&`key`in e?e.key:e;t.add(String(r))}return t}function r(e,t){let n={};for(let
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@real-router/core/api");const t=`[search-schema-plugin]`;function n(e){let t=new Set;for(let n of e)if(n.path&&n.path.length>0){let e=n.path[0],r=typeof e==`object`&&`key`in e?e.key:e;t.add(String(r))}return t}function r(e,t){let n={};for(let[r,i]of Object.entries(e))t.has(r)||(n[r]=i);return n}var i=class{#e;#t;#n;#r;#i;#a;#o;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n.mode??`development`,this.#r=n.strict??!1,this.#i=n.onError,this.#u(),this.#a=this.#e.addInterceptor(`forwardState`,(e,t,n)=>{let r=e(t,n);return this.#l(r)}),this.#o=this.#n===`development`?this.#t.subscribeChanges(e=>{this.#s(e)}):()=>{}}getPlugin(){return{teardown:()=>{this.#a(),this.#o()}}}#s(e){switch(e.op){case`add`:case`replace`:for(let t of e.added)this.#f(t.name);break;case`update`:e.patch.defaultParams!==void 0&&this.#f(e.name);break}}#c(e){return this.#e.getRouteConfig(e)?.searchSchema}#l(e){let i=this.#c(e.name);if(!i)return e;let a=i[`~standard`].validate(e.params);if(a instanceof Promise)throw TypeError(`${t} Async schema validation is not supported. Route "${e.name}" returned a Promise from ~standard.validate().`);if(`value`in a){let t=this.#r?a.value:{...e.params,...a.value};return{...e,params:t}}if(this.#i)return{...e,params:this.#i(e.name,e.params,a.issues)};this.#n===`development`&&console.error(`${t} Route "${e.name}": invalid search params`,a.issues);let o=n(a.issues),s=r(e.params,o),c=this.#t.get(e.name)?.defaultParams,l=c?{...c,...s}:s;return{...e,params:l}}#u(){if(this.#n!==`development`)return;let e=this.#e.getTree();e&&this.#d(e)}#d(e){if(e.fullName&&this.#f(e.fullName),e.children instanceof Map)for(let t of e.children.values())t&&typeof t==`object`&&this.#d(t)}#f(e){let n=this.#c(e);if(!n)return;let r=this.#t.get(e)?.defaultParams;if(!r)return;let i=n[`~standard`].validate(r);i instanceof Promise||`issues`in i&&console.warn(`${t} Route "${e}": defaultParams do not pass searchSchema`,i.issues)}};const a=new Set([`development`,`production`]);function o(e){if(e.mode!==void 0&&!a.has(e.mode))throw TypeError(`${t} Invalid mode: "${e.mode}". Must be "development" or "production".`);if(e.strict!==void 0&&typeof e.strict!=`boolean`)throw TypeError(`${t} Invalid strict option: expected boolean, got ${typeof e.strict}.`);if(e.onError!==void 0&&typeof e.onError!=`function`)throw TypeError(`${t} Invalid onError: expected function, got ${typeof e.onError}.`)}function s(t={}){o(t);let n=Object.freeze({...t});return t=>new i((0,e.getPluginApi)(t),(0,e.getRoutesApi)(t),n).getPlugin()}exports.searchSchemaPlugin=s;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#pluginApi","#routesApi","#mode","#strict","#onError","#removeForwardStateInterceptor","#removeChangesSubscription","#validateExistingDefaultParams","#validateState","#onTreeChanged","#validateSingleRouteDefaultParams","#getSchema","#walkTree"],"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/plugin.ts","../../src/validation.ts","../../src/factory.ts"],"sourcesContent":["// packages/search-schema-plugin/src/constants.ts\n\nexport const ERROR_PREFIX = \"[search-schema-plugin]\";\n","// packages/search-schema-plugin/src/helpers.ts\n\nimport type { StandardSchemaV1Issue } from \"./types\";\nimport type { Params } from \"@real-router/core\";\n\n/**\n * Extract top-level keys from validation issues.\n * Only processes issues with a non-empty path — issues without path\n * affect the whole object and can't be stripped by key.\n */\nexport function getInvalidKeys(\n issues: readonly StandardSchemaV1Issue[],\n): Set<string> {\n const keys = new Set<string>();\n\n for (const issue of issues) {\n if (issue.path && issue.path.length > 0) {\n const segment = issue.path[0];\n const key =\n typeof segment === \"object\" && \"key\" in segment ? segment.key : segment;\n\n keys.add(String(key));\n }\n }\n\n return keys;\n}\n\n/** Create a shallow copy of params without the specified keys. */\nexport function omitKeys(params: Params, keys: Set<string>): Params {\n const result: Params = {};\n\n for (const key of Object.keys(params)) {\n if (!keys.has(key)) {\n result[key] = params[key];\n }\n }\n\n return result;\n}\n","import { ERROR_PREFIX } from \"./constants\";\nimport { getInvalidKeys, omitKeys } from \"./helpers\";\n\nimport type {\n SearchSchemaPluginOptions,\n StandardSchemaV1,\n StandardSchemaV1Issue,\n} from \"./types\";\nimport type { Params, Plugin, TreeChangedEvent } from \"@real-router/core\";\nimport type { PluginApi, RoutesApi } from \"@real-router/core/api\";\n\nexport class SearchSchemaPlugin {\n readonly #pluginApi: PluginApi;\n readonly #routesApi: RoutesApi;\n readonly #mode: \"development\" | \"production\";\n readonly #strict: boolean;\n readonly #onError:\n | ((\n routeName: string,\n params: Params,\n issues: readonly StandardSchemaV1Issue[],\n ) => Params)\n | undefined;\n readonly #removeForwardStateInterceptor: () => void;\n readonly #removeChangesSubscription: () => void;\n\n constructor(\n pluginApi: PluginApi,\n routesApi: RoutesApi,\n options: SearchSchemaPluginOptions,\n ) {\n this.#pluginApi = pluginApi;\n this.#routesApi = routesApi;\n this.#mode = options.mode ?? \"development\";\n this.#strict = options.strict ?? false;\n this.#onError = options.onError;\n\n this.#validateExistingDefaultParams();\n\n this.#removeForwardStateInterceptor = this.#pluginApi.addInterceptor(\n \"forwardState\",\n (next, routeName, routeParams) => {\n const result = next(routeName, routeParams);\n\n return this.#validateState(result);\n },\n );\n\n // Dev-time defaultParams validation for runtime tree mutations. Replaces the\n // old `add` interceptor: TREE_CHANGED additionally covers `update` (changed\n // defaultParams) and `replace` (new route set) — the gap the interceptor\n // could not reach. Production mode skips the subscription entirely.\n this.#removeChangesSubscription =\n this.#mode === \"development\"\n ? this.#routesApi.subscribeChanges((event) => {\n this.#onTreeChanged(event);\n })\n : () => {};\n }\n\n getPlugin(): Plugin {\n return {\n teardown: () => {\n this.#removeForwardStateInterceptor();\n this.#removeChangesSubscription();\n },\n };\n }\n\n #onTreeChanged(event: TreeChangedEvent): void {\n switch (event.op) {\n case \"add\":\n case \"replace\": {\n // `added` is FLAT (full dotted names, descendants included).\n for (const route of event.added) {\n this.#validateSingleRouteDefaultParams(route.name);\n }\n\n break;\n }\n case \"update\": {\n // Only a defaultParams change can newly violate the schema.\n if (event.patch.defaultParams !== undefined) {\n this.#validateSingleRouteDefaultParams(event.name);\n }\n\n break;\n }\n // \"remove\" / \"clear\": the routes are gone — nothing to validate.\n }\n }\n\n #getSchema(routeName: string): StandardSchemaV1 | undefined {\n return this.#pluginApi.getRouteConfig(routeName)?.searchSchema as\n | StandardSchemaV1\n | undefined;\n }\n\n #validateState(result: { name: string; params: Params }): {\n name: string;\n params: Params;\n } {\n const schema = this.#getSchema(result.name);\n\n if (!schema) {\n return result;\n }\n\n const validation = schema[\"~standard\"].validate(result.params);\n\n if (validation instanceof Promise) {\n throw new TypeError(\n `${ERROR_PREFIX} Async schema validation is not supported. Route \"${result.name}\" returned a Promise from ~standard.validate().`,\n );\n }\n\n if (\"value\" in validation) {\n const params = this.#strict\n ? (validation.value as Params)\n : { ...result.params, ...(validation.value as Params) };\n\n return { ...result, params };\n }\n\n if (this.#onError) {\n return {\n ...result,\n params: this.#onError(result.name, result.params, validation.issues),\n };\n }\n\n if (this.#mode === \"development\") {\n console.error(\n `${ERROR_PREFIX} Route \"${result.name}\": invalid search params`,\n validation.issues,\n );\n }\n\n const invalidKeys = getInvalidKeys(validation.issues);\n const stripped = omitKeys(result.params, invalidKeys);\n const route = this.#routesApi.get(result.name);\n const defaults = route?.defaultParams;\n const restored = defaults ? { ...defaults, ...stripped } : stripped;\n\n return { ...result, params: restored };\n }\n\n #validateExistingDefaultParams(): void {\n if (this.#mode !== \"development\") {\n return;\n }\n\n const tree = this.#pluginApi.getTree() as unknown as\n | { fullName?: string; children?: ReadonlyMap<string, unknown> }\n | undefined;\n\n /* v8 ignore next -- @preserve: getTree() always returns a RouteTree, defensive check */\n if (!tree) {\n return;\n }\n\n this.#walkTree(tree);\n }\n\n #walkTree(node: {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n }): void {\n if (node.fullName) {\n this.#validateSingleRouteDefaultParams(node.fullName);\n }\n\n /* v8 ignore next 3 -- @preserve: children is always a Map in RouteTree */\n if (node.children instanceof Map) {\n for (const child of node.children.values()) {\n if (child && typeof child === \"object\") {\n this.#walkTree(\n child as {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n },\n );\n }\n }\n }\n }\n\n #validateSingleRouteDefaultParams(routeName: string): void {\n const schema = this.#getSchema(routeName);\n\n if (!schema) {\n return;\n }\n\n const route = this.#routesApi.get(routeName);\n const defaultParams = route?.defaultParams;\n\n if (!defaultParams) {\n return;\n }\n\n const validation = schema[\"~standard\"].validate(defaultParams);\n\n if (validation instanceof Promise) {\n return;\n }\n\n if (\"issues\" in validation) {\n console.warn(\n `${ERROR_PREFIX} Route \"${routeName}\": defaultParams do not pass searchSchema`,\n validation.issues,\n );\n }\n }\n}\n","import { ERROR_PREFIX } from \"./constants\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\n\nconst VALID_MODES = new Set([\"development\", \"production\"]);\n\nexport function validateOptions(options: SearchSchemaPluginOptions): void {\n if (options.mode !== undefined && !VALID_MODES.has(options.mode)) {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid mode: \"${options.mode}\". Must be \"development\" or \"production\".`,\n );\n }\n\n if (options.strict !== undefined && typeof options.strict !== \"boolean\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid strict option: expected boolean, got ${typeof options.strict}.`,\n );\n }\n\n if (options.onError !== undefined && typeof options.onError !== \"function\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid onError: expected function, got ${typeof options.onError}.`,\n );\n }\n}\n","import { getPluginApi, getRoutesApi } from \"@real-router/core/api\";\n\nimport { SearchSchemaPlugin } from \"./plugin\";\nimport { validateOptions } from \"./validation\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\nimport type { PluginFactory, Plugin } from \"@real-router/core\";\n\nexport function searchSchemaPlugin(\n options: SearchSchemaPluginOptions = {},\n): PluginFactory {\n validateOptions(options);\n\n const frozenOptions: SearchSchemaPluginOptions = Object.freeze({\n ...options,\n });\n\n return (router): Plugin => {\n const pluginApi = getPluginApi(router);\n const routesApi = getRoutesApi(router);\n const plugin = new SearchSchemaPlugin(pluginApi, routesApi, frozenOptions);\n\n return plugin.getPlugin();\n };\n}\n"],"mappings":"0GAEA,MAAa,EAAe,yBCQ5B,SAAgB,EACd,EACa,CACb,IAAM,EAAO,IAAI,IAEjB,IAAK,IAAM,KAAS,EAClB,GAAI,EAAM,MAAQ,EAAM,KAAK,OAAS,EAAG,CACvC,IAAM,EAAU,EAAM,KAAK,GACrB,EACJ,OAAO,GAAY,UAAY,QAAS,EAAU,EAAQ,IAAM,EAElE,EAAK,IAAI,OAAO,CAAG,CAAC,CACtB,CAGF,OAAO,CACT,CAGA,SAAgB,EAAS,EAAgB,EAA2B,CAClE,IAAM,EAAiB,CAAC,EAExB,IAAK,IAAM,KAAO,OAAO,KAAK,CAAM,EAC7B,EAAK,IAAI,CAAG,IACf,EAAO,GAAO,EAAO,IAIzB,O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,EAAY,IAAI,EAAQ,IAAI,EAC7D,MAAU,UACR,GAAG,EAAa,kBAAkB,EAAQ,KAAK,0CACjD,EAGF,GAAI,EAAQ,SAAW,IAAA,IAAa,OAAO,EAAQ,QAAW,UAC5D,MAAU,UACR,GAAG,EAAa,gDAAgD,OAAO,EAAQ,OAAO,EACxF,EAGF,GAAI,EAAQ,UAAY,IAAA,IAAa,OAAO,EAAQ,SAAY,WAC9D,MAAU,UACR,GAAG,EAAa,2CAA2C,OAAO,EAAQ,QAAQ,EACpF,CAEJ,CChBA,SAAgB,EACd,EAAqC,CAAC,EACvB,CACf,EAAgB,CAAO,EAEvB,IAAM,EAA2C,OAAO,OAAO,CAC7D,GAAG,CACL,CAAC,EAED,MAAQ,IAKC,IAFY,GAAA,EAAA,EAAA,aAAA,CAFY,CAEe,GAAA,EAAA,EAAA,aAAA,CADf,CAC0B,EAAG,CAEhD,CAAC,CAAC,UAAU,CAE5B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#pluginApi","#routesApi","#mode","#strict","#onError","#removeForwardStateInterceptor","#removeChangesSubscription","#validateExistingDefaultParams","#validateState","#onTreeChanged","#validateSingleRouteDefaultParams","#getSchema","#walkTree"],"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/plugin.ts","../../src/validation.ts","../../src/factory.ts"],"sourcesContent":["// packages/search-schema-plugin/src/constants.ts\n\nexport const ERROR_PREFIX = \"[search-schema-plugin]\";\n","// packages/search-schema-plugin/src/helpers.ts\n\nimport type { StandardSchemaV1Issue } from \"./types\";\nimport type { Params } from \"@real-router/core\";\n\n/**\n * Extract top-level keys from validation issues.\n * Only processes issues with a non-empty path — issues without path\n * affect the whole object and can't be stripped by key.\n */\nexport function getInvalidKeys(\n issues: readonly StandardSchemaV1Issue[],\n): Set<string> {\n const keys = new Set<string>();\n\n for (const issue of issues) {\n if (issue.path && issue.path.length > 0) {\n const segment = issue.path[0];\n const key =\n typeof segment === \"object\" && \"key\" in segment ? segment.key : segment;\n\n keys.add(String(key));\n }\n }\n\n return keys;\n}\n\n/** Create a shallow copy of params without the specified keys. */\nexport function omitKeys(params: Params, keys: Set<string>): Params {\n const result: Params = {};\n\n for (const [key, value] of Object.entries(params)) {\n if (!keys.has(key)) {\n result[key] = value;\n }\n }\n\n return result;\n}\n","import { ERROR_PREFIX } from \"./constants\";\nimport { getInvalidKeys, omitKeys } from \"./helpers\";\n\nimport type {\n SearchSchemaPluginOptions,\n StandardSchemaV1,\n StandardSchemaV1Issue,\n} from \"./types\";\nimport type { Params, Plugin, TreeChangedEvent } from \"@real-router/core\";\nimport type { PluginApi, RoutesApi } from \"@real-router/core/api\";\n\nexport class SearchSchemaPlugin {\n readonly #pluginApi: PluginApi;\n readonly #routesApi: RoutesApi;\n readonly #mode: \"development\" | \"production\";\n readonly #strict: boolean;\n readonly #onError:\n | ((\n routeName: string,\n params: Params,\n issues: readonly StandardSchemaV1Issue[],\n ) => Params)\n | undefined;\n readonly #removeForwardStateInterceptor: () => void;\n readonly #removeChangesSubscription: () => void;\n\n constructor(\n pluginApi: PluginApi,\n routesApi: RoutesApi,\n options: SearchSchemaPluginOptions,\n ) {\n this.#pluginApi = pluginApi;\n this.#routesApi = routesApi;\n this.#mode = options.mode ?? \"development\";\n this.#strict = options.strict ?? false;\n this.#onError = options.onError;\n\n this.#validateExistingDefaultParams();\n\n this.#removeForwardStateInterceptor = this.#pluginApi.addInterceptor(\n \"forwardState\",\n (next, routeName, routeParams) => {\n const result = next(routeName, routeParams);\n\n return this.#validateState(result);\n },\n );\n\n // Dev-time defaultParams validation for runtime tree mutations. Replaces the\n // old `add` interceptor: TREE_CHANGED additionally covers `update` (changed\n // defaultParams) and `replace` (new route set) — the gap the interceptor\n // could not reach. Production mode skips the subscription entirely.\n this.#removeChangesSubscription =\n this.#mode === \"development\"\n ? this.#routesApi.subscribeChanges((event) => {\n this.#onTreeChanged(event);\n })\n : () => {};\n }\n\n getPlugin(): Plugin {\n return {\n teardown: () => {\n this.#removeForwardStateInterceptor();\n this.#removeChangesSubscription();\n },\n };\n }\n\n #onTreeChanged(event: TreeChangedEvent): void {\n switch (event.op) {\n case \"add\":\n case \"replace\": {\n // `added` is FLAT (full dotted names, descendants included).\n for (const route of event.added) {\n this.#validateSingleRouteDefaultParams(route.name);\n }\n\n break;\n }\n case \"update\": {\n // Only a defaultParams change can newly violate the schema.\n if (event.patch.defaultParams !== undefined) {\n this.#validateSingleRouteDefaultParams(event.name);\n }\n\n break;\n }\n // \"remove\" / \"clear\": the routes are gone — nothing to validate.\n }\n }\n\n #getSchema(routeName: string): StandardSchemaV1 | undefined {\n return this.#pluginApi.getRouteConfig(routeName)?.searchSchema as\n | StandardSchemaV1\n | undefined;\n }\n\n #validateState(result: { name: string; params: Params }): {\n name: string;\n params: Params;\n } {\n const schema = this.#getSchema(result.name);\n\n if (!schema) {\n return result;\n }\n\n const validation = schema[\"~standard\"].validate(result.params);\n\n if (validation instanceof Promise) {\n throw new TypeError(\n `${ERROR_PREFIX} Async schema validation is not supported. Route \"${result.name}\" returned a Promise from ~standard.validate().`,\n );\n }\n\n if (\"value\" in validation) {\n const params = this.#strict\n ? (validation.value as Params)\n : { ...result.params, ...(validation.value as Params) };\n\n return { ...result, params };\n }\n\n if (this.#onError) {\n return {\n ...result,\n params: this.#onError(result.name, result.params, validation.issues),\n };\n }\n\n if (this.#mode === \"development\") {\n console.error(\n `${ERROR_PREFIX} Route \"${result.name}\": invalid search params`,\n validation.issues,\n );\n }\n\n const invalidKeys = getInvalidKeys(validation.issues);\n const stripped = omitKeys(result.params, invalidKeys);\n const route = this.#routesApi.get(result.name);\n const defaults = route?.defaultParams;\n const restored = defaults ? { ...defaults, ...stripped } : stripped;\n\n return { ...result, params: restored };\n }\n\n #validateExistingDefaultParams(): void {\n if (this.#mode !== \"development\") {\n return;\n }\n\n const tree = this.#pluginApi.getTree() as unknown as\n | { fullName?: string; children?: ReadonlyMap<string, unknown> }\n | undefined;\n\n /* v8 ignore next -- @preserve: getTree() always returns a RouteTree, defensive check */\n if (!tree) {\n return;\n }\n\n this.#walkTree(tree);\n }\n\n #walkTree(node: {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n }): void {\n if (node.fullName) {\n this.#validateSingleRouteDefaultParams(node.fullName);\n }\n\n /* v8 ignore next 3 -- @preserve: children is always a Map in RouteTree */\n if (node.children instanceof Map) {\n for (const child of node.children.values()) {\n if (child && typeof child === \"object\") {\n this.#walkTree(\n child as {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n },\n );\n }\n }\n }\n }\n\n #validateSingleRouteDefaultParams(routeName: string): void {\n const schema = this.#getSchema(routeName);\n\n if (!schema) {\n return;\n }\n\n const route = this.#routesApi.get(routeName);\n const defaultParams = route?.defaultParams;\n\n if (!defaultParams) {\n return;\n }\n\n const validation = schema[\"~standard\"].validate(defaultParams);\n\n if (validation instanceof Promise) {\n return;\n }\n\n if (\"issues\" in validation) {\n console.warn(\n `${ERROR_PREFIX} Route \"${routeName}\": defaultParams do not pass searchSchema`,\n validation.issues,\n );\n }\n }\n}\n","import { ERROR_PREFIX } from \"./constants\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\n\nconst VALID_MODES = new Set([\"development\", \"production\"]);\n\nexport function validateOptions(options: SearchSchemaPluginOptions): void {\n if (options.mode !== undefined && !VALID_MODES.has(options.mode)) {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid mode: \"${options.mode}\". Must be \"development\" or \"production\".`,\n );\n }\n\n if (options.strict !== undefined && typeof options.strict !== \"boolean\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid strict option: expected boolean, got ${typeof options.strict}.`,\n );\n }\n\n if (options.onError !== undefined && typeof options.onError !== \"function\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid onError: expected function, got ${typeof options.onError}.`,\n );\n }\n}\n","import { getPluginApi, getRoutesApi } from \"@real-router/core/api\";\n\nimport { SearchSchemaPlugin } from \"./plugin\";\nimport { validateOptions } from \"./validation\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\nimport type { PluginFactory, Plugin } from \"@real-router/core\";\n\nexport function searchSchemaPlugin(\n options: SearchSchemaPluginOptions = {},\n): PluginFactory {\n validateOptions(options);\n\n const frozenOptions: SearchSchemaPluginOptions = Object.freeze({\n ...options,\n });\n\n return (router): Plugin => {\n const pluginApi = getPluginApi(router);\n const routesApi = getRoutesApi(router);\n const plugin = new SearchSchemaPlugin(pluginApi, routesApi, frozenOptions);\n\n return plugin.getPlugin();\n };\n}\n"],"mappings":"0GAEA,MAAa,EAAe,yBCQ5B,SAAgB,EACd,EACa,CACb,IAAM,EAAO,IAAI,IAEjB,IAAK,IAAM,KAAS,EAClB,GAAI,EAAM,MAAQ,EAAM,KAAK,OAAS,EAAG,CACvC,IAAM,EAAU,EAAM,KAAK,GACrB,EACJ,OAAO,GAAY,UAAY,QAAS,EAAU,EAAQ,IAAM,EAElE,EAAK,IAAI,OAAO,CAAG,CAAC,CACtB,CAGF,OAAO,CACT,CAGA,SAAgB,EAAS,EAAgB,EAA2B,CAClE,IAAM,EAAiB,CAAC,EAExB,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EACzC,EAAK,IAAI,CAAG,IACf,EAAO,GAAO,GAIlB,OAAO,CACT,CC5BA,IAAa,EAAb,KAAgC,CAC9B,GACA,GACA,GACA,GACA,GAOA,GACA,GAEA,YACE,EACA,EACA,EACA,CACA,KAAKA,GAAa,EAClB,KAAKC,GAAa,EAClB,KAAKC,GAAQ,EAAQ,MAAQ,cAC7B,KAAKC,GAAU,EAAQ,QAAU,GACjC,KAAKC,GAAW,EAAQ,QAExB,KAAKG,GAA+B,EAEpC,KAAKF,GAAiC,KAAKL,GAAW,eACpD,gBACC,EAAM,EAAW,IAAgB,CAChC,IAAM,EAAS,EAAK,EAAW,CAAW,EAE1C,OAAO,KAAKQ,GAAe,CAAM,CACnC,CACF,EAMA,KAAKF,GACH,KAAKJ,KAAU,cACX,KAAKD,GAAW,iBAAkB,GAAU,CAC1C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,GAAA,EAAA,EAAA,aAAA,CAFY,CAEe,GAAA,EAAA,EAAA,aAAA,CADf,CAC0B,EAAG,CAEhD,CAAC,CAAC,UAAU,CAE5B"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getPluginApi as e,getRoutesApi as t}from"@real-router/core/api";const n=`[search-schema-plugin]`;function r(e){let t=new Set;for(let n of e)if(n.path&&n.path.length>0){let e=n.path[0],r=typeof e==`object`&&`key`in e?e.key:e;t.add(String(r))}return t}function i(e,t){let n={};for(let
|
|
1
|
+
import{getPluginApi as e,getRoutesApi as t}from"@real-router/core/api";const n=`[search-schema-plugin]`;function r(e){let t=new Set;for(let n of e)if(n.path&&n.path.length>0){let e=n.path[0],r=typeof e==`object`&&`key`in e?e.key:e;t.add(String(r))}return t}function i(e,t){let n={};for(let[r,i]of Object.entries(e))t.has(r)||(n[r]=i);return n}var a=class{#e;#t;#n;#r;#i;#a;#o;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n.mode??`development`,this.#r=n.strict??!1,this.#i=n.onError,this.#u(),this.#a=this.#e.addInterceptor(`forwardState`,(e,t,n)=>{let r=e(t,n);return this.#l(r)}),this.#o=this.#n===`development`?this.#t.subscribeChanges(e=>{this.#s(e)}):()=>{}}getPlugin(){return{teardown:()=>{this.#a(),this.#o()}}}#s(e){switch(e.op){case`add`:case`replace`:for(let t of e.added)this.#f(t.name);break;case`update`:e.patch.defaultParams!==void 0&&this.#f(e.name);break}}#c(e){return this.#e.getRouteConfig(e)?.searchSchema}#l(e){let t=this.#c(e.name);if(!t)return e;let a=t[`~standard`].validate(e.params);if(a instanceof Promise)throw TypeError(`${n} Async schema validation is not supported. Route "${e.name}" returned a Promise from ~standard.validate().`);if(`value`in a){let t=this.#r?a.value:{...e.params,...a.value};return{...e,params:t}}if(this.#i)return{...e,params:this.#i(e.name,e.params,a.issues)};this.#n===`development`&&console.error(`${n} Route "${e.name}": invalid search params`,a.issues);let o=r(a.issues),s=i(e.params,o),c=this.#t.get(e.name)?.defaultParams,l=c?{...c,...s}:s;return{...e,params:l}}#u(){if(this.#n!==`development`)return;let e=this.#e.getTree();e&&this.#d(e)}#d(e){if(e.fullName&&this.#f(e.fullName),e.children instanceof Map)for(let t of e.children.values())t&&typeof t==`object`&&this.#d(t)}#f(e){let t=this.#c(e);if(!t)return;let r=this.#t.get(e)?.defaultParams;if(!r)return;let i=t[`~standard`].validate(r);i instanceof Promise||`issues`in i&&console.warn(`${n} Route "${e}": defaultParams do not pass searchSchema`,i.issues)}};const o=new Set([`development`,`production`]);function s(e){if(e.mode!==void 0&&!o.has(e.mode))throw TypeError(`${n} Invalid mode: "${e.mode}". Must be "development" or "production".`);if(e.strict!==void 0&&typeof e.strict!=`boolean`)throw TypeError(`${n} Invalid strict option: expected boolean, got ${typeof e.strict}.`);if(e.onError!==void 0&&typeof e.onError!=`function`)throw TypeError(`${n} Invalid onError: expected function, got ${typeof e.onError}.`)}function c(n={}){s(n);let r=Object.freeze({...n});return n=>new a(e(n),t(n),r).getPlugin()}export{c as searchSchemaPlugin};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#pluginApi","#routesApi","#mode","#strict","#onError","#removeForwardStateInterceptor","#removeChangesSubscription","#validateExistingDefaultParams","#validateState","#onTreeChanged","#validateSingleRouteDefaultParams","#getSchema","#walkTree"],"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/plugin.ts","../../src/validation.ts","../../src/factory.ts"],"sourcesContent":["// packages/search-schema-plugin/src/constants.ts\n\nexport const ERROR_PREFIX = \"[search-schema-plugin]\";\n","// packages/search-schema-plugin/src/helpers.ts\n\nimport type { StandardSchemaV1Issue } from \"./types\";\nimport type { Params } from \"@real-router/core\";\n\n/**\n * Extract top-level keys from validation issues.\n * Only processes issues with a non-empty path — issues without path\n * affect the whole object and can't be stripped by key.\n */\nexport function getInvalidKeys(\n issues: readonly StandardSchemaV1Issue[],\n): Set<string> {\n const keys = new Set<string>();\n\n for (const issue of issues) {\n if (issue.path && issue.path.length > 0) {\n const segment = issue.path[0];\n const key =\n typeof segment === \"object\" && \"key\" in segment ? segment.key : segment;\n\n keys.add(String(key));\n }\n }\n\n return keys;\n}\n\n/** Create a shallow copy of params without the specified keys. */\nexport function omitKeys(params: Params, keys: Set<string>): Params {\n const result: Params = {};\n\n for (const key of Object.keys(params)) {\n if (!keys.has(key)) {\n result[key] = params[key];\n }\n }\n\n return result;\n}\n","import { ERROR_PREFIX } from \"./constants\";\nimport { getInvalidKeys, omitKeys } from \"./helpers\";\n\nimport type {\n SearchSchemaPluginOptions,\n StandardSchemaV1,\n StandardSchemaV1Issue,\n} from \"./types\";\nimport type { Params, Plugin, TreeChangedEvent } from \"@real-router/core\";\nimport type { PluginApi, RoutesApi } from \"@real-router/core/api\";\n\nexport class SearchSchemaPlugin {\n readonly #pluginApi: PluginApi;\n readonly #routesApi: RoutesApi;\n readonly #mode: \"development\" | \"production\";\n readonly #strict: boolean;\n readonly #onError:\n | ((\n routeName: string,\n params: Params,\n issues: readonly StandardSchemaV1Issue[],\n ) => Params)\n | undefined;\n readonly #removeForwardStateInterceptor: () => void;\n readonly #removeChangesSubscription: () => void;\n\n constructor(\n pluginApi: PluginApi,\n routesApi: RoutesApi,\n options: SearchSchemaPluginOptions,\n ) {\n this.#pluginApi = pluginApi;\n this.#routesApi = routesApi;\n this.#mode = options.mode ?? \"development\";\n this.#strict = options.strict ?? false;\n this.#onError = options.onError;\n\n this.#validateExistingDefaultParams();\n\n this.#removeForwardStateInterceptor = this.#pluginApi.addInterceptor(\n \"forwardState\",\n (next, routeName, routeParams) => {\n const result = next(routeName, routeParams);\n\n return this.#validateState(result);\n },\n );\n\n // Dev-time defaultParams validation for runtime tree mutations. Replaces the\n // old `add` interceptor: TREE_CHANGED additionally covers `update` (changed\n // defaultParams) and `replace` (new route set) — the gap the interceptor\n // could not reach. Production mode skips the subscription entirely.\n this.#removeChangesSubscription =\n this.#mode === \"development\"\n ? this.#routesApi.subscribeChanges((event) => {\n this.#onTreeChanged(event);\n })\n : () => {};\n }\n\n getPlugin(): Plugin {\n return {\n teardown: () => {\n this.#removeForwardStateInterceptor();\n this.#removeChangesSubscription();\n },\n };\n }\n\n #onTreeChanged(event: TreeChangedEvent): void {\n switch (event.op) {\n case \"add\":\n case \"replace\": {\n // `added` is FLAT (full dotted names, descendants included).\n for (const route of event.added) {\n this.#validateSingleRouteDefaultParams(route.name);\n }\n\n break;\n }\n case \"update\": {\n // Only a defaultParams change can newly violate the schema.\n if (event.patch.defaultParams !== undefined) {\n this.#validateSingleRouteDefaultParams(event.name);\n }\n\n break;\n }\n // \"remove\" / \"clear\": the routes are gone — nothing to validate.\n }\n }\n\n #getSchema(routeName: string): StandardSchemaV1 | undefined {\n return this.#pluginApi.getRouteConfig(routeName)?.searchSchema as\n | StandardSchemaV1\n | undefined;\n }\n\n #validateState(result: { name: string; params: Params }): {\n name: string;\n params: Params;\n } {\n const schema = this.#getSchema(result.name);\n\n if (!schema) {\n return result;\n }\n\n const validation = schema[\"~standard\"].validate(result.params);\n\n if (validation instanceof Promise) {\n throw new TypeError(\n `${ERROR_PREFIX} Async schema validation is not supported. Route \"${result.name}\" returned a Promise from ~standard.validate().`,\n );\n }\n\n if (\"value\" in validation) {\n const params = this.#strict\n ? (validation.value as Params)\n : { ...result.params, ...(validation.value as Params) };\n\n return { ...result, params };\n }\n\n if (this.#onError) {\n return {\n ...result,\n params: this.#onError(result.name, result.params, validation.issues),\n };\n }\n\n if (this.#mode === \"development\") {\n console.error(\n `${ERROR_PREFIX} Route \"${result.name}\": invalid search params`,\n validation.issues,\n );\n }\n\n const invalidKeys = getInvalidKeys(validation.issues);\n const stripped = omitKeys(result.params, invalidKeys);\n const route = this.#routesApi.get(result.name);\n const defaults = route?.defaultParams;\n const restored = defaults ? { ...defaults, ...stripped } : stripped;\n\n return { ...result, params: restored };\n }\n\n #validateExistingDefaultParams(): void {\n if (this.#mode !== \"development\") {\n return;\n }\n\n const tree = this.#pluginApi.getTree() as unknown as\n | { fullName?: string; children?: ReadonlyMap<string, unknown> }\n | undefined;\n\n /* v8 ignore next -- @preserve: getTree() always returns a RouteTree, defensive check */\n if (!tree) {\n return;\n }\n\n this.#walkTree(tree);\n }\n\n #walkTree(node: {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n }): void {\n if (node.fullName) {\n this.#validateSingleRouteDefaultParams(node.fullName);\n }\n\n /* v8 ignore next 3 -- @preserve: children is always a Map in RouteTree */\n if (node.children instanceof Map) {\n for (const child of node.children.values()) {\n if (child && typeof child === \"object\") {\n this.#walkTree(\n child as {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n },\n );\n }\n }\n }\n }\n\n #validateSingleRouteDefaultParams(routeName: string): void {\n const schema = this.#getSchema(routeName);\n\n if (!schema) {\n return;\n }\n\n const route = this.#routesApi.get(routeName);\n const defaultParams = route?.defaultParams;\n\n if (!defaultParams) {\n return;\n }\n\n const validation = schema[\"~standard\"].validate(defaultParams);\n\n if (validation instanceof Promise) {\n return;\n }\n\n if (\"issues\" in validation) {\n console.warn(\n `${ERROR_PREFIX} Route \"${routeName}\": defaultParams do not pass searchSchema`,\n validation.issues,\n );\n }\n }\n}\n","import { ERROR_PREFIX } from \"./constants\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\n\nconst VALID_MODES = new Set([\"development\", \"production\"]);\n\nexport function validateOptions(options: SearchSchemaPluginOptions): void {\n if (options.mode !== undefined && !VALID_MODES.has(options.mode)) {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid mode: \"${options.mode}\". Must be \"development\" or \"production\".`,\n );\n }\n\n if (options.strict !== undefined && typeof options.strict !== \"boolean\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid strict option: expected boolean, got ${typeof options.strict}.`,\n );\n }\n\n if (options.onError !== undefined && typeof options.onError !== \"function\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid onError: expected function, got ${typeof options.onError}.`,\n );\n }\n}\n","import { getPluginApi, getRoutesApi } from \"@real-router/core/api\";\n\nimport { SearchSchemaPlugin } from \"./plugin\";\nimport { validateOptions } from \"./validation\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\nimport type { PluginFactory, Plugin } from \"@real-router/core\";\n\nexport function searchSchemaPlugin(\n options: SearchSchemaPluginOptions = {},\n): PluginFactory {\n validateOptions(options);\n\n const frozenOptions: SearchSchemaPluginOptions = Object.freeze({\n ...options,\n });\n\n return (router): Plugin => {\n const pluginApi = getPluginApi(router);\n const routesApi = getRoutesApi(router);\n const plugin = new SearchSchemaPlugin(pluginApi, routesApi, frozenOptions);\n\n return plugin.getPlugin();\n };\n}\n"],"mappings":"uEAEA,MAAa,EAAe,yBCQ5B,SAAgB,EACd,EACa,CACb,IAAM,EAAO,IAAI,IAEjB,IAAK,IAAM,KAAS,EAClB,GAAI,EAAM,MAAQ,EAAM,KAAK,OAAS,EAAG,CACvC,IAAM,EAAU,EAAM,KAAK,GACrB,EACJ,OAAO,GAAY,UAAY,QAAS,EAAU,EAAQ,IAAM,EAElE,EAAK,IAAI,OAAO,CAAG,CAAC,CACtB,CAGF,OAAO,CACT,CAGA,SAAgB,EAAS,EAAgB,EAA2B,CAClE,IAAM,EAAiB,CAAC,EAExB,IAAK,IAAM,KAAO,OAAO,KAAK,CAAM,EAC7B,EAAK,IAAI,CAAG,IACf,EAAO,GAAO,EAAO,IAIzB,OAAO,CACT,CC5BA,IAAa,EAAb,KAAgC,CAC9B,GACA,GACA,GACA,GACA,GAOA,GACA,GAEA,YACE,EACA,EACA,EACA,CACA,KAAKA,GAAa,EAClB,KAAKC,GAAa,EAClB,KAAKC,GAAQ,EAAQ,MAAQ,cAC7B,KAAKC,GAAU,EAAQ,QAAU,GACjC,KAAKC,GAAW,EAAQ,QAExB,KAAKG,GAA+B,EAEpC,KAAKF,GAAiC,KAAKL,GAAW,eACpD,gBACC,E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,OAAO,EAAQ,QAAQ,EACpF,CAEJ,CChBA,SAAgB,EACd,EAAqC,CAAC,EACvB,CACf,EAAgB,CAAO,EAEvB,IAAM,EAA2C,OAAO,OAAO,CAC7D,GAAG,CACL,CAAC,EAED,MAAQ,IAKC,IAFY,EAFD,EAAa,CAEe,EAD5B,EAAa,CAC0B,EAAG,CAEhD,CAAC,CAAC,UAAU,CAE5B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["#pluginApi","#routesApi","#mode","#strict","#onError","#removeForwardStateInterceptor","#removeChangesSubscription","#validateExistingDefaultParams","#validateState","#onTreeChanged","#validateSingleRouteDefaultParams","#getSchema","#walkTree"],"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/plugin.ts","../../src/validation.ts","../../src/factory.ts"],"sourcesContent":["// packages/search-schema-plugin/src/constants.ts\n\nexport const ERROR_PREFIX = \"[search-schema-plugin]\";\n","// packages/search-schema-plugin/src/helpers.ts\n\nimport type { StandardSchemaV1Issue } from \"./types\";\nimport type { Params } from \"@real-router/core\";\n\n/**\n * Extract top-level keys from validation issues.\n * Only processes issues with a non-empty path — issues without path\n * affect the whole object and can't be stripped by key.\n */\nexport function getInvalidKeys(\n issues: readonly StandardSchemaV1Issue[],\n): Set<string> {\n const keys = new Set<string>();\n\n for (const issue of issues) {\n if (issue.path && issue.path.length > 0) {\n const segment = issue.path[0];\n const key =\n typeof segment === \"object\" && \"key\" in segment ? segment.key : segment;\n\n keys.add(String(key));\n }\n }\n\n return keys;\n}\n\n/** Create a shallow copy of params without the specified keys. */\nexport function omitKeys(params: Params, keys: Set<string>): Params {\n const result: Params = {};\n\n for (const [key, value] of Object.entries(params)) {\n if (!keys.has(key)) {\n result[key] = value;\n }\n }\n\n return result;\n}\n","import { ERROR_PREFIX } from \"./constants\";\nimport { getInvalidKeys, omitKeys } from \"./helpers\";\n\nimport type {\n SearchSchemaPluginOptions,\n StandardSchemaV1,\n StandardSchemaV1Issue,\n} from \"./types\";\nimport type { Params, Plugin, TreeChangedEvent } from \"@real-router/core\";\nimport type { PluginApi, RoutesApi } from \"@real-router/core/api\";\n\nexport class SearchSchemaPlugin {\n readonly #pluginApi: PluginApi;\n readonly #routesApi: RoutesApi;\n readonly #mode: \"development\" | \"production\";\n readonly #strict: boolean;\n readonly #onError:\n | ((\n routeName: string,\n params: Params,\n issues: readonly StandardSchemaV1Issue[],\n ) => Params)\n | undefined;\n readonly #removeForwardStateInterceptor: () => void;\n readonly #removeChangesSubscription: () => void;\n\n constructor(\n pluginApi: PluginApi,\n routesApi: RoutesApi,\n options: SearchSchemaPluginOptions,\n ) {\n this.#pluginApi = pluginApi;\n this.#routesApi = routesApi;\n this.#mode = options.mode ?? \"development\";\n this.#strict = options.strict ?? false;\n this.#onError = options.onError;\n\n this.#validateExistingDefaultParams();\n\n this.#removeForwardStateInterceptor = this.#pluginApi.addInterceptor(\n \"forwardState\",\n (next, routeName, routeParams) => {\n const result = next(routeName, routeParams);\n\n return this.#validateState(result);\n },\n );\n\n // Dev-time defaultParams validation for runtime tree mutations. Replaces the\n // old `add` interceptor: TREE_CHANGED additionally covers `update` (changed\n // defaultParams) and `replace` (new route set) — the gap the interceptor\n // could not reach. Production mode skips the subscription entirely.\n this.#removeChangesSubscription =\n this.#mode === \"development\"\n ? this.#routesApi.subscribeChanges((event) => {\n this.#onTreeChanged(event);\n })\n : () => {};\n }\n\n getPlugin(): Plugin {\n return {\n teardown: () => {\n this.#removeForwardStateInterceptor();\n this.#removeChangesSubscription();\n },\n };\n }\n\n #onTreeChanged(event: TreeChangedEvent): void {\n switch (event.op) {\n case \"add\":\n case \"replace\": {\n // `added` is FLAT (full dotted names, descendants included).\n for (const route of event.added) {\n this.#validateSingleRouteDefaultParams(route.name);\n }\n\n break;\n }\n case \"update\": {\n // Only a defaultParams change can newly violate the schema.\n if (event.patch.defaultParams !== undefined) {\n this.#validateSingleRouteDefaultParams(event.name);\n }\n\n break;\n }\n // \"remove\" / \"clear\": the routes are gone — nothing to validate.\n }\n }\n\n #getSchema(routeName: string): StandardSchemaV1 | undefined {\n return this.#pluginApi.getRouteConfig(routeName)?.searchSchema as\n | StandardSchemaV1\n | undefined;\n }\n\n #validateState(result: { name: string; params: Params }): {\n name: string;\n params: Params;\n } {\n const schema = this.#getSchema(result.name);\n\n if (!schema) {\n return result;\n }\n\n const validation = schema[\"~standard\"].validate(result.params);\n\n if (validation instanceof Promise) {\n throw new TypeError(\n `${ERROR_PREFIX} Async schema validation is not supported. Route \"${result.name}\" returned a Promise from ~standard.validate().`,\n );\n }\n\n if (\"value\" in validation) {\n const params = this.#strict\n ? (validation.value as Params)\n : { ...result.params, ...(validation.value as Params) };\n\n return { ...result, params };\n }\n\n if (this.#onError) {\n return {\n ...result,\n params: this.#onError(result.name, result.params, validation.issues),\n };\n }\n\n if (this.#mode === \"development\") {\n console.error(\n `${ERROR_PREFIX} Route \"${result.name}\": invalid search params`,\n validation.issues,\n );\n }\n\n const invalidKeys = getInvalidKeys(validation.issues);\n const stripped = omitKeys(result.params, invalidKeys);\n const route = this.#routesApi.get(result.name);\n const defaults = route?.defaultParams;\n const restored = defaults ? { ...defaults, ...stripped } : stripped;\n\n return { ...result, params: restored };\n }\n\n #validateExistingDefaultParams(): void {\n if (this.#mode !== \"development\") {\n return;\n }\n\n const tree = this.#pluginApi.getTree() as unknown as\n | { fullName?: string; children?: ReadonlyMap<string, unknown> }\n | undefined;\n\n /* v8 ignore next -- @preserve: getTree() always returns a RouteTree, defensive check */\n if (!tree) {\n return;\n }\n\n this.#walkTree(tree);\n }\n\n #walkTree(node: {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n }): void {\n if (node.fullName) {\n this.#validateSingleRouteDefaultParams(node.fullName);\n }\n\n /* v8 ignore next 3 -- @preserve: children is always a Map in RouteTree */\n if (node.children instanceof Map) {\n for (const child of node.children.values()) {\n if (child && typeof child === \"object\") {\n this.#walkTree(\n child as {\n fullName?: string;\n children?: ReadonlyMap<string, unknown>;\n },\n );\n }\n }\n }\n }\n\n #validateSingleRouteDefaultParams(routeName: string): void {\n const schema = this.#getSchema(routeName);\n\n if (!schema) {\n return;\n }\n\n const route = this.#routesApi.get(routeName);\n const defaultParams = route?.defaultParams;\n\n if (!defaultParams) {\n return;\n }\n\n const validation = schema[\"~standard\"].validate(defaultParams);\n\n if (validation instanceof Promise) {\n return;\n }\n\n if (\"issues\" in validation) {\n console.warn(\n `${ERROR_PREFIX} Route \"${routeName}\": defaultParams do not pass searchSchema`,\n validation.issues,\n );\n }\n }\n}\n","import { ERROR_PREFIX } from \"./constants\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\n\nconst VALID_MODES = new Set([\"development\", \"production\"]);\n\nexport function validateOptions(options: SearchSchemaPluginOptions): void {\n if (options.mode !== undefined && !VALID_MODES.has(options.mode)) {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid mode: \"${options.mode}\". Must be \"development\" or \"production\".`,\n );\n }\n\n if (options.strict !== undefined && typeof options.strict !== \"boolean\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid strict option: expected boolean, got ${typeof options.strict}.`,\n );\n }\n\n if (options.onError !== undefined && typeof options.onError !== \"function\") {\n throw new TypeError(\n `${ERROR_PREFIX} Invalid onError: expected function, got ${typeof options.onError}.`,\n );\n }\n}\n","import { getPluginApi, getRoutesApi } from \"@real-router/core/api\";\n\nimport { SearchSchemaPlugin } from \"./plugin\";\nimport { validateOptions } from \"./validation\";\n\nimport type { SearchSchemaPluginOptions } from \"./types\";\nimport type { PluginFactory, Plugin } from \"@real-router/core\";\n\nexport function searchSchemaPlugin(\n options: SearchSchemaPluginOptions = {},\n): PluginFactory {\n validateOptions(options);\n\n const frozenOptions: SearchSchemaPluginOptions = Object.freeze({\n ...options,\n });\n\n return (router): Plugin => {\n const pluginApi = getPluginApi(router);\n const routesApi = getRoutesApi(router);\n const plugin = new SearchSchemaPlugin(pluginApi, routesApi, frozenOptions);\n\n return plugin.getPlugin();\n };\n}\n"],"mappings":"uEAEA,MAAa,EAAe,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R,CAEA,GAAkC,EAAyB,CACzD,IAAM,EAAS,KAAKD,GAAW,CAAS,EAExC,GAAI,CAAC,EACH,OAIF,IAAM,EADQ,KAAKV,GAAW,IAAI,CACR,CAAC,EAAE,cAE7B,GAAI,CAAC,EACH,OAGF,IAAM,EAAa,EAAO,YAAY,CAAC,SAAS,CAAa,EAEzD,aAAsB,SAItB,WAAY,GACd,QAAQ,KACN,GAAG,EAAa,UAAU,EAAU,2CACpC,EAAW,MACb,CAEJ,CACF,EClNA,MAAM,EAAc,IAAI,IAAI,CAAC,cAAe,YAAY,CAAC,EAEzD,SAAgB,EAAgB,EAA0C,CACxE,GAAI,EAAQ,OAAS,IAAA,IAAa,CAAC,EAAY,IAAI,EAAQ,IAAI,EAC7D,MAAU,UACR,GAAG,EAAa,kBAAkB,EAAQ,KAAK,0CACjD,EAGF,GAAI,EAAQ,SAAW,IAAA,IAAa,OAAO,EAAQ,QAAW,UAC5D,MAAU,UACR,GAAG,EAAa,gDAAgD,OAAO,EAAQ,OAAO,EACxF,EAGF,GAAI,EAAQ,UAAY,IAAA,IAAa,OAAO,EAAQ,SAAY,WAC9D,MAAU,UACR,GAAG,EAAa,2CAA2C,OAAO,EAAQ,QAAQ,EACpF,CAEJ,CChBA,SAAgB,EACd,EAAqC,CAAC,EACvB,CACf,EAAgB,CAAO,EAEvB,IAAM,EAA2C,OAAO,OAAO,CAC7D,GAAG,CACL,CAAC,EAED,MAAQ,IAKC,IAFY,EAFD,EAAa,CAEe,EAD5B,EAAa,CAC0B,EAAG,CAEhD,CAAC,CAAC,UAAU,CAE5B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@real-router/search-schema-plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
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.
|
|
48
|
+
"@real-router/core": "^0.58.0"
|
|
50
49
|
},
|
|
51
50
|
"scripts": {
|
|
52
51
|
"test": "vitest",
|
package/src/constants.ts
DELETED
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
|
-
}
|