exact-mirror 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2022 saltyAom
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # Exact Mirror
2
+
3
+ Enforce value to TypeBox/OpenAPI model
4
+
5
+ By providing model ahead of time, the library will generate a function to mirror a value to an exact type
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ # Using either one of the package manager
11
+ npm install exact-mirror
12
+ yarn add exact-mirror
13
+ pnpm add exact-mirror
14
+ bun add exact-mirror
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ It is designed to be used with [TypeBox](https://github.com/sinclairzx81/typebox) but an OpenAPI schema should also work.
20
+
21
+ ```typescript
22
+ import { Type as t } from '@sinclair/typebox'
23
+ import { createMirror } from 'exact-mirror'
24
+
25
+ const shape = t.Object({
26
+ name: t.String(),
27
+ id: t.Number()
28
+ })
29
+
30
+ const value = {
31
+ id: 0,
32
+ name: 'saltyaom',
33
+ // @ts-expect-error
34
+ shoudBeRemoved: true
35
+ } satisfies typeof shape.static
36
+
37
+ const mirror = createMirror(shape)
38
+
39
+ console.log(mirror(value)) // {"id":0,"name":"saltyaom"}
40
+ ```
package/bunfig.toml ADDED
@@ -0,0 +1,2 @@
1
+ [install]
2
+ registry = "https://registry.npmjs.org/"
@@ -0,0 +1,4 @@
1
+ import type { TAnySchema } from '@sinclair/typebox';
2
+ export declare const mergeObjectIntersection: (schema: TAnySchema) => TAnySchema;
3
+ export declare const createMirror: <T extends TAnySchema>(schema: T) => ((v: T["static"]) => T["static"]);
4
+ export default createMirror;
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createMirror: () => createMirror,
24
+ default: () => index_default,
25
+ mergeObjectIntersection: () => mergeObjectIntersection
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var Kind = Symbol.for("TypeBox.Kind");
29
+ var OptionalKind = Symbol.for("TypeBox.Optional");
30
+ var isSpecialProperty = (name) => /(\ |-|\t|\n)/.test(name);
31
+ var joinProperty = (v1, v2) => {
32
+ if (isSpecialProperty(v2)) return `${v1}["${v2}"]`;
33
+ return `${v1}.${v2}`;
34
+ };
35
+ var encodeProperty = (v) => isSpecialProperty(v) ? `"${v}"` : v;
36
+ var mergeObjectIntersection = (schema) => {
37
+ if (!schema.allOf || Kind in schema && (schema[Kind] !== "Intersect" || schema.type !== "object"))
38
+ return schema;
39
+ const { allOf, ...newSchema } = schema;
40
+ newSchema.properties = {};
41
+ if (Kind in newSchema) newSchema[Kind] = "Object";
42
+ for (const type of allOf) {
43
+ if (type.type !== "object") continue;
44
+ const { properties, required, type: _, [Kind]: __, ...rest } = type;
45
+ if (required)
46
+ newSchema.required = newSchema.required ? newSchema.required.concat(required) : required;
47
+ Object.assign(newSchema, rest);
48
+ for (const property in type.properties)
49
+ newSchema.properties[property] = mergeObjectIntersection(
50
+ type.properties[property]
51
+ );
52
+ }
53
+ return newSchema;
54
+ };
55
+ var mirror = (schema, property, instruction) => {
56
+ if (!schema) return "";
57
+ const isRoot = property === "v";
58
+ if (isRoot && schema.type !== "object" && schema.type !== "array")
59
+ return `return v`;
60
+ let v = "";
61
+ switch (schema.type) {
62
+ case "object":
63
+ schema = mergeObjectIntersection(schema);
64
+ v += "{";
65
+ if (schema.additionalProperties) v += `...${property}`;
66
+ const keys = Object.keys(schema.properties);
67
+ for (let i2 = 0; i2 < keys.length; i2++) {
68
+ const key = keys[i2];
69
+ const name = joinProperty(property, key);
70
+ if (!schema.required.includes(key)) {
71
+ const index = instruction.array;
72
+ if (property.startsWith("ar")) {
73
+ const array = instruction.optionalsInArray;
74
+ if (array[index]) array[index].push(name.slice(5));
75
+ else array[index] = [name.slice(5)];
76
+ } else {
77
+ instruction.optionals.push(name);
78
+ }
79
+ }
80
+ const child = schema.properties[key];
81
+ if (schema.additionalProperties && child.type !== "object")
82
+ continue;
83
+ if (i2 !== 0) v += ",";
84
+ v += `${encodeProperty(key)}:${mirror(child, name, instruction)}`;
85
+ }
86
+ v += "}";
87
+ break;
88
+ case "array":
89
+ const i = instruction.array;
90
+ instruction.array++;
91
+ if (schema.items.type !== "object" && schema.items.type !== "array") {
92
+ v = property;
93
+ break;
94
+ }
95
+ if (!isRoot) v = `(()=>{`;
96
+ v += `const ar${i}s=${property},ar${i}v=new Array(${property}.length);for(let i=0;i<ar${i}s.length;i++){const ar${i}p=ar${i}s[i];ar${i}v[i]=${mirror(schema.items, `ar${i}p`, instruction)};`;
97
+ const optionals = instruction.optionalsInArray[i + 1];
98
+ if (optionals) {
99
+ for (let oi = 0; oi < optionals.length; oi++) {
100
+ const key = `ar${i}v[i].${optionals[oi]}`;
101
+ if (oi !== 0) v += ";";
102
+ v += `if(${key}===undefined)delete ${key}`;
103
+ }
104
+ }
105
+ v += `}`;
106
+ if (!isRoot) v += `}return ar${i}v})()`;
107
+ break;
108
+ default:
109
+ v = property;
110
+ }
111
+ if (!isRoot) return v;
112
+ if (schema.type === "array") return `${v}return ar0v`;
113
+ v = `const x=${v}
114
+ `;
115
+ for (let i = 0; i < instruction.optionals.length; i++) {
116
+ const key = instruction.optionals[i];
117
+ v += `if(${key}===undefined)delete x${key.slice(1)}
118
+ `;
119
+ }
120
+ return `${v}return x`;
121
+ };
122
+ var createMirror = (schema) => {
123
+ const f = mirror(schema, "v", {
124
+ optionals: [],
125
+ optionalsInArray: [],
126
+ array: 0
127
+ });
128
+ return Function("v", f);
129
+ };
130
+ var index_default = createMirror;
131
+ // Annotate the CommonJS export names for ESM import in node:
132
+ 0 && (module.exports = {
133
+ createMirror,
134
+ mergeObjectIntersection
135
+ });
@@ -0,0 +1,4 @@
1
+ import type { TAnySchema } from '@sinclair/typebox';
2
+ export declare const mergeObjectIntersection: (schema: TAnySchema) => TAnySchema;
3
+ export declare const createMirror: <T extends TAnySchema>(schema: T) => ((v: T["static"]) => T["static"]);
4
+ export default createMirror;
package/dist/index.mjs ADDED
@@ -0,0 +1,109 @@
1
+ // src/index.ts
2
+ var Kind = Symbol.for("TypeBox.Kind");
3
+ var OptionalKind = Symbol.for("TypeBox.Optional");
4
+ var isSpecialProperty = (name) => /(\ |-|\t|\n)/.test(name);
5
+ var joinProperty = (v1, v2) => {
6
+ if (isSpecialProperty(v2)) return `${v1}["${v2}"]`;
7
+ return `${v1}.${v2}`;
8
+ };
9
+ var encodeProperty = (v) => isSpecialProperty(v) ? `"${v}"` : v;
10
+ var mergeObjectIntersection = (schema) => {
11
+ if (!schema.allOf || Kind in schema && (schema[Kind] !== "Intersect" || schema.type !== "object"))
12
+ return schema;
13
+ const { allOf, ...newSchema } = schema;
14
+ newSchema.properties = {};
15
+ if (Kind in newSchema) newSchema[Kind] = "Object";
16
+ for (const type of allOf) {
17
+ if (type.type !== "object") continue;
18
+ const { properties, required, type: _, [Kind]: __, ...rest } = type;
19
+ if (required)
20
+ newSchema.required = newSchema.required ? newSchema.required.concat(required) : required;
21
+ Object.assign(newSchema, rest);
22
+ for (const property in type.properties)
23
+ newSchema.properties[property] = mergeObjectIntersection(
24
+ type.properties[property]
25
+ );
26
+ }
27
+ return newSchema;
28
+ };
29
+ var mirror = (schema, property, instruction) => {
30
+ if (!schema) return "";
31
+ const isRoot = property === "v";
32
+ if (isRoot && schema.type !== "object" && schema.type !== "array")
33
+ return `return v`;
34
+ let v = "";
35
+ switch (schema.type) {
36
+ case "object":
37
+ schema = mergeObjectIntersection(schema);
38
+ v += "{";
39
+ if (schema.additionalProperties) v += `...${property}`;
40
+ const keys = Object.keys(schema.properties);
41
+ for (let i2 = 0; i2 < keys.length; i2++) {
42
+ const key = keys[i2];
43
+ const name = joinProperty(property, key);
44
+ if (!schema.required.includes(key)) {
45
+ const index = instruction.array;
46
+ if (property.startsWith("ar")) {
47
+ const array = instruction.optionalsInArray;
48
+ if (array[index]) array[index].push(name.slice(5));
49
+ else array[index] = [name.slice(5)];
50
+ } else {
51
+ instruction.optionals.push(name);
52
+ }
53
+ }
54
+ const child = schema.properties[key];
55
+ if (schema.additionalProperties && child.type !== "object")
56
+ continue;
57
+ if (i2 !== 0) v += ",";
58
+ v += `${encodeProperty(key)}:${mirror(child, name, instruction)}`;
59
+ }
60
+ v += "}";
61
+ break;
62
+ case "array":
63
+ const i = instruction.array;
64
+ instruction.array++;
65
+ if (schema.items.type !== "object" && schema.items.type !== "array") {
66
+ v = property;
67
+ break;
68
+ }
69
+ if (!isRoot) v = `(()=>{`;
70
+ v += `const ar${i}s=${property},ar${i}v=new Array(${property}.length);for(let i=0;i<ar${i}s.length;i++){const ar${i}p=ar${i}s[i];ar${i}v[i]=${mirror(schema.items, `ar${i}p`, instruction)};`;
71
+ const optionals = instruction.optionalsInArray[i + 1];
72
+ if (optionals) {
73
+ for (let oi = 0; oi < optionals.length; oi++) {
74
+ const key = `ar${i}v[i].${optionals[oi]}`;
75
+ if (oi !== 0) v += ";";
76
+ v += `if(${key}===undefined)delete ${key}`;
77
+ }
78
+ }
79
+ v += `}`;
80
+ if (!isRoot) v += `}return ar${i}v})()`;
81
+ break;
82
+ default:
83
+ v = property;
84
+ }
85
+ if (!isRoot) return v;
86
+ if (schema.type === "array") return `${v}return ar0v`;
87
+ v = `const x=${v}
88
+ `;
89
+ for (let i = 0; i < instruction.optionals.length; i++) {
90
+ const key = instruction.optionals[i];
91
+ v += `if(${key}===undefined)delete x${key.slice(1)}
92
+ `;
93
+ }
94
+ return `${v}return x`;
95
+ };
96
+ var createMirror = (schema) => {
97
+ const f = mirror(schema, "v", {
98
+ optionals: [],
99
+ optionalsInArray: [],
100
+ array: 0
101
+ });
102
+ return Function("v", f);
103
+ };
104
+ var index_default = createMirror;
105
+ export {
106
+ createMirror,
107
+ index_default as default,
108
+ mergeObjectIntersection
109
+ };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "exact-mirror",
3
+ "version": "0.0.0",
4
+ "description": "Mirror exact value to TypeBox/OpenAPI model",
5
+ "license": "MIT",
6
+ "scripts": {
7
+ "dev": "bun run --watch example/index.ts",
8
+ "test": "bun test && npm run test:node",
9
+ "test:node": "npm install --prefix ./test/node/cjs/ && npm install --prefix ./test/node/esm/ && node ./test/node/cjs/index.js && node ./test/node/esm/index.js",
10
+ "build": "bun build.ts",
11
+ "release": "npm run build && npm run test && npm publish --access public"
12
+ },
13
+ "peerDependencies": {
14
+ "@sinclair/typebox": "^0.34.15"
15
+ },
16
+ "peerDependenciesMeta": {
17
+ "@sinclair/typebox": {
18
+ "optional": true
19
+ }
20
+ },
21
+ "devDependencies": {
22
+ "@types/bun": "1.2.2",
23
+ "elysia": "^1.2.11",
24
+ "eslint": "9.6.0",
25
+ "mitata": "^1.0.33",
26
+ "tsup": "^8.1.0",
27
+ "tsx": "^4.19.2",
28
+ "typescript": "^5.5.3"
29
+ },
30
+ "main": "./dist/cjs/index.js",
31
+ "module": "./dist/index.mjs",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ "./package.json": "./package.json",
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "import": "./dist/index.mjs",
38
+ "require": "./dist/cjs/index.js"
39
+ }
40
+ },
41
+ "keywords": [
42
+ "elysia",
43
+ "exact",
44
+ "mirror",
45
+ "typebox"
46
+ ],
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/elysiajs/exact-mirror"
50
+ },
51
+ "author": {
52
+ "name": "saltyAom",
53
+ "url": "https://github.com/SaltyAom",
54
+ "email": "saltyaom@gmail.com"
55
+ },
56
+ "homepage": "https://github.com/elysiajs/exact-mirror",
57
+ "bugs": "https://github.com/elysiajs/exact-mirror/issues"
58
+ }