-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 03a39c7
Showing
202 changed files
with
13,896 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
root = true | ||
|
||
[*] | ||
end_of_line = lf | ||
insert_final_newline = true | ||
charset = utf-8 | ||
|
||
[*.{ts,tsx,coffee,less,htm,html,cc,h,sh,ejs,java,json}] | ||
indent_style = space | ||
indent_size = 2 | ||
trim_trailing_whitespace = true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"parser": "@typescript-eslint/parser", | ||
"plugins": ["@typescript-eslint"], | ||
"extends": [ | ||
"eslint:recommended", | ||
"plugin:@typescript-eslint/eslint-recommended", | ||
"plugin:@typescript-eslint/recommended", | ||
"prettier", | ||
"prettier/@typescript-eslint" | ||
], | ||
"rules": { | ||
"@typescript-eslint/interface-name-prefix": ["error", "always"], | ||
"@typescript-eslint/no-parameter-properties": "off", | ||
"@typescript-eslint/explicit-function-return-type": "off" | ||
}, | ||
"overrides": [ | ||
{ | ||
"files": "*.output.ts", | ||
"rules": { | ||
"@typescript-eslint/camelcase": "off", | ||
"@typescript-eslint/no-explicit-any": "off" | ||
} | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
node_modules | ||
yarn-error.log | ||
coverage | ||
dist |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
{ | ||
"version": "0.2.0", | ||
"configurations": [ | ||
{ | ||
"name": "Current TS File", | ||
"type": "node", | ||
"request": "launch", | ||
"args": ["${relativeFile}"], | ||
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"], | ||
"sourceMaps": true, | ||
"cwd": "${workspaceRoot}", | ||
"protocol": "inspector" | ||
}, | ||
{ | ||
"type": "node", | ||
"request": "launch", | ||
"name": "Jest All", | ||
"program": "${workspaceFolder}/node_modules/.bin/jest", | ||
"args": ["--runInBand"], | ||
"console": "integratedTerminal", | ||
"internalConsoleOptions": "neverOpen", | ||
"disableOptimisticBPs": true, | ||
"windows": { | ||
"program": "${workspaceFolder}/node_modules/jest/bin/jest" | ||
} | ||
}, | ||
{ | ||
"type": "node", | ||
"request": "launch", | ||
"name": "Jest Current File", | ||
"program": "${workspaceFolder}/node_modules/.bin/jest", | ||
"args": ["${file}", "--config", "jest.config.js"], | ||
"console": "integratedTerminal", | ||
"internalConsoleOptions": "neverOpen", | ||
"disableOptimisticBPs": true, | ||
"windows": { | ||
"program": "${workspaceFolder}/node_modules/jest/bin/jest" | ||
} | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{ | ||
"editor.formatOnSave": true, | ||
"eslint.validate": [ | ||
"javascript", | ||
"javascriptreact", | ||
"typescript", | ||
"typescriptreact" | ||
], | ||
"eslint.enable": true, | ||
"typescript.tsdk": "node_modules/typescript/lib" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
# tserial | ||
|
||
Runtime deserialization for TypeScript interfaces and type aliases | ||
|
||
## Table of Contents | ||
|
||
- [Overview](#overview) | ||
- [Design Goals](#design-goals) | ||
- [Installation](#installation) | ||
- [Usage](#usage) | ||
|
||
## Overview | ||
|
||
[Read the blog post for a high level summary](https://lukeautry.com/blog/tserial) | ||
|
||
TypeScript's structural typing system offers a powerful way to represent the shape of data. Data delivered across system is, by default, not validated. A developer version can use type assertions to "cast" untrusted input to the intended type, but this is insecure and incorrect. The developer should write code that validates input data and coerces it to the right type. | ||
|
||
`tserial` automates this process and offers the developer a way to securely deserialize data at runtime. | ||
|
||
## Design Goals | ||
|
||
- Should use plain TypeScript expressions as the source of truth (no DSLs or codecs) | ||
- Should define a subset of type expressions that represent serializable data. Expressions involving functions (classes, function declarations and expressions, etc) will not be permitted. | ||
- Should offer consumers a way to opt-in to interfaces/type aliases they would like to be validated at runtime | ||
- Should generate a single file with a deserialization routine | ||
- Should have no runtime dependencies | ||
- Should have minimal build time dependencies | ||
- Deserialization routine should use composable assertions and type guards which incrementally prove adherence to a type expression via narrowing | ||
- Hedges against "stale" output since compiler will usually raise errors when narrowing produces an incomplete type | ||
- Deserialization routine must produce granular error data; if data isn't valid, useful, structured error data should be returned to the caller | ||
- Node.js, browser, and [deno](https://github.com/denoland/deno) support | ||
|
||
## Installation | ||
|
||
NOTE: This is not yet published on NPM | ||
|
||
```sh | ||
npm install tserial --save-dev | ||
|
||
yarn add tserial --dev | ||
``` | ||
|
||
## Usage | ||
|
||
The CLI and Node API use the same underlying modules. Both generate file content. The CLI takes care of writing the file to the file system, while the Node API just returns string content. | ||
|
||
In either mode, it's highly recommended to use a formatter like [prettier](https://prettier.io) to format the generated code. No attempt has been made to autogenerate well-formatted code. | ||
|
||
### CLI | ||
|
||
```sh | ||
# all options | ||
tserial --help | ||
|
||
# minimal command, use tsconfig.json at project root and default tag identifier | ||
tserial --out ./path/to/generated_file.ts | ||
|
||
# custom tsconfig | ||
tserial --out ./path/to/generated_file.ts --tsconfig some-custom-tsconfig.json | ||
|
||
# custom tag name (defaults to serializable) | ||
# custom tsconfig | ||
tserial --out ./path/to/generated_file.ts --tag myCustomTag | ||
|
||
# deno imports | ||
tserial --out ./path/to/generated_file.ts --deno | ||
``` | ||
|
||
### Node API | ||
|
||
The best documentation is the source code itself. Check out [this file](test/render/render-content.ts) for an example of how the test suite calls the Node API. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { promises as fs } from "fs"; | ||
import { resolve } from "path"; | ||
|
||
export const getFiles = async (dir: string): Promise<string[]> => { | ||
const dirents = await fs.readdir(dir, { withFileTypes: true }); | ||
const files = await Promise.all( | ||
dirents.map(async dirent => { | ||
const res = resolve(dir, dirent.name); | ||
return dirent.isDirectory() ? getFiles(res) : res; | ||
}) | ||
); | ||
|
||
return Array.prototype.concat(...files); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
export const matchAll = (pattern: RegExp, str: string) => { | ||
const matches = new Array<RegExpExecArray>(); | ||
|
||
let groups = pattern.exec(str); | ||
while (groups) { | ||
matches.push(groups); | ||
groups = pattern.exec(str); | ||
} | ||
|
||
return matches; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import { promises as fs } from "fs"; | ||
import { getFiles } from "./common/get-files"; | ||
import { basename } from "path"; | ||
import { matchAll } from "./common/match-all"; | ||
import prettier from "prettier"; | ||
|
||
type SnippetOutput = Record<string, ISnippet>; | ||
|
||
interface ISnippet { | ||
content: string; | ||
dependencies: string[]; | ||
} | ||
|
||
(async () => { | ||
const files = await getFiles("./src/assertions"); | ||
|
||
const output: SnippetOutput = {}; | ||
|
||
for (const file of files) { | ||
const content = (await fs.readFile(file)).toString(); | ||
const importPattern = /import { (?:.)* } from "\.\/(.+)";/g; | ||
|
||
const matches = matchAll(importPattern, content); | ||
const dependencies = new Array<string>(); | ||
matches.forEach(match => { | ||
dependencies.push(match[1]); | ||
}); | ||
|
||
output[basename(file).replace(".ts", "")] = { | ||
content: content | ||
.replace(importPattern, "") | ||
.trim() | ||
.replace(/export /g, ""), | ||
dependencies | ||
}; | ||
} | ||
|
||
await fs.writeFile( | ||
"./src/render/snippets.ts", | ||
prettier.format( | ||
` | ||
/* | ||
* Autogenerated by ${basename(__filename)} | ||
*/ | ||
export const snippets = ${JSON.stringify(output, null, 2)}; | ||
`, | ||
{ parser: "typescript" } | ||
) | ||
); | ||
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
// eslint-disable-next-line | ||
module.exports = { | ||
testEnvironment: "node", | ||
transform: { | ||
"^.+\\.tsx?$": "ts-jest" | ||
}, | ||
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], | ||
testRegex: "(/__test__/.*|(\\.|/)(spec))\\.(ts|js)x?$", | ||
coverageDirectory: "coverage", | ||
collectCoverageFrom: ["src/**/*.{ts,tsx,js,jsx}", "!src/**/*.d.ts"] | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
{ | ||
"name": "tserial", | ||
"version": "1.0.0", | ||
"description": "Runtime validation for TypeScript type expressions", | ||
"license": "MIT", | ||
"main": "./dist/index.js", | ||
"typings": "./dist/index.d.ts", | ||
"scripts": { | ||
"test": "jest", | ||
"test:full": "yarn snippets && yarn test:render && yarn test", | ||
"coverage": "jest --coverage", | ||
"watch": "tsc --watch --noEmit", | ||
"typecheck": "tsc --noEmit", | ||
"test:render": "ts-node ./test/render/render-content.ts", | ||
"snippets": "ts-node ./dev/generate-assertion-snippets.ts", | ||
"build": "yarn snippets && tsc -p tsconfig.build.json", | ||
"clean": "rm -rf ./dist", | ||
"cli": "ts-node ./src/cli/index.ts" | ||
}, | ||
"bin": { | ||
"tserial": "dist/cli/index.js" | ||
}, | ||
"files": [ | ||
"/dist" | ||
], | ||
"dependencies": { | ||
"typescript": "^3.6.4" | ||
}, | ||
"devDependencies": { | ||
"@types/jest": "^24.0.18", | ||
"@types/node": "^12.7.12", | ||
"@types/prettier": "^1.18.3", | ||
"@typescript-eslint/eslint-plugin": "^2.3.3", | ||
"@typescript-eslint/parser": "^2.3.3", | ||
"@typescript-eslint/typescript-estree": "^2.3.3", | ||
"eslint": "^6.5.1", | ||
"eslint-config-prettier": "^6.4.0", | ||
"jest": "^24.9.0", | ||
"jest-codemods": "^0.20.0", | ||
"prettier": "^1.18.2", | ||
"ts-jest": "^24.1.0", | ||
"ts-node": "^8.4.1" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { Result, Expected } from "./result"; | ||
import { success } from "./success"; | ||
import { isArray } from "./array"; | ||
import { error } from "./error"; | ||
|
||
type ArrayScanResult<T> = IArrayScanSuccess<T> | Expected; | ||
|
||
interface IArrayScanSuccess<T> { | ||
kind: "success"; | ||
values: T[]; | ||
} | ||
|
||
const scanArrayForType = <T>( | ||
values: unknown[], | ||
fn: (ele: unknown) => Result<T> | ||
): ArrayScanResult<T> => { | ||
for (let index = 0; index < values.length; index++) { | ||
const result = fn(values[index]); | ||
if (!result.success) { | ||
return error("keyed", { | ||
key: `[${index}]`, | ||
value: result | ||
}); | ||
} | ||
} | ||
|
||
return { kind: "success", values: values as T[] }; | ||
}; | ||
|
||
export const assertArrayOfType = <T>( | ||
value: unknown, | ||
fn: (ele: unknown) => Result<T> | ||
): Result<T[]> => { | ||
if (isArray(value)) { | ||
const scanResult = scanArrayForType(value, fn); | ||
if (scanResult.kind === "success") { | ||
return success(scanResult.values); | ||
} else { | ||
return scanResult; | ||
} | ||
} else { | ||
return error("single", { value: "array" }); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export const isArray = (value: unknown): value is unknown[] => | ||
Array.isArray(value); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { Result } from "./result"; | ||
import { success } from "./success"; | ||
import { error } from "./error"; | ||
|
||
export const isBoolean = (value: unknown): value is boolean => | ||
typeof value === "boolean"; | ||
|
||
export const assertBoolean = (value: unknown): Result<boolean> => | ||
isBoolean(value) ? success(value) : error("single", { value: "boolean" }); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { IExpectedTypes } from "./result"; | ||
|
||
export const error = <K extends keyof IExpectedTypes>( | ||
kind: K, | ||
value: Omit<IExpectedTypes[K], "success" | "kind"> | ||
): IExpectedTypes[K] => | ||
(({ | ||
success: false, | ||
kind, | ||
...value | ||
} as unknown) as IExpectedTypes[K]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { Result } from "./result"; | ||
import { success } from "./success"; | ||
import { error } from "./error"; | ||
|
||
export const isFalse = (value: unknown): value is false => value === false; | ||
|
||
export const assertFalse = (value: unknown): Result<false> => | ||
isFalse(value) ? success(value) : error("single", { value: false }); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export const hasKey = <O extends {}, K extends string>( | ||
value: O, | ||
key: K | ||
): value is O & Record<K, unknown> => key in value; |
Oops, something went wrong.