├── .nvmrc ├── .eslintignore ├── test ├── index.ts ├── env.ts ├── tsconfig.json └── setup-window-mock.ts ├── .DS_Store ├── scripts ├── hooks │ └── pre-push.sh └── ensure-deduplicate.sh ├── tsconfig.spec.json ├── src ├── math.spec.ts ├── math.ts ├── index.html ├── framework │ ├── effects │ │ ├── log-with.ts │ │ └── process-env.ts │ ├── context │ │ └── safe-context.tsx │ └── adt │ │ └── variant.ts ├── contexts │ └── start-app-env.ts ├── App.spec.tsx ├── core │ ├── environment.ts │ └── short-report.ts ├── App.tsx ├── index.tsx └── auth │ └── SignIn.tsx ├── webpack ├── tsconfig.json ├── webpack.prod.ts ├── webpack.dev.ts └── webpack.common.ts ├── jest.config.js ├── README.md ├── prettier.config.js ├── Dockerfile ├── public └── env.js ├── .vscode └── settings.json ├── entrypoint.sh ├── .github └── workflows │ └── main.yml ├── LICENSE ├── .gitignore ├── .eslintrc.js ├── nginx.conf ├── package.json └── tsconfig.json /.nvmrc: -------------------------------------------------------------------------------- 1 | 12.16 -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | *.js -------------------------------------------------------------------------------- /test/index.ts: -------------------------------------------------------------------------------- 1 | import './env' 2 | import './setup-window-mock' 3 | -------------------------------------------------------------------------------- /test/env.ts: -------------------------------------------------------------------------------- 1 | import * as dotenv from 'dotenv' 2 | 3 | dotenv.config() 4 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stouffi/typescript-react-starter/HEAD/.DS_Store -------------------------------------------------------------------------------- /scripts/hooks/pre-push.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | if ! yarn check --integrity 3 | then 4 | yarn 5 | fi -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "CommonJS" 5 | }, 6 | "exclude": [] 7 | } 8 | -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.spec.json", 3 | "compilerOptions": { 4 | "rootDir": "." 5 | }, 6 | "include": ["**/*.ts"] 7 | } 8 | -------------------------------------------------------------------------------- /src/math.spec.ts: -------------------------------------------------------------------------------- 1 | import { add } from './math' 2 | 3 | describe('Math', () => { 4 | test('add', () => { 5 | expect(add(1)(2)).toBe(3) 6 | expect(add(-1)(1)).toBe(0) 7 | }) 8 | }) 9 | -------------------------------------------------------------------------------- /src/math.ts: -------------------------------------------------------------------------------- 1 | export const add = (a: number) => (b: number) => a + b 2 | 3 | // multiply is not used and will not be included in the production build 4 | export const multiply = (a: number) => (b: number) => a * b 5 | -------------------------------------------------------------------------------- /webpack/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "module": "commonjs", 6 | "target": "es5" 7 | }, 8 | "include": ["webpack.*.ts"] 9 | } 10 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | TypeScript React Starter 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /webpack/webpack.prod.ts: -------------------------------------------------------------------------------- 1 | import { Configuration } from 'webpack' 2 | import * as merge from 'webpack-merge' 3 | import common from './webpack.common' 4 | 5 | const config: Configuration = merge(common, { 6 | mode: 'production', 7 | devtool: 'source-map' 8 | }) 9 | export default config 10 | -------------------------------------------------------------------------------- /scripts/ensure-deduplicate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | if yarn yarn-deduplicate -fl 3 | then 4 | echo "INFO: No duplicates found. Pursuing..." 5 | else 6 | echo "INFO: Lockfile contains duplicates! deduplicating..." 7 | yarn yarn-deduplicate 8 | echo "INFO: Lockfile deduplicated. Reinstalling..." 9 | yarn 10 | fi -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest/presets/js-with-babel', 3 | transformIgnorePatterns: ['node_modules/(?!fp-ts)'], 4 | setupFiles: ['./test/index.ts'], 5 | globals: { 6 | _env: {}, 7 | 'ts-jest': { 8 | tsConfig: './tsconfig.spec.json' 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Typescript React Starter 2 | 3 | With fp-ts ecosystem 4 | 5 | ## Setup 6 | 7 | ``` 8 | yarn 9 | ``` 10 | 11 | ## Development 12 | 13 | ``` 14 | yarn start 15 | ``` 16 | 17 | ## Test 18 | 19 | ``` 20 | yarn test 21 | ``` 22 | 23 | ## Production build 24 | 25 | ``` 26 | yarn build 27 | ``` 28 | -------------------------------------------------------------------------------- /src/framework/effects/log-with.ts: -------------------------------------------------------------------------------- 1 | import { effect } from '@matechs/effect' 2 | 3 | export interface Logger { 4 | log: (s: string, ...args: unknown[]) => effect.Effect 5 | } 6 | 7 | export const logWith = (message: string) => 8 | effect.chainTap(a => effect.accessM(({ log }: Logger) => log(message, a))) 9 | -------------------------------------------------------------------------------- /src/framework/effects/process-env.ts: -------------------------------------------------------------------------------- 1 | import { effect } from '@matechs/effect' 2 | import { Decoder } from 'io-ts' 3 | 4 | export interface Env { 5 | env: NodeJS.ProcessEnv 6 | } 7 | 8 | export const fromDecoder = (decoder: Decoder) => 9 | effect.accessM(({ env }: Env) => effect.fromEither(decoder.decode(env))) 10 | -------------------------------------------------------------------------------- /webpack/webpack.dev.ts: -------------------------------------------------------------------------------- 1 | import { Configuration } from 'webpack' 2 | import * as merge from 'webpack-merge' 3 | import common from './webpack.common' 4 | 5 | const config: Configuration = merge(common, { 6 | mode: 'development', 7 | devtool: 'inline-source-map', 8 | devServer: { 9 | contentBase: './public' 10 | } 11 | }) 12 | export default config 13 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | printWidth: 100, 3 | semi: false, 4 | singleQuote: true, 5 | proseWrap: 'preserve', 6 | useTabs: false, 7 | tabWidth: 2, 8 | trailingComma: 'none', 9 | jsxBracketSameLine: false, 10 | arrowParens: 'avoid', 11 | bracketSpacing: true, 12 | cursorOffset: -1, 13 | insertPragma: false, 14 | requirePragma: false 15 | } 16 | -------------------------------------------------------------------------------- /src/contexts/start-app-env.ts: -------------------------------------------------------------------------------- 1 | import { option } from 'fp-ts' 2 | import * as React from 'react' 3 | import { withContextGuard } from '../framework/context/safe-context' 4 | 5 | export interface StartAppEnv { 6 | auth: firebase.auth.Auth 7 | } 8 | 9 | export const StartAppEnvContext = React.createContext>(option.none) 10 | 11 | export const withStartAppEnvGuard = withContextGuard(StartAppEnvContext) 12 | -------------------------------------------------------------------------------- /test/setup-window-mock.ts: -------------------------------------------------------------------------------- 1 | Object.defineProperty(window, 'matchMedia', { 2 | writable: true, 3 | value: jest.fn().mockImplementation(query => ({ 4 | matches: false, 5 | media: query, 6 | onchange: null, 7 | addListener: jest.fn(), // deprecated 8 | removeListener: jest.fn(), // deprecated 9 | addEventListener: jest.fn(), 10 | removeEventListener: jest.fn(), 11 | dispatchEvent: jest.fn() 12 | })) 13 | }) 14 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx:stable-alpine 2 | 3 | RUN apk add --update coreutils 4 | 5 | RUN apk add --no-cache nodejs yarn 6 | 7 | RUN yarn global add @beam-australia/react-env 8 | 9 | ADD nginx.conf /etc/nginx/nginx.conf.template 10 | 11 | ADD entrypoint.sh /var/entrypoint.sh 12 | 13 | ENTRYPOINT ["/var/entrypoint.sh"] 14 | 15 | CMD ["nginx", "-g", "daemon off;"] 16 | 17 | WORKDIR /var/www 18 | 19 | ADD dist /var/www 20 | 21 | COPY .env* /var/www/ 22 | -------------------------------------------------------------------------------- /public/env.js: -------------------------------------------------------------------------------- 1 | window._env = {"NODE_ENV":"development","REACT_APP_FIREBASE_apiKey":"AIzaSyD5-cANw7k205X94_f_WBi2-Uh_0Fte2ek","REACT_APP_FIREBASE_authDomain":"family-bf4d0.firebaseapp.com","REACT_APP_FIREBASE_databaseURL":"https://family-bf4d0.firebaseio.com","REACT_APP_FIREBASE_projectId":"family-bf4d0","REACT_APP_FIREBASE_storageBucket":"family-bf4d0.appspot.com","REACT_APP_FIREBASE_messagingSenderId":"883756894820","REACT_APP_FIREBASE_appId":"1:883756894820:web:5b2e311d7705376dc7ad71"}; -------------------------------------------------------------------------------- /src/framework/context/safe-context.tsx: -------------------------------------------------------------------------------- 1 | import { option, pipeable as p } from 'fp-ts' 2 | import * as React from 'react' 3 | 4 | export const withContextGuard = (Context: React.Context>) => < 5 | CP extends object 6 | >( 7 | f: (c: C) => CP 8 | ) =>

(Wrapped: React.FC

): React.FC

=> props => 9 | p.pipe( 10 | React.useContext(Context), 11 | option.map(c => ), 12 | option.toNullable 13 | ) 14 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.codeActionsOnSave": { 4 | "source.organizeImports": true, 5 | "source.fixAll.eslint": true 6 | }, 7 | "typescript.tsdk": "node_modules/typescript/lib", 8 | "eslint.validate": ["typescript", "typescriptreact"], 9 | "[typescript]": { 10 | "editor.formatOnSave": false 11 | }, 12 | "[typescriptreact]": { 13 | "editor.formatOnSave": false 14 | }, 15 | "npm.packageManager": "yarn", 16 | "eslint.packageManager": "yarn" 17 | } 18 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -eu 4 | 5 | echo "Serializing environment:" 6 | 7 | react-env --dest . 8 | 9 | envs=$(cat env.js) 10 | 11 | echo "$envs" 12 | 13 | # save content of env.js as it will be removed. 14 | subs="data:text/javascript;base64,$(base64 -w 0 env.js)" 15 | 16 | echo "$subs" 17 | 18 | rm env.js 19 | 20 | # cat /var/www/index.html 21 | 22 | # Substitute the script with src by an equivalent inline script. 23 | sed -i "s|||" /var/www/index.html 24 | 25 | # echo 'After substitution' 26 | # cat /var/www/index.html 27 | 28 | test -n "$PORT" 29 | 30 | envsubst "\$PORT" < /etc/nginx/nginx.conf.template > /etc/nginx/nginx.conf 31 | 32 | exec "$@" 33 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - name: Get yarn cache directory path 11 | id: yarn-cache-dir-path 12 | run: echo "::set-output name=dir::$(yarn cache dir)" 13 | - uses: actions/cache@v1 14 | id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`) 15 | with: 16 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 17 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 18 | restore-keys: | 19 | ${{ runner.os }}-yarn- 20 | - name: Install dependencies 21 | run: yarn --frozen-lockfile 22 | - name: Test 23 | run: yarn test-ci 24 | - name: Build 25 | run: yarn build 26 | -------------------------------------------------------------------------------- /src/framework/adt/variant.ts: -------------------------------------------------------------------------------- 1 | import { AsOpaque } from 'morphic-ts/lib/batteries/interpreters-BAST' 2 | import { summon } from 'morphic-ts/lib/batteries/summoner' 3 | import { AType, EType } from 'morphic-ts/lib/usage/utils' 4 | 5 | const Nothing_ = summon(F => 6 | F.interface( 7 | { 8 | type: F.stringLiteral('Nothing') 9 | }, 10 | 'Nothing' 11 | ) 12 | ) 13 | export interface Nothing extends AType {} 14 | export interface NothingRaw extends EType {} 15 | export const Nothing = AsOpaque(Nothing_) 16 | 17 | const Waiting_ = summon(F => 18 | F.interface( 19 | { 20 | type: F.stringLiteral('Waiting') 21 | }, 22 | 'Waiting' 23 | ) 24 | ) 25 | export interface Waiting extends AType {} 26 | export interface WaitingRaw extends EType {} 27 | export const Waiting = AsOpaque(Waiting_) 28 | -------------------------------------------------------------------------------- /src/App.spec.tsx: -------------------------------------------------------------------------------- 1 | import { render } from '@testing-library/react' 2 | import * as firebase from 'firebase' 3 | import 'firebase/auth' 4 | import { constNull } from 'fp-ts/lib/function' 5 | import * as React from 'react' 6 | import { App } from './App' 7 | import { SignInContext } from './auth/SignIn' 8 | 9 | jest.mock('./auth/SignIn', () => ({ SignInContext: jest.fn(constNull) })) 10 | 11 | describe('App', () => { 12 | // Test is skipped because not api keys are available on the starter repo 13 | test.skip('mount', () => { 14 | firebase.initializeApp({ apiKey: process.env.REACT_APP_FIREBASE_apiKey }) 15 | const auth = firebase.auth() 16 | const spy = jest.spyOn(auth, 'onAuthStateChanged') 17 | // Implemented as immediately signed out 18 | spy.mockImplementation(nextOrObserver => 19 | typeof nextOrObserver === 'function' ? nextOrObserver(null as any) : nextOrObserver.next(null) 20 | ) 21 | render() 22 | expect(SignInContext).toHaveBeenCalled() 23 | spy.mockRestore() 24 | }) 25 | }) 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Stephane Le Baron 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. -------------------------------------------------------------------------------- /webpack/webpack.common.ts: -------------------------------------------------------------------------------- 1 | import { CleanWebpackPlugin } from 'clean-webpack-plugin' 2 | import * as ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin' 3 | import * as HtmlWebpackPlugin from 'html-webpack-plugin' 4 | import * as path from 'path' 5 | import * as webpack from 'webpack' 6 | 7 | const config: webpack.Configuration = { 8 | entry: './src/index.tsx', 9 | devtool: 'inline-source-map', 10 | module: { 11 | rules: [ 12 | { 13 | test: /\.tsx?$/, 14 | loader: 'ts-loader', 15 | options: { 16 | transpileOnly: true 17 | }, 18 | exclude: /node_modules/ 19 | }, 20 | { 21 | test: /\.css$/i, 22 | use: ['style-loader', 'css-loader'] 23 | } 24 | ] 25 | }, 26 | resolve: { 27 | extensions: ['.tsx', '.ts', '.js'] 28 | }, 29 | output: { 30 | filename: 'bundle.js', 31 | path: path.resolve(__dirname, '..', 'dist') 32 | }, 33 | plugins: [ 34 | new CleanWebpackPlugin(), 35 | new ForkTsCheckerWebpackPlugin({ eslint: true }), 36 | new HtmlWebpackPlugin({ template: './src/index.html' }) 37 | ] 38 | } 39 | 40 | export default config 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Workspace 2 | dist 3 | 4 | # Logs 5 | logs 6 | *.log 7 | npm-debug.log* 8 | yarn-debug.log* 9 | yarn-error.log* 10 | 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | 17 | # Directory for instrumented libs generated by jscoverage/JSCover 18 | lib-cov 19 | 20 | # Coverage directory used by tools like istanbul 21 | coverage 22 | 23 | # nyc test coverage 24 | .nyc_output 25 | 26 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 27 | .grunt 28 | 29 | # Bower dependency directory (https://bower.io/) 30 | bower_components 31 | 32 | # node-waf configuration 33 | .lock-wscript 34 | 35 | # Compiled binary addons (https://nodejs.org/api/addons.html) 36 | build/Release 37 | 38 | # Dependency directories 39 | node_modules/ 40 | jspm_packages/ 41 | 42 | # TypeScript v1 declaration files 43 | typings/ 44 | 45 | # Optional npm cache directory 46 | .npm 47 | 48 | # Optional eslint cache 49 | .eslintcache 50 | 51 | # Optional REPL history 52 | .node_repl_history 53 | 54 | # Output of 'npm pack' 55 | *.tgz 56 | 57 | # Yarn Integrity file 58 | .yarn-integrity 59 | 60 | # dotenv environment variables file 61 | .env 62 | 63 | # next.js build output 64 | .next 65 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', // Specifies the ESLint parser 3 | extends: [ 4 | 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin 5 | 'plugin:@typescript-eslint/recommended-requiring-type-checking', 6 | 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier 7 | 'plugin:prettier/recommended' // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. 8 | ], 9 | parserOptions: { 10 | ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features 11 | sourceType: 'module', // Allows for the use of imports 12 | project: ['./tsconfig.json', 'webpack/tsconfig.json', 'test/tsconfig.json'] 13 | }, 14 | plugins: ['prefer-arrow'], 15 | rules: { 16 | // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs 17 | '@typescript-eslint/explicit-function-return-type': 0, 18 | '@typescript-eslint/no-unused-vars': 0, 19 | '@typescript-eslint/no-empty-interface': [1, { allowSingleExtends: true }], 20 | '@typescript-eslint/no-explicit-any': 0, 21 | 'prefer-arrow/prefer-arrow-functions': 1, 22 | 'arrow-body-style': [1, 'as-needed'], 23 | 'prettier/prettier': 1 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/core/environment.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/camelcase */ 2 | import { effect } from '@matechs/effect' 3 | import { function as f, pipeable as p } from 'fp-ts' 4 | import { AsOpaque, summon } from 'morphic-ts/lib/batteries/summoner' 5 | import { AType, EType } from 'morphic-ts/lib/usage/utils' 6 | import { fromDecoder } from '../framework/effects/process-env' 7 | import { shortReportInsecure } from './short-report' 8 | 9 | const Environment_ = summon(F => 10 | F.interface( 11 | { 12 | REACT_APP_FIREBASE_apiKey: F.string(), 13 | REACT_APP_FIREBASE_authDomain: F.string(), 14 | REACT_APP_FIREBASE_databaseURL: F.string(), 15 | REACT_APP_FIREBASE_projectId: F.string(), 16 | REACT_APP_FIREBASE_storageBucket: F.string(), 17 | REACT_APP_FIREBASE_messagingSenderId: F.string(), 18 | REACT_APP_FIREBASE_appId: F.string() 19 | }, 20 | 'Environment' 21 | ) 22 | ) 23 | 24 | export interface Environment extends AType {} 25 | export interface EnvironmentRaw extends EType {} 26 | export const Environment = AsOpaque(Environment_) 27 | 28 | export const readEnvironment = p.pipe( 29 | fromDecoder(Environment.strictType), 30 | effect.mapError( 31 | f.flow( 32 | shortReportInsecure, 33 | s => console.log('Invalid Environment', s), 34 | () => 'Invalid Environment' 35 | ) 36 | ) 37 | ) 38 | 39 | declare global { 40 | const _env: NodeJS.ProcessEnv 41 | } 42 | 43 | export const env = _env 44 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import { Spin } from 'antd' 2 | import { function as f, option } from 'fp-ts' 3 | import { makeADT, ofType } from 'morphic-ts/lib/adt' 4 | import * as React from 'react' 5 | import { useEffect, useState } from 'react' 6 | import { SignInContext } from './auth/SignIn' 7 | import { withStartAppEnvGuard } from './contexts/start-app-env' 8 | import { Nothing, Waiting } from './framework/adt/variant' 9 | 10 | interface ContextProps { 11 | auth: firebase.auth.Auth 12 | } 13 | 14 | interface HasUser { 15 | type: 'HasUser' 16 | user: firebase.User 17 | } 18 | 19 | const ResourceUser = makeADT('type')({ 20 | Nothing: ofType(), 21 | Waiting: ofType(), 22 | HasUser: ofType() 23 | }) 24 | 25 | const nothing = ResourceUser.of.Nothing({}) 26 | const waiting = ResourceUser.of.Waiting({}) 27 | 28 | const toUserOrUndefined = f.flow( 29 | option.fromPredicate(ResourceUser.is.HasUser), 30 | option.map(({ user }) => user), 31 | option.toUndefined 32 | ) 33 | 34 | export const App: React.FC = ({ auth }) => { 35 | const [userState, setUser] = useState(waiting) 36 | useEffect( 37 | () => 38 | auth.onAuthStateChanged( 39 | f.flow( 40 | option.fromNullable, 41 | option.fold( 42 | () => nothing, 43 | user => ResourceUser.of.HasUser({ user }) 44 | ), 45 | setUser 46 | ) 47 | ), 48 | [toUserOrUndefined(userState)] 49 | ) 50 | return ResourceUser.match({ 51 | HasUser: ({ user }) =>

Hello {user.displayName ?? 'you'}

, 52 | Nothing: () => , 53 | Waiting: () => 54 | })(userState) 55 | } 56 | 57 | export const AppContext = withStartAppEnvGuard(f.identity)(App) 58 | -------------------------------------------------------------------------------- /src/core/short-report.ts: -------------------------------------------------------------------------------- 1 | import { array, option, pipeable as p } from 'fp-ts' 2 | import { ValidationError } from 'io-ts' 3 | 4 | /** 5 | * The insecure variant of `shortReport` which may leak sensitive information. 6 | * To use only in development. 7 | * 8 | * @param errors 9 | */ 10 | export const shortReportInsecure = (errors: ValidationError[]): string => 11 | errors 12 | .map(error => { 13 | const contextArray = new Array(...error.context) 14 | const expectedType = array.last(contextArray) 15 | const outerType = array.lookup(contextArray.length - 2, contextArray) 16 | 17 | const msg = `${error.context.map(c => c.key).join('/')}: expecting type <${p.pipe( 18 | expectedType, 19 | option.fold( 20 | () => 'UNKNOWN', 21 | x => x.type.name 22 | ) 23 | )}> ${ 24 | option.isSome(outerType) ? `in Type ${outerType.value.type.name}` : '' 25 | } Got value <${JSON.stringify(error.value)}>, type: ${typeof error.value}` 26 | return msg 27 | }) 28 | .join('\n') 29 | 30 | /** 31 | * A short reporter made to report less verbose (so, more readable) messages than native `io-ts` `PathReporter`. 32 | * @param errors 33 | */ 34 | export const shortReport = (errors: ValidationError[]): string => 35 | errors 36 | .map(error => { 37 | const contextArray = new Array(...error.context) 38 | const expectedType = array.last(contextArray) 39 | const outerType = array.lookup(contextArray.length - 2, contextArray) 40 | 41 | const msg = `${error.context.map(c => c.key).join('/')}: expecting type <${p.pipe( 42 | expectedType, 43 | option.fold( 44 | () => 'UNKNOWN', 45 | x => x.type.name 46 | ) 47 | )}> ${ 48 | option.isSome(outerType) ? `in Type ${outerType.value.type.name}` : '' 49 | } Got invalid value` 50 | return msg 51 | }) 52 | .join('\n') 53 | -------------------------------------------------------------------------------- /nginx.conf: -------------------------------------------------------------------------------- 1 | # auto detects a good number of processes to run 2 | worker_processes auto; 3 | 4 | #Provides the configuration file context in which the directives that affect connection processing are specified. 5 | events { 6 | # Sets the maximum number of simultaneous connections that can be opened by a worker process. 7 | worker_connections 8000; 8 | # Tells the worker to accept multiple connections at a time 9 | multi_accept on; 10 | } 11 | 12 | 13 | http { 14 | # what times to include 15 | include /etc/nginx/mime.types; 16 | # what is the default one 17 | default_type application/octet-stream; 18 | 19 | # Sets the path, format, and configuration for a buffered log write 20 | log_format compression '$remote_addr - $remote_user [$time_local] ' 21 | '"$request" $status $upstream_addr ' 22 | '"$http_referer" "$http_user_agent"'; 23 | 24 | server { 25 | # listen on port PORT 26 | listen $PORT; 27 | # save logs here 28 | access_log /var/log/nginx/access.log compression; 29 | 30 | # where the root here 31 | root /var/www; 32 | # what file to server as index 33 | index index.html index.htm; 34 | 35 | location / { 36 | # First attempt to serve request as file, then 37 | # as directory, then fall back to redirecting to index.html 38 | try_files $uri $uri/ /index.html; 39 | } 40 | 41 | # Media: images, icons, video, audio, HTC 42 | location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { 43 | expires 1M; 44 | access_log off; 45 | add_header Cache-Control "public"; 46 | } 47 | 48 | # Javascript and CSS files 49 | location ~* \.(?:css|js)$ { 50 | try_files $uri =404; 51 | expires 1y; 52 | access_log off; 53 | add_header Cache-Control "public"; 54 | } 55 | 56 | # Any route containing a file extension (e.g. /devicesfile.js) 57 | location ~ ^.+\..+$ { 58 | try_files $uri =404; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import { effect, exit } from '@matechs/effect' 2 | import 'antd/dist/antd.css' 3 | import * as firebase from 'firebase/app' 4 | import 'firebase/auth' 5 | import { function as f, option, pipeable as p } from 'fp-ts' 6 | import * as React from 'react' 7 | import * as ReactDOM from 'react-dom' 8 | import { AppContext } from './App' 9 | import { StartAppEnv, StartAppEnvContext } from './contexts/start-app-env' 10 | import { env, Environment, readEnvironment } from './core/environment' 11 | 12 | const startApp = (e: StartAppEnv) => { 13 | const rootEl = document.createElement('div') 14 | rootEl.id = 'root' 15 | document.body.appendChild(rootEl) 16 | ReactDOM.render( 17 | 18 | 19 | , 20 | rootEl 21 | ) 22 | } 23 | 24 | interface FirebaseInitializeAppOptions { 25 | apiKey: string 26 | authDomain: string 27 | databaseURL: string 28 | projectId: string 29 | storageBucket: string 30 | messagingSenderId: string 31 | appId: string 32 | } 33 | 34 | const stripEnvVarsPrefix = (e: Environment): FirebaseInitializeAppOptions => ({ 35 | apiKey: e.REACT_APP_FIREBASE_apiKey, 36 | authDomain: e.REACT_APP_FIREBASE_authDomain, 37 | databaseURL: e.REACT_APP_FIREBASE_databaseURL, 38 | projectId: e.REACT_APP_FIREBASE_projectId, 39 | storageBucket: e.REACT_APP_FIREBASE_storageBucket, 40 | messagingSenderId: e.REACT_APP_FIREBASE_messagingSenderId, 41 | appId: e.REACT_APP_FIREBASE_appId 42 | }) 43 | 44 | export const initializeFirebase: (e: Environment) => firebase.app.App = f.flow( 45 | stripEnvVarsPrefix, 46 | firebase.initializeApp 47 | ) 48 | 49 | const toStartAppEnv = (app: firebase.app.App): StartAppEnv => ({ auth: app.auth() }) 50 | 51 | const getStartAppEnv = p.pipe( 52 | readEnvironment, 53 | effect.map( 54 | f.flow(initializeFirebase, toStartAppEnv, startApp, e => { 55 | console.log(JSON.stringify(e)) 56 | return e 57 | }) 58 | ) 59 | ) 60 | 61 | export const program = p.pipe(getStartAppEnv, effect.provide({ env }), eff => 62 | effect.run(eff, ex => { 63 | exit.isDone(ex) || console.log('Program exited with error', ex) 64 | }) 65 | ) 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typescript-starter", 3 | "description": "React & TypeScript Starter with webpack, ts-jest and runtime environment variables. It comes with fp-ts ecosystem and pre-configured prettier, eslint, vscode, husky hooks and Dockerfile to build a deployable image of your app", 4 | "repository": "git@github.com:Stouffi/typescript-react-starter.git", 5 | "author": "Stouffi ", 6 | "license": "MIT", 7 | "private": true, 8 | "sideEffects": false, 9 | "scripts": { 10 | "build": "TS_NODE_PROJECT=\"webpack/tsconfig.json\" webpack --config webpack/webpack.prod.ts", 11 | "prestart": "react-env", 12 | "start": "TS_NODE_PROJECT=\"webpack/tsconfig.json\" webpack-dev-server --config webpack/webpack.dev.ts", 13 | "test": "jest --watch", 14 | "test-ci": "jest", 15 | "postinstall": "./scripts/ensure-deduplicate.sh" 16 | }, 17 | "husky": { 18 | "hooks": { 19 | "pre-push": "./scripts/hooks/pre-push.sh" 20 | } 21 | }, 22 | "devDependencies": { 23 | "@beam-australia/react-env": "3.1.1", 24 | "@testing-library/react": "12.0.0", 25 | "@types/html-webpack-plugin": "3.2.5", 26 | "@types/jest": "26.0.24", 27 | "@types/node": "^12.19.8", 28 | "@types/react": "17.0.15", 29 | "@types/react-dom": "17.0.9", 30 | "@types/webpack": "5.28.0", 31 | "@types/webpack-dev-server": "3.11.3", 32 | "@types/webpack-merge": "5.0.0", 33 | "@typescript-eslint/eslint-plugin": "4.29.0", 34 | "@typescript-eslint/parser": "4.29.0", 35 | "clean-webpack-plugin": "3.0.0", 36 | "css-loader": "6.2.0", 37 | "eslint": "7.32.0", 38 | "eslint-config-prettier": "8.3.0", 39 | "eslint-plugin-prefer-arrow": "1.2.3", 40 | "eslint-plugin-prettier": "3.4.0", 41 | "eslint-plugin-react": "7.24.0", 42 | "fork-ts-checker-webpack-plugin": "6.3.1", 43 | "html-webpack-plugin": "5.3.2", 44 | "husky": "7.0.1", 45 | "jest": "26.6.3", 46 | "prettier": "2.3.2", 47 | "style-loader": "3.2.1", 48 | "ts-jest": "26.5.6", 49 | "ts-loader": "8.1.0", 50 | "ts-node": "10.1.0", 51 | "tsconfig-paths": "3.10.1", 52 | "typescript": "4.3.5", 53 | "webpack": "5.48.0", 54 | "webpack-cli": "4.1.0", 55 | "webpack-dev-server": "3.11.2", 56 | "webpack-merge": "5.8.0", 57 | "yarn-deduplicate": "3.1.0" 58 | }, 59 | "dependencies": { 60 | "@matechs/console": "7.12.0", 61 | "@matechs/effect": "5.0.29", 62 | "antd": "4.16.10", 63 | "fast-check": "2.17.0", 64 | "fast-equals": "2.0.0", 65 | "firebase": "7.24.0", 66 | "fp-ts": "2.11.1", 67 | "fp-ts-contrib": "0.1.26", 68 | "io-ts": "2.2.16", 69 | "io-ts-types": "0.5.16", 70 | "monocle-ts": "2.3.10", 71 | "morphic-ts": "0.8.0-rc.2", 72 | "newtype-ts": "0.3.4", 73 | "react": "17.0.2", 74 | "react-dom": "17.0.2", 75 | "react-redux": "7.2.4", 76 | "redux": "4.1.1", 77 | "redux-observable": "2.0.0", 78 | "retry-ts": "0.1.3", 79 | "rxjs": "7.3.0" 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/auth/SignIn.tsx: -------------------------------------------------------------------------------- 1 | import { log, provideConsole } from '@matechs/console' 2 | import { effect } from '@matechs/effect' 3 | import { Button, Form, Input } from 'antd' 4 | import * as firebase from 'firebase' 5 | import { function as f, option, pipeable as p } from 'fp-ts' 6 | import { AsOpaque, summon } from 'morphic-ts/lib/batteries/summoner' 7 | import { AType, EType } from 'morphic-ts/lib/usage/utils' 8 | import * as React from 'react' 9 | import { withStartAppEnvGuard } from '../contexts/start-app-env' 10 | 11 | const layout = { 12 | labelCol: { 13 | span: 8 14 | }, 15 | wrapperCol: { 16 | span: 16 17 | } 18 | } 19 | const tailLayout = { 20 | wrapperCol: { 21 | offset: 8, 22 | span: 16 23 | } 24 | } 25 | 26 | const SignInData_ = summon(F => 27 | F.interface( 28 | { 29 | username: F.string(), 30 | password: F.string() 31 | }, 32 | 'SignInData' 33 | ) 34 | ) 35 | 36 | export interface SignInData extends AType {} 37 | export interface SignInDataRaw extends EType {} 38 | export const SignInData = AsOpaque(SignInData_) 39 | 40 | const signIn = ({ username, password }: SignInData) => 41 | effect.accessM(({ auth }: Props) => 42 | effect.fromPromise(() => auth.signInWithEmailAndPassword(username, password)) 43 | ) 44 | 45 | interface Props { 46 | auth: firebase.auth.Auth 47 | } 48 | 49 | export const SignIn: React.FC = ({ auth }) => { 50 | const [data, setData] = React.useState>(option.none) 51 | React.useEffect(() => { 52 | const signInEff = p.pipe( 53 | data, 54 | option.map( 55 | f.flow( 56 | signIn, 57 | effect.asUnit, 58 | effect.chainError(err => log('SignIn error', err)), 59 | effect.provideS({ auth }), 60 | provideConsole, 61 | effect.run 62 | ) 63 | ) 64 | ) 65 | return p.pipe(signInEff, option.toUndefined) 66 | }) 67 | 68 | const onFinish = (values: unknown) => { 69 | console.log('Success:', values) 70 | p.pipe(SignInData.strictType.decode(values), option.fromEither, setData) 71 | } 72 | 73 | const onFinishFailed = (errorInfo: unknown) => { 74 | console.log('Failed:', errorInfo) 75 | } 76 | 77 | return ( 78 |
87 | 97 | 98 | 99 | 100 | 110 | 111 | 112 | 113 | {/* 114 | Remember me 115 | */} 116 | 117 | 118 | 121 | 122 |
123 | ) 124 | } 125 | 126 | export const SignInContext = withStartAppEnvGuard(f.identity)(SignIn) 127 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | "skipLibCheck": true, 5 | "incremental": true /* Enable incremental compilation */, 6 | "target": "ES5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, 7 | "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, 8 | // "lib": [], /* Specify library files to be included in the compilation. */ 9 | // "allowJs": true, /* Allow javascript files to be compiled. */ 10 | // "checkJs": true, /* Report errors in .js files. */ 11 | "jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */, 12 | "declaration": true /* Generates corresponding '.d.ts' file. */, 13 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 14 | "sourceMap": true /* Generates corresponding '.map' file. */, 15 | // "outFile": "./", /* Concatenate and emit output to single file. */ 16 | "outDir": "./dist" /* Redirect output structure to the directory. */, 17 | "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */, 18 | // "composite": true, /* Enable project compilation */ 19 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 20 | // "removeComments": true, /* Do not emit comments to output. */ 21 | // "noEmit": true /* Do not emit outputs. */, 22 | "emitDeclarationOnly": true, 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true /* Enable all strict type-checking options. */, 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, 36 | 37 | /* Additional Checks */ 38 | "noUnusedLocals": true /* Report errors on unused locals. */, 39 | "noUnusedParameters": true /* Report errors on unused parameters. */, 40 | "noImplicitReturns": true /* Report error when not all code paths in function return a value. */, 41 | "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */, 42 | 43 | /* Module Resolution Options */ 44 | "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [] /* Type declaration files to be included in compilation. */, 50 | // "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, 51 | "esModuleInterop": false /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 67 | }, 68 | "include": ["src/**/*.ts", "src/**/*.tsx"], 69 | "exclude": ["**/*.spec.*"] 70 | } 71 | --------------------------------------------------------------------------------