From e4b7b34a5915886eaa2dc7f18d758646e3c1c615 Mon Sep 17 00:00:00 2001 From: Tom Gobich Date: Sun, 20 Oct 2024 08:56:11 -0400 Subject: [PATCH] initial commit --- .editorconfig | 22 ++ .github/lock.yml | 26 ++ .github/stale.yml | 24 ++ .github/workflows/test.yml | 60 +++++ .gitignore | 14 + .npmrc | 1 + .prettierignore | 4 + LICENSE.md | 9 + README.md | 115 ++++++++ bin/test.ts | 11 + configure.ts | 22 ++ index.ts | 10 + package.json | 90 +++++++ providers/README.md | 5 + src/README.md | 3 + src/scaffolds/base_scaffold.ts | 74 +++++ src/scaffolds/jumpstart_scaffold.ts | 253 ++++++++++++++++++ src/scaffolds/tailwind_scaffold.ts | 177 ++++++++++++ src/utils/child_process.ts | 4 + src/utils/file_helper.ts | 15 ++ stubs/README.md | 6 + stubs/configs/tailwind.config.stub | 43 +++ .../auth/forgot_password_controller.stub | 42 +++ stubs/controllers/auth/login_controller.stub | 19 ++ stubs/controllers/auth/logout_controller.stub | 12 + .../controllers/auth/register_controller.stub | 20 ++ .../settings/account_controller.stub | 52 ++++ .../settings/profile_controller.stub | 19 ++ stubs/main.ts | 8 + .../create_email_histories_table.stub | 27 ++ .../create_password_reset_tokens_table.stub | 32 +++ .../create_remember_me_tokens_table.stub | 33 +++ stubs/models/email_history.stub | 27 ++ stubs/models/password_reset_token.stub | 152 +++++++++++ stubs/routes/auth.stub | 29 ++ stubs/routes/web.stub | 25 ++ stubs/services/edge_form_service.stub | 56 ++++ stubs/start/globals.stub | 18 ++ stubs/validators/auth.stub | 41 +++ stubs/validators/settings.stub | 24 ++ stubs/views/components/button/index.edge | 19 ++ stubs/views/components/card/index.edge | 21 ++ stubs/views/components/form/checkbox.edge | 20 ++ stubs/views/components/form/errors.edge | 8 + stubs/views/components/form/group.edge | 19 ++ stubs/views/components/form/index.edge | 16 ++ stubs/views/components/form/input.edge | 40 +++ stubs/views/components/form/label.edge | 8 + stubs/views/components/layout/auth.edge | 28 ++ stubs/views/components/layout/index.edge | 90 +++++++ stubs/views/components/toast/flash.edge | 13 + stubs/views/components/toast/index.edge | 35 +++ stubs/views/emails/account/email_changed.edge | 82 ++++++ stubs/views/emails/auth/forgot_password.edge | 105 ++++++++ stubs/views/emails/auth/password_reset.edge | 103 +++++++ .../pages/auth/forgot_password/index.edge | 46 ++++ .../pages/auth/forgot_password/reset.edge | 51 ++++ stubs/views/pages/auth/login.edge | 44 +++ stubs/views/pages/auth/register.edge | 36 +++ stubs/views/pages/settings/account.edge | 41 +++ stubs/views/pages/settings/profile.edge | 20 ++ stubs/views/pages/welcome.edge | 7 + tests/example.spec.ts | 7 + tsconfig.json | 7 + tsnode.esm.js | 18 ++ 65 files changed, 2508 insertions(+) create mode 100644 .editorconfig create mode 100644 .github/lock.yml create mode 100644 .github/stale.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .npmrc create mode 100644 .prettierignore create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 bin/test.ts create mode 100644 configure.ts create mode 100644 index.ts create mode 100644 package.json create mode 100644 providers/README.md create mode 100644 src/README.md create mode 100644 src/scaffolds/base_scaffold.ts create mode 100644 src/scaffolds/jumpstart_scaffold.ts create mode 100644 src/scaffolds/tailwind_scaffold.ts create mode 100644 src/utils/child_process.ts create mode 100644 src/utils/file_helper.ts create mode 100644 stubs/README.md create mode 100644 stubs/configs/tailwind.config.stub create mode 100644 stubs/controllers/auth/forgot_password_controller.stub create mode 100644 stubs/controllers/auth/login_controller.stub create mode 100644 stubs/controllers/auth/logout_controller.stub create mode 100644 stubs/controllers/auth/register_controller.stub create mode 100644 stubs/controllers/settings/account_controller.stub create mode 100644 stubs/controllers/settings/profile_controller.stub create mode 100644 stubs/main.ts create mode 100644 stubs/migrations/create_email_histories_table.stub create mode 100644 stubs/migrations/create_password_reset_tokens_table.stub create mode 100644 stubs/migrations/create_remember_me_tokens_table.stub create mode 100644 stubs/models/email_history.stub create mode 100644 stubs/models/password_reset_token.stub create mode 100644 stubs/routes/auth.stub create mode 100644 stubs/routes/web.stub create mode 100644 stubs/services/edge_form_service.stub create mode 100644 stubs/start/globals.stub create mode 100644 stubs/validators/auth.stub create mode 100644 stubs/validators/settings.stub create mode 100644 stubs/views/components/button/index.edge create mode 100644 stubs/views/components/card/index.edge create mode 100644 stubs/views/components/form/checkbox.edge create mode 100644 stubs/views/components/form/errors.edge create mode 100644 stubs/views/components/form/group.edge create mode 100644 stubs/views/components/form/index.edge create mode 100644 stubs/views/components/form/input.edge create mode 100644 stubs/views/components/form/label.edge create mode 100644 stubs/views/components/layout/auth.edge create mode 100644 stubs/views/components/layout/index.edge create mode 100644 stubs/views/components/toast/flash.edge create mode 100644 stubs/views/components/toast/index.edge create mode 100644 stubs/views/emails/account/email_changed.edge create mode 100644 stubs/views/emails/auth/forgot_password.edge create mode 100644 stubs/views/emails/auth/password_reset.edge create mode 100644 stubs/views/pages/auth/forgot_password/index.edge create mode 100644 stubs/views/pages/auth/forgot_password/reset.edge create mode 100644 stubs/views/pages/auth/login.edge create mode 100644 stubs/views/pages/auth/register.edge create mode 100644 stubs/views/pages/settings/account.edge create mode 100644 stubs/views/pages/settings/profile.edge create mode 100644 stubs/views/pages/welcome.edge create mode 100644 tests/example.spec.ts create mode 100644 tsconfig.json create mode 100644 tsnode.esm.js diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..1dfdf29 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# http://editorconfig.org + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.json] +insert_final_newline = ignore + +[**.min.js] +indent_style = ignore +insert_final_newline = ignore + +[MakeFile] +indent_style = space + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/lock.yml b/.github/lock.yml new file mode 100644 index 0000000..ea7cf67 --- /dev/null +++ b/.github/lock.yml @@ -0,0 +1,26 @@ +--- +ignoreUnless: {{ STALE_BOT }} +--- +# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app + +# Number of days of inactivity before a closed issue or pull request is locked +daysUntilLock: 60 + +# Skip issues and pull requests created before a given timestamp. Timestamp must +# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable +skipCreatedBefore: false + +# Issues and pull requests with these labels will be ignored. Set to `[]` to disable +exemptLabels: ['Type: Security'] + +# Label to add before locking, such as `outdated`. Set to `false` to disable +lockLabel: false + +# Comment to post before locking. Set to `false` to disable +lockComment: > + This thread has been automatically locked since there has not been + any recent activity after it was closed. Please open a new issue for + related bugs. + +# Assign `resolved` as the reason for locking. Set to `false` to disable +setLockReason: false diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 0000000..d21cf6c --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,24 @@ +--- +ignoreUnless: {{ STALE_BOT }} +--- +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 60 + +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 + +# Issues with these labels will never be considered stale +exemptLabels: + - 'Type: Security' + +# Label to use when marking an issue as stale +staleLabel: 'Status: Abandoned' + +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. + +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..6e82cdd --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,60 @@ +name: test + +on: + - push + - pull_request + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install + run: npm install + - name: Run lint + run: npm run lint + + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install + run: npm install + - name: Run typecheck + run: npm run typecheck + + tests: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + node-version: + - 20.10.0 + - 21.x + steps: + - uses: actions/checkout@v4 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install + run: npm install + - name: Run tests + run: npm test + windows: + runs-on: windows-latest + strategy: + matrix: + node-version: + - 20.10.0 + - 21.x + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install + run: npm install + - name: Run tests + run: npm test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..966cd35 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +node_modules +coverage +.DS_STORE +.nyc_output +.idea +.vscode/ +*.sublime-project +*.sublime-workspace +*.log +build +dist +yarn.lock +shrinkwrap.yaml +package-lock.json diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..43c97e7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +package-lock=false diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..da1f07a --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +build +docs +coverage +*.html diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..1bb5ef3 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +# The MIT License + +Copyright (c) 2023 + +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: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..30356f7 --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +# AdonisJS package starter kit + +> A boilerplate for creating AdonisJS packages + +This repo provides you with a starting point for creating AdonisJS packages. Of course, you can create a package from scratch with your folder structure and workflow. However, using this starter kit can speed up the process, as you have fewer decisions to make. + +## Setup + +- Clone the repo on your computer, or use `giget` to download this repo without the Git history. + ```sh + npx giget@latest gh:adonisjs/pkg-starter-kit + ``` +- Install dependencies. +- Update the `package.json` file and define the `name`, `description`, `keywords`, and `author` properties. +- The repo is configured with an MIT license. Feel free to change that if you are not publishing under the MIT license. + +## Folder structure + +The starter kit mimics the folder structure of the official packages. Feel free to rename files and folders as per your requirements. + +``` +├── providers +├── src +├── bin +├── stubs +├── configure.ts +├── index.ts +├── LICENSE.md +├── package.json +├── README.md +├── tsconfig.json +├── tsnode.esm.js +``` + +- The `configure.ts` file exports the `configure` hook to configure the package using the `node ace configure` command. +- The `index.ts` file is the main entry point of the package. +- The `tsnode.esm.js` file runs TypeScript code using TS-Node + SWC. Please read the code comment in this file to learn more. +- The `bin` directory contains the entry point file to run Japa tests. +- Learn more about [the `providers` directory](./providers/README.md). +- Learn more about [the `src` directory](./src/README.md). +- Learn more about [the `stubs` directory](./stubs/README.md). + +### File system naming convention + +We use `snake_case` naming conventions for the file system. The rule is enforced using ESLint. However, turn off the rule and use your preferred naming conventions. + +## Peer dependencies + +The starter kit has a peer dependency on `@adonisjs/core@6`. Since you are creating a package for AdonisJS, you must make it against a specific version of the framework core. + +If your package needs Lucid to be functional, you may install `@adonisjs/lucid` as a development dependency and add it to the list of `peerDependencies`. + +As a rule of thumb, packages installed in the user application should be part of the `peerDependencies` of your package and not the main dependency. + +For example, if you install `@adonisjs/core` as a main dependency, then essentially, you are importing a separate copy of `@adonisjs/core` and not sharing the one from the user application. Here is a great article explaining [peer dependencies](https://blog.bitsrc.io/understanding-peer-dependencies-in-javascript-dbdb4ab5a7be). + +## Published files + +Instead of publishing your repo's source code to npm, you must cherry-pick files and folders to publish only the required files. + +The cherry-picking uses the `files` property inside the `package.json` file. By default, we publish the following files and folders. + +```json +{ + "files": ["build/src", "build/providers", "build/stubs", "build/index.d.ts", "build/index.js"] +} +``` + +If you create additional folders or files, mention them inside the `files` array. + +## Exports + +[Node.js Subpath exports](https://nodejs.org/api/packages.html#subpath-exports) allows you to define the exports of your package regardless of the folder structure. This starter kit defines the following exports. + +```json +{ + "exports": { + ".": "./build/index.js", + "./types": "./build/src/types.js" + } +} +``` + +- The dot `.` export is the main export. +- The `./types` exports all the types defined inside the `./build/src/types.js` file (the compiled output). + +Feel free to change the exports as per your requirements. + +## Testing + +We configure the [Japa test runner](https://japa.dev/) with this starter kit. Japa is used in AdonisJS applications as well. Just run one of the following commands to execute tests. + +- `npm run test`: This command will first lint the code using ESlint and then run tests and report the test coverage using [c8](https://github.com/bcoe/c8). +- `npm run quick:test`: Runs only the tests without linting or coverage reporting. + +The starter kit also has a Github workflow file to run tests using Github Actions. The tests are executed against `Node.js 20.x` and `Node.js 21.x` versions on both Linux and Windows. Feel free to edit the workflow file in the `.github/workflows` directory. + +## TypeScript workflow + +- The starter kit uses [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) for compiling the TypeScript to JavaScript when publishing the package. +- [TS-Node](https://typestrong.org/ts-node/) and [SWC](https://swc.rs/) are used to run tests without compiling the source code. +- The `tsconfig.json` file is extended from [`@adonisjs/tsconfig`](https://github.com/adonisjs/tooling-config/tree/main/packages/typescript-config) and uses the `NodeNext` module system. Meaning the packages are written using ES modules. +- You can perform type checking without compiling the source code using the `npm run type check` script. + +Feel free to explore the `tsconfig.json` file for all the configured options. + +## ESLint and Prettier setup + +The starter kit configures ESLint and Prettier. Both configurations are stored within the `package.json` file and use our [shared config](https://github.com/adonisjs/tooling-config/tree/main/packages). Feel free to change the configuration, use custom plugins, or remove both tools altogether. + +## Using Stale bot + +The [Stale bot](https://github.com/apps/stale) is a Github application that automatically marks issues and PRs as stale and closes after a specific duration of inactivity. + +Feel free to delete the `.github/stale.yml` and `.github/lock.yml` files if you decide not to use the Stale bot. diff --git a/bin/test.ts b/bin/test.ts new file mode 100644 index 0000000..7978bf2 --- /dev/null +++ b/bin/test.ts @@ -0,0 +1,11 @@ +import { assert } from '@japa/assert' +import { configure, processCLIArgs, run } from '@japa/runner' + +processCLIArgs(process.argv.splice(2)) + +configure({ + files: ['tests/**/*.spec.ts'], + plugins: [assert()], +}) + +run() diff --git a/configure.ts b/configure.ts new file mode 100644 index 0000000..4d13dbb --- /dev/null +++ b/configure.ts @@ -0,0 +1,22 @@ +/* +|-------------------------------------------------------------------------- +| Configure hook +|-------------------------------------------------------------------------- +| +| The configure hook is called when someone runs "node ace configure " +| command. You are free to perform any operations inside this function to +| configure the package. +| +| To make things easier, you have access to the underlying "ConfigureCommand" +| instance and you can use codemods to modify the source files. +| +*/ + +import ConfigureCommand from '@adonisjs/core/commands/configure' +import TailwindScaffold from './src/scaffolds/tailwind_scaffold.js' +import JumpstartScaffold from './src/scaffolds/jumpstart_scaffold.js' + +export async function configure(command: ConfigureCommand) { + await new TailwindScaffold(command).run() + await new JumpstartScaffold(command).run() +} diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..5843ae1 --- /dev/null +++ b/index.ts @@ -0,0 +1,10 @@ +/* +|-------------------------------------------------------------------------- +| Package entrypoint +|-------------------------------------------------------------------------- +| +| Export values from the package entrypoint as you see fit. +| +*/ + +export { configure } from './configure.js' diff --git a/package.json b/package.json new file mode 100644 index 0000000..9b1ab27 --- /dev/null +++ b/package.json @@ -0,0 +1,90 @@ +{ + "name": "@adocasts.com/jumpstart", + "description": "", + "version": "0.0.0", + "engines": { + "node": ">=20.6.0" + }, + "type": "module", + "files": [ + "build/src", + "build/providers", + "build/stubs", + "build/configure.d.ts", + "build/configure.js", + "build/index.d.ts", + "build/index.js" + ], + "exports": { + ".": "./build/index.js", + "./types": "./build/src/types.js" + }, + "scripts": { + "clean": "del-cli build", + "copy:templates": "copyfiles \"stubs/**/*.{stub,edge}\" build", + "typecheck": "tsc --noEmit", + "lint": "eslint . --ext=.ts", + "format": "prettier --write .", + "quick:test": "node --import=./tsnode.esm.js --enable-source-maps bin/test.ts", + "pretest": "npm run lint", + "test": "c8 npm run quick:test", + "prebuild": "npm run lint && npm run clean", + "build": "tsc", + "postbuild": "npm run copy:templates", + "release": "np", + "version": "npm run build", + "prepublishOnly": "npm run build" + }, + "devDependencies": { + "@adonisjs/assembler": "^7.7.0", + "@adonisjs/core": "^6.12.0", + "@adonisjs/eslint-config": "^1.3.0", + "@adonisjs/prettier-config": "^1.3.0", + "@adonisjs/tsconfig": "^1.3.0", + "@japa/assert": "^3.0.0", + "@japa/runner": "^3.1.4", + "@swc/core": "^1.6.3", + "@types/node": "^20.14.5", + "c8": "^10.1.2", + "copyfiles": "^2.4.1", + "del-cli": "^5.1.0", + "eslint": "^8.57.0", + "np": "^10.0.6", + "prettier": "^3.3.2", + "ts-node": "^10.9.2", + "typescript": "^5.4.5" + }, + "peerDependencies": { + "@adonisjs/core": "^6.2.0" + }, + "author": "tomgobich,adocasts.com", + "license": "MIT", + "keywords": [ + "adonisjs", + "auth", + "lucid" + ], + "eslintConfig": { + "extends": "@adonisjs/eslint-config/package" + }, + "prettier": "@adonisjs/prettier-config", + "publishConfig": { + "access": "public", + "tag": "latest" + }, + "np": { + "message": "chore(release): %s", + "tag": "latest", + "branch": "main", + "anyBranch": false + }, + "c8": { + "reporter": [ + "text", + "html" + ], + "exclude": [ + "tests/**" + ] + } +} diff --git a/providers/README.md b/providers/README.md new file mode 100644 index 0000000..ac2ab06 --- /dev/null +++ b/providers/README.md @@ -0,0 +1,5 @@ +# The providers directory + +The `providers` directory contains the service providers exported by your application. Make sure to register these providers within the `exports` collection (aka package entrypoints) defined within the `package.json` file. + +Learn more about [package entrypoints](https://nodejs.org/api/packages.html#package-entry-points). diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..2e688c7 --- /dev/null +++ b/src/README.md @@ -0,0 +1,3 @@ +# The src directory + +The `src` directory is where you organize your package code. Feel free to create additional sub-directories as you see fit. diff --git a/src/scaffolds/base_scaffold.ts b/src/scaffolds/base_scaffold.ts new file mode 100644 index 0000000..9fb6a74 --- /dev/null +++ b/src/scaffolds/base_scaffold.ts @@ -0,0 +1,74 @@ +import { Codemods } from '@adonisjs/core/ace/codemods' +import ConfigureCommand from '@adonisjs/core/commands/configure' +import { cp } from 'node:fs/promises' +import { SyntaxKind } from 'typescript' +import { stubsRoot } from '../../stubs/main.js' +import { slash } from '@adonisjs/core/helpers' +export default class BaseScaffold { + declare codemods: Codemods + + constructor(protected command: ConfigureCommand) {} + + get app() { + return this.command.app + } + + get logger() { + return this.command.logger + } + + get colors() { + return this.command.colors + } + + async boot() { + this.codemods = await this.command.createCodemods() + } + + async copyView(stubName: string) { + const stub = this.app.makePath(stubsRoot, 'views', stubName) + const dest = this.app.viewsPath(stubName.replace('.stub', '.ts')) + await cp(stub, dest, { recursive: true, force: false }) + this.logger.action(`create ${slash(this.app.relativePath(dest))}`) + } + + async copyModel(stubName: string) { + const stub = this.app.makePath(stubsRoot, 'models', stubName) + const dest = this.app.modelsPath(stubName.replace('.stub', '.ts')) + await cp(stub, dest, { recursive: true, force: false }) + this.logger.action(`create ${slash(this.app.relativePath(dest))}`) + } + + async copyController(stubName: string) { + const stub = this.app.makePath(stubsRoot, 'controllers', stubName) + const dest = this.app.httpControllersPath(stubName.replace('.stub', '.ts')) + await cp(stub, dest, { recursive: true, force: false }) + this.logger.action(`create ${slash(this.app.relativePath(dest))}`) + } + + async isProviderRegistered(path: string) { + const project = await this.codemods.getTsMorphProject() + const file = project?.getSourceFile(this.app.makePath('adonisrc.ts')) + const defaultExport = file?.getDefaultExportSymbol() + + if (!file) { + throw new Error('Cannot find the adonisrc.ts file') + } + + if (!defaultExport) { + throw new Error('Cannot find the default export in adonisrc.ts') + } + + // get the object contents of `defineConfig` + const declaration = defaultExport.getDeclarations()[0] + const options = + declaration.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0] || + declaration.getChildrenOfKind(SyntaxKind.CallExpression)[0].getArguments()[0] + + const providers = options + .getProperty('providers') + ?.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression) + + return providers?.getFullText().includes(path) + } +} diff --git a/src/scaffolds/jumpstart_scaffold.ts b/src/scaffolds/jumpstart_scaffold.ts new file mode 100644 index 0000000..18620e3 --- /dev/null +++ b/src/scaffolds/jumpstart_scaffold.ts @@ -0,0 +1,253 @@ +import { cp, readFile, writeFile } from 'node:fs/promises' +import BaseScaffold from './base_scaffold.js' +import ConfigureCommand from '@adonisjs/core/commands/configure' +import { stubsRoot } from '../../stubs/main.js' + +type Import = { + defaultImport?: string + namedImports?: string[] + module: string +} + +export default class JumpstartScaffold extends BaseScaffold { + constructor(protected command: ConfigureCommand) { + super(command) + } + + async run() { + await this.boot() + + const ace = await this.app.container.make('ace') + const isAuthConfigured = await this.isProviderRegistered('@adonisjs/auth/auth_provider') + const isLucidConfigured = await this.isProviderRegistered('@adonisjs/lucid/database_provider') + const isMailConfigured = await this.isProviderRegistered('@adonisjs/mail/mail_provider') + + if (!isLucidConfigured) { + this.logger.log( + this.colors.blue("You'll need @adonisjs/lucid installed and configured to continue") + ) + await ace.exec('add @adonisjs/lucid', []) + } + + if (!isAuthConfigured) { + this.logger.log( + this.colors.blue("You'll need @adonisjs/auth installed and configured to continue") + ) + await ace.exec('add @adonisjs/auth', []) + } + + if (!isMailConfigured) { + this.logger.log( + this.colors.blue("You'll need @adonisjs/mail installed and configured to continue") + ) + await ace.exec('add', ['@adonisjs/mail']) + } + + await this.codemods.installPackages([ + { name: 'edge-iconify', isDevDependency: false }, + { name: '@iconify-json/ph', isDevDependency: false }, + { name: '@iconify-json/svg-spinners', isDevDependency: false }, + ]) + + await this.#updateEnv() + await this.#enableHttpMethodSpoofing() + await this.#registerPreloads() + await this.#generateStubs() + await this.#updateUserModel() + } + + async #updateEnv() { + await this.codemods.defineEnvVariables({ APP_URL: `http:$HOST:$PORT` }) + await this.codemods.defineEnvValidations({ + leadingComment: 'URL pointing to your app; useful for emails', + variables: { + APP_URL: 'Env.schema.string()', + }, + }) + } + + async #enableHttpMethodSpoofing() { + const appConfigPath = this.app.makePath('config/app.ts') + let appConfig = await readFile(appConfigPath, 'utf8') + appConfig = appConfig.replace('allowMethodSpoofing: false', 'allowMethodSpoofing: true') + await writeFile(appConfigPath, appConfig) + this.logger.log(`${this.colors.green('UPDATED:')} config/app.ts > enabled HTTP Method Spoofing`) + } + + async #registerPreloads() { + await this.codemods.makeUsingStub(stubsRoot, 'start/globals.stub', {}) + await this.codemods.makeUsingStub(stubsRoot, 'routes/auth.stub', {}) + await this.codemods.makeUsingStub(stubsRoot, 'routes/web.stub', {}) + + await this.codemods.updateRcFile((rcFile) => { + rcFile + .addPreloadFile('#start/globals') + .addPreloadFile('#start/routes/auth') + .addPreloadFile('#start/routes/web') + }) + } + + async #generateStubs() { + // stubs -> views + await cp(this.app.makePath(stubsRoot, 'views'), this.app.viewsPath(), { + recursive: true, + force: false, + }) + + // stubs -> migrations + await this.codemods.makeUsingStub(stubsRoot, 'migrations/create_email_histories_table.stub', {}) + await this.codemods.makeUsingStub( + stubsRoot, + 'migrations/create_password_reset_tokens_table.stub', + {} + ) + await this.codemods.makeUsingStub( + stubsRoot, + 'migrations/create_remember_me_tokens_table.stub', + {} + ) + + // stubs -> models + await this.copyModel('email_history.stub') + await this.copyModel('password_reset_token.stub') + + // stubs -> validators + await this.codemods.makeUsingStub(stubsRoot, 'validators/auth.stub', {}) + await this.codemods.makeUsingStub(stubsRoot, 'validators/settings.stub', {}) + + // stubs -> services + await this.codemods.makeUsingStub(stubsRoot, 'services/edge_form_service.stub', {}) + + // stubs -> controllers + await this.copyController('auth/forgot_password_controller.stub') + await this.copyController('auth/login_controller.stub') + await this.copyController('auth/logout_controller.stub') + await this.copyController('auth/register_controller.stub') + await this.copyController('settings/account_controller.stub') + await this.copyController('settings/profile_controller.stub') + } + + async #updateUserModel() { + const project = await this.codemods.getTsMorphProject() + const file = project?.getSourceFile(this.app.modelsPath('user.ts')) + const model = file?.getClass('User') + const imports: Set = new Set() + + if (!model) { + this.logger.log(`${this.colors.yellow('SKIPPED:')} user model updates, model not found.`) + return + } + + imports.add({ namedImports: ['Authenticator'], module: '@adonisjs/auth' }) + imports.add({ namedImports: ['Authenticators'], module: '@adonisjs/auth/types' }) + imports.add({ namedImports: ['Infer'], module: '@vinejs/vine/types' }) + imports.add({ + namedImports: ['loginValidator', 'registerValidator'], + module: '#validators/auth', + }) + imports.add({ namedImports: ['updateEmailValidator'], module: '#validators/settings' }) + imports.add({ namedImports: ['DbRememberMeTokensProvider'], module: '@adonisjs/auth/session' }) + imports.add({ defaultImport: 'db', module: '@adonisjs/lucid/services/db' }) + imports.add({ defaultImport: 'mail', module: '@adonisjs/mail/services/main' }) + imports.add({ defaultImport: 'app', module: '@adonisjs/core/services/app' }) + imports.add({ defaultImport: 'EmailHistory', module: '#models/email_history' }) + + model.addProperty({ + isStatic: true, + name: 'rememberMeTokens', + initializer: 'DbRememberMeTokensProvider.forModel(User)', + }) + + const login = model.addMethod({ + isStatic: true, + isAsync: true, + name: 'login', + parameters: [ + { name: 'auth', type: 'Authenticator' }, + { + name: '{ email, password, remember }', + type: 'Infer', + }, + ], + }) + + login.setBodyText(` + const user = await this.verifyCredentials(email, password) + await auth.use('web').login(user, remember) + return user + `) + + const register = model.addMethod({ + isStatic: true, + isAsync: true, + name: 'register', + parameters: [ + { name: 'auth', type: 'Authenticator' }, + { name: 'data', type: 'Infer' }, + ], + }) + + register.setBodyText(` + const user = await this.create(data) + await auth.use('web').login(user) + return user + `) + + const logout = model.addMethod({ + isStatic: true, + isAsync: true, + name: 'logout', + parameters: [{ name: 'auth', type: 'Authenticator' }], + }) + + logout.setBodyText(`await auth.use('web').logout()`) + + const updateEmail = model.addMethod({ + isAsync: true, + name: 'updateEmail', + parameters: [{ name: 'data', type: 'Infer' }], + }) + + updateEmail.setBodyText(` + const emailOld = this.email + + // verify the password is correct for auth user + await User.verifyCredentials(emailOld, data.password) + + await db.transaction(async (trx) => { + this.useTransaction(trx) + + await this.merge({ email: data.email }).save() + await EmailHistory.create( + { + userId: this.id, + emailNew: data.email, + emailOld, + }, + { client: trx } + ) + }) + + await mail.sendLater((message) => { + message + .to(emailOld) + .subject(\`Your \${app.appName} email has been successfully changed\`) + .htmlView('emails/account/email_changed', { user: this }) + }) + `) + + imports?.forEach((imp) => { + const exists = file?.getImportDeclaration(imp.module) + + if (exists) return + + file?.addImportDeclaration({ + defaultImport: imp.defaultImport, + namedImports: imp.namedImports, + moduleSpecifier: imp.module, + }) + }) + + await file?.save() + } +} diff --git a/src/scaffolds/tailwind_scaffold.ts b/src/scaffolds/tailwind_scaffold.ts new file mode 100644 index 0000000..e62d21c --- /dev/null +++ b/src/scaffolds/tailwind_scaffold.ts @@ -0,0 +1,177 @@ +import ConfigureCommand from '@adonisjs/core/commands/configure' +import { writeFile } from 'node:fs/promises' +import { SourceFile, Symbol } from 'ts-morph' +import { SyntaxKind } from 'typescript' +import { stubsRoot } from '../../stubs/main.js' +import { readFileOrDefault } from '../utils/file_helper.js' +import BaseScaffold from './base_scaffold.js' + +type Import = { + name: string + module: string +} + +export default class TailwindScaffold extends BaseScaffold { + tailwindImport: Import = { + name: 'tailwind', + module: 'tailwindcss', + } + + autoprefixerImport: Import = { + name: 'autoprefixer', + module: 'autoprefixer', + } + + constructor(protected command: ConfigureCommand) { + super(command) + } + + async run() { + this.codemods = await this.command.createCodemods() + + const cssPath = this.app.makePath('resources/css/app.css') + const cssContents = '@tailwind base;\n@tailwind components;\n@tailwind utilities;\n' + + await this.codemods.installPackages([ + { name: 'tailwindcss', isDevDependency: true }, + { name: 'autoprefixer', isDevDependency: true }, + ]) + + await this.codemods.makeUsingStub(stubsRoot, 'configs/tailwind.config.stub', {}) + + let css = await readFileOrDefault(cssPath, '') + let wasChanged = false + + if (!css.includes('[x-cloak]')) { + const cloak = '[x-cloak] { display: none; }\n' + css = css ? `${cloak}${css}` : cloak + wasChanged = true + } + + if (!css.includes('@tailwind')) { + css = css ? `${cssContents}\n${css}` : cssContents + wasChanged = true + } + + if (wasChanged) { + await writeFile(cssPath, css) + + this.logger.log( + `${this.colors.green('UPDATED:')} resources/css/app.css > included @tailwind directives &/or x-cloak` + ) + } + + await this.#addViteConfig() + } + + async #addViteConfig() { + const project = await this.codemods.getTsMorphProject() + const file = project?.getSourceFile(this.app.makePath('vite.config.ts')) + const defaultExport = file?.getDefaultExportSymbol() + + if (!file) { + throw new Error('Cannot find the vite.config.ts file') + } + + if (!defaultExport) { + throw new Error('Cannot find the default export in vite.config.ts') + } + + const imports = await this.#addVitePostcssPlugins(defaultExport) + + this.#addMissingImports(file, imports) + + if (imports.length) { + file.formatText({ indentSize: 2 }) + + this.logger.log( + `${this.colors.green('UPDATED:')} tailwind.config.ts > added tailwind & autoprefixer plugins` + ) + } + + await file.save() + } + + async #addVitePostcssPlugins(defaultExport: Symbol) { + // get the object contents of `defineConfig` + const declaration = defaultExport.getDeclarations()[0] + const options = + declaration.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0] || + declaration.getChildrenOfKind(SyntaxKind.CallExpression)[0].getArguments()[0] + + // 1. if there isn't already a `css` property, we can add the whole thing + const cssProperty = options + .getProperty('css') + ?.getFirstChildByKind(SyntaxKind.ObjectLiteralExpression) + + if (!cssProperty?.getFullText()) { + options.addPropertyAssignment({ + name: 'css', + initializer: `{ postcss: { plugins: [tailwind(), autoprefixer()] } }`, + }) + return [this.tailwindImport, this.autoprefixerImport] + } + + // 2. if there is a `css` property but not a `postcss` property, + // we can add the whole `postcss` config + const postcssProperty = cssProperty + .getProperty('postcss') + ?.getFirstChildByKind(SyntaxKind.ObjectLiteralExpression) + + if (!postcssProperty?.getFullText()) { + cssProperty.addPropertyAssignment({ + name: 'postcss', + initializer: '{ plugins: [tailwind(), autoprefixer()] }', + }) + return [this.tailwindImport, this.autoprefixerImport] + } + + // 3. if there is a `css.postcss` property, but it doesn't contain `plugins`, + // we can add the plugins + const plugins = postcssProperty + ?.getProperty('plugins') + ?.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression) + + if (!plugins?.getFullText()) { + postcssProperty.addPropertyAssignment({ + name: 'plugins', + initializer: '[tailwind(), autoprefixer()]', + }) + return [this.tailwindImport, this.autoprefixerImport] + } + + // 4. if there is a `css.postcss.plugins` property, + // determine if either the tailwind or autoprefixer plugis are missing + const pluginItems = plugins + ?.getElements() + .filter((element) => ['tailwind()', 'autoprefixer()'].includes(element.getText())) + .map((element) => element.getText()) + + const imports: Import[] = [] + + if (!pluginItems?.includes('tailwind()')) { + plugins.insertElement(0, 'tailwind()') + imports.push(this.tailwindImport) + } + + if (!pluginItems.includes('autoprefixer()')) { + plugins.addElement('autoprefixer()') + imports.push(this.autoprefixerImport) + } + + return imports + } + + #addMissingImports(file: SourceFile, imports: Import[]) { + const defaultImports = file.getImportDeclarations().map((r) => r.getDefaultImport()?.getText()) + + imports?.forEach((imp) => { + if (defaultImports?.includes(imp.name)) return + + file.addImportDeclaration({ + defaultImport: imp.name, + moduleSpecifier: imp.module, + }) + }) + } +} diff --git a/src/utils/child_process.ts b/src/utils/child_process.ts new file mode 100644 index 0000000..243676f --- /dev/null +++ b/src/utils/child_process.ts @@ -0,0 +1,4 @@ +import { promisify } from 'node:util' +import child_process from 'node:child_process' + +export const exec = promisify(child_process.exec) diff --git a/src/utils/file_helper.ts b/src/utils/file_helper.ts new file mode 100644 index 0000000..84e7a20 --- /dev/null +++ b/src/utils/file_helper.ts @@ -0,0 +1,15 @@ +import { readFile } from 'node:fs/promises' + +export async function readFileOrDefault(filePath: string, defaultValue: string) { + try { + const data = await readFile(filePath, 'utf8') + return data + } catch (err) { + if (err.code === 'ENOENT') { + return defaultValue + } else { + console.error(`Error reading file: ${err}`) + throw err + } + } +} diff --git a/stubs/README.md b/stubs/README.md new file mode 100644 index 0000000..4dd2dac --- /dev/null +++ b/stubs/README.md @@ -0,0 +1,6 @@ +# The stubs directory + +The `stubs` directory stores all the stubs needed by your package. It could be config files you will publish during the initial setup or stubs you want to use within the scaffolding commands. + +- Inside the `package.json` file, we have defined a `copy:templates` script that copies the `stubs` folder to the `build` folder. +- Ensure the `build/stubs` are always published to npm via the `files` array inside the `package.json` file. diff --git a/stubs/configs/tailwind.config.stub b/stubs/configs/tailwind.config.stub new file mode 100644 index 0000000..686ba7a --- /dev/null +++ b/stubs/configs/tailwind.config.stub @@ -0,0 +1,43 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: [ + './resources/views/**/*.{edge,js,ts,jsx,tsx,vue}', + ], + theme: { + extend: { + /** + * Default Home Page Theme + * Adjust to match your project's needs + */ + fontFamily: { + sans: [ "Instrument Sans", "sans-serif" ] + }, + colors: { + primary: { + DEFAULT: "#5A45FF", + lighter: "#a599ff" + }, + sand: { + 1: "var(--sand-1)", + 2: "var(--sand-2)", + 3: "var(--sand-3)", + 4: "var(--sand-4)", + 5: "var(--sand-5)", + 6: "var(--sand-6)", + 7: "var(--sand-7)", + 8: "var(--sand-8)", + 9: "var(--sand-9)", + 10: "var(--sand-10)", + 11: "var(--sand-11)", + 12: "var(--sand-12)" + } + } + } + }, + plugins: [], +} +{{{ + exports({ + to: app.makePath('', 'tailwind.config.js') + }) +}}} diff --git a/stubs/controllers/auth/forgot_password_controller.stub b/stubs/controllers/auth/forgot_password_controller.stub new file mode 100644 index 0000000..3208742 --- /dev/null +++ b/stubs/controllers/auth/forgot_password_controller.stub @@ -0,0 +1,42 @@ +import PasswordResetToken from '#models/password_reset_token' +import { passwordResetSendValidator, passwordResetValidator } from '#validators/auth' +import type { HttpContext } from '@adonisjs/core/http' + +export default class ForgotPasswordsController { + #sentSessionKey = 'FORGOT_PASSWORD_SENT' + + async index({ view, session }: HttpContext) { + const isSent = session.flashMessages.has(this.#sentSessionKey) + + return view.render('pages/auth/forgot_password/index', { isSent }) + } + + async send({ request, response, session }: HttpContext) { + const { email } = await request.validateUsing(passwordResetSendValidator) + + await PasswordResetToken.send(email) + + session.flash(this.#sentSessionKey, true) + + return response.redirect().back() + } + + async reset({ params, view }: HttpContext) { + const { isValid, user } = await PasswordResetToken.verify(params.value) + return view.render('pages/auth/forgot_password/reset', { + value: params.value, + email: user?.email, + isValid, + }) + } + + async update({ request, response, session }: HttpContext) { + const data = await request.validateUsing(passwordResetValidator) + + await PasswordResetToken.reset(data.value, data.password) + + session.flash('success', 'Your password has been updated') + + return response.redirect().toRoute('auth.login.show') + } +} diff --git a/stubs/controllers/auth/login_controller.stub b/stubs/controllers/auth/login_controller.stub new file mode 100644 index 0000000..fb0999a --- /dev/null +++ b/stubs/controllers/auth/login_controller.stub @@ -0,0 +1,19 @@ +import User from '#models/user' +import { loginValidator } from '#validators/auth' +import type { HttpContext } from '@adonisjs/core/http' + +export default class LoginController { + async show({ view }: HttpContext) { + return view.render('pages/auth/login') + } + + async store({ request, response, auth, session }: HttpContext) { + const data = await request.validateUsing(loginValidator) + const user = await User.login(auth, data) + const baseMessage = 'Welcome back' + + session.flash('success', user.fullName ? `${baseMessage}, ${user.fullName}` : baseMessage) + + return response.redirect().toRoute('welcome') + } +} diff --git a/stubs/controllers/auth/logout_controller.stub b/stubs/controllers/auth/logout_controller.stub new file mode 100644 index 0000000..f410419 --- /dev/null +++ b/stubs/controllers/auth/logout_controller.stub @@ -0,0 +1,12 @@ +import User from '#models/user' +import type { HttpContext } from '@adonisjs/core/http' + +export default class LogoutController { + async handle({ response, auth, session }: HttpContext) { + await User.logout(auth) + + session.flash('success', 'See you next time') + + return response.redirect().toRoute('auth.login.show') + } +} diff --git a/stubs/controllers/auth/register_controller.stub b/stubs/controllers/auth/register_controller.stub new file mode 100644 index 0000000..ef7b4ce --- /dev/null +++ b/stubs/controllers/auth/register_controller.stub @@ -0,0 +1,20 @@ +import User from '#models/user' +import { registerValidator } from '#validators/auth' +import type { HttpContext } from '@adonisjs/core/http' +import app from '@adonisjs/core/services/app' + +export default class RegisterController { + async show({ view }: HttpContext) { + return view.render('pages/auth/register') + } + + async store({ request, response, auth, session }: HttpContext) { + const data = await request.validateUsing(registerValidator) + const user = await User.register(auth, data) + const baseMessage = `Welcome to ${app.appName}` + + session.flash('success', user.fullName ? `${baseMessage}, ${user.fullName}` : baseMessage) + + return response.redirect().toRoute('welcome') + } +} diff --git a/stubs/controllers/settings/account_controller.stub b/stubs/controllers/settings/account_controller.stub new file mode 100644 index 0000000..25feed6 --- /dev/null +++ b/stubs/controllers/settings/account_controller.stub @@ -0,0 +1,52 @@ +import { emailRule } from '#validators/auth' +import { updateEmailValidator } from '#validators/settings' +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' +import vine from '@vinejs/vine' + +export default class AccountController { + async index({ view }: HttpContext) { + return view.render('pages/settings/account') + } + + async updateEmail({ request, response, auth, session }: HttpContext) { + const data = await request.validateUsing(updateEmailValidator) + const user = auth.use('web').user! + + if (data.email === user.email) { + session.flash('success', 'You are already using the submitted email') + return response.redirect().back() + } + + await user.updateEmail(data) + + session.flash('success', 'Your email has been updated') + + return response.redirect().back() + } + + async destroy({ request, response, auth, session }: HttpContext) { + const user = auth.use('web').user! + const validator = vine.compile( + vine.object({ + confirmEmail: emailRule().in([user.email]), + }) + ) + + await validator.validate(request.all()) + + await db.transaction(async (trx) => { + user.useTransaction(trx) + + // if you have any, delete other non-cascading relationships here + + await user.delete() + }) + + await auth.use('web').logout() + + session.flash('success', 'Your account has been deleted') + + return response.redirect().toRoute('auth.register.show') + } +} diff --git a/stubs/controllers/settings/profile_controller.stub b/stubs/controllers/settings/profile_controller.stub new file mode 100644 index 0000000..e03e4e8 --- /dev/null +++ b/stubs/controllers/settings/profile_controller.stub @@ -0,0 +1,19 @@ +import { updateProfileValidator } from '#validators/settings' +import type { HttpContext } from '@adonisjs/core/http' + +export default class ProfileController { + async index({ view }: HttpContext) { + return view.render('pages/settings/profile') + } + + async update({ request, response, auth, session }: HttpContext) { + const data = await request.validateUsing(updateProfileValidator) + const user = auth.use('web').user! + + await user.merge(data).save() + + session.flash('success', 'Your profile has been updated') + + return response.redirect().back() + } +} diff --git a/stubs/main.ts b/stubs/main.ts new file mode 100644 index 0000000..361d6cd --- /dev/null +++ b/stubs/main.ts @@ -0,0 +1,8 @@ +import { dirname } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * Path to the root directory where the stubs are stored. We use + * this path within commands and the configure hook + */ +export const stubsRoot = dirname(fileURLToPath(import.meta.url)) diff --git a/stubs/migrations/create_email_histories_table.stub b/stubs/migrations/create_email_histories_table.stub new file mode 100644 index 0000000..7202765 --- /dev/null +++ b/stubs/migrations/create_email_histories_table.stub @@ -0,0 +1,27 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'email_histories' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id') + table.integer('user_id').unsigned().references('users.id').notNullable().onDelete('CASCADE') + table.string('email_old', 254).notNullable() + table.string('email_new', 254).notNullable() + + table.timestamp('created_at') + table.timestamp('updated_at') + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} + +{{{ + exports({ + to: app.makePath(app.migrationsPath(), `${Date.now()}_create_email_histories_table.ts`), + }) +}}} diff --git a/stubs/migrations/create_password_reset_tokens_table.stub b/stubs/migrations/create_password_reset_tokens_table.stub new file mode 100644 index 0000000..60b03b1 --- /dev/null +++ b/stubs/migrations/create_password_reset_tokens_table.stub @@ -0,0 +1,32 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'password_reset_tokens' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id') + table + .integer('user_id') + .notNullable() + .unsigned() + .references('id') + .inTable('users') + .onDelete('CASCADE') + + table.string('value').notNullable().unique() + table.timestamp('created_at').notNullable() + table.timestamp('updated_at').notNullable() + table.timestamp('expires_at').notNullable() + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} +{{{ + exports({ + to: app.makePath(app.migrationsPath(), `${Date.now()}_create_password_reset_tokens_table.ts`), + }) +}}} diff --git a/stubs/migrations/create_remember_me_tokens_table.stub b/stubs/migrations/create_remember_me_tokens_table.stub new file mode 100644 index 0000000..9cd86a8 --- /dev/null +++ b/stubs/migrations/create_remember_me_tokens_table.stub @@ -0,0 +1,33 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'remember_me_tokens' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments() + table + .integer('tokenable_id') + .notNullable() + .unsigned() + .references('id') + .inTable('users') + .onDelete('CASCADE') + + table.string('hash').notNullable().unique() + table.timestamp('created_at').notNullable() + table.timestamp('updated_at').notNullable() + table.timestamp('expires_at').notNullable() + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} + +{{{ + exports({ + to: app.makePath(app.migrationsPath(), `${Date.now()}_create_remember_me_tokens_table.ts`), + }) +}}} diff --git a/stubs/models/email_history.stub b/stubs/models/email_history.stub new file mode 100644 index 0000000..ba0d3c3 --- /dev/null +++ b/stubs/models/email_history.stub @@ -0,0 +1,27 @@ +import User from '#models/user' +import { BaseModel, belongsTo, column } from '@adonisjs/lucid/orm' +import type { BelongsTo } from '@adonisjs/lucid/types/relations' +import { DateTime } from 'luxon' + +export default class EmailHistory extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare userId: number + + @column() + declare emailOld: string + + @column() + declare emailNew: string + + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime + + @belongsTo(() => User) + declare user: BelongsTo +} diff --git a/stubs/models/password_reset_token.stub b/stubs/models/password_reset_token.stub new file mode 100644 index 0000000..be2b86b --- /dev/null +++ b/stubs/models/password_reset_token.stub @@ -0,0 +1,152 @@ +import { DateTime, DurationLikeObject } from 'luxon' +import { BaseModel, belongsTo, column } from '@adonisjs/lucid/orm' +import User from './user.js' +import type { BelongsTo } from '@adonisjs/lucid/types/relations' +import string from '@adonisjs/core/helpers/string' +import encryption from '@adonisjs/core/services/encryption' +import router from '@adonisjs/core/services/router' +import mail from '@adonisjs/mail/services/main' +import env from '#start/env' +import { Exception } from '@adonisjs/core/exceptions' +import app from '@adonisjs/core/services/app' + +export default class PasswordResetToken extends BaseModel { + // how long the token will remain valid after creation + static validFor: DurationLikeObject = { hour: 1 } + + @column({ isPrimary: true }) + declare id: number + + @column() + declare userId: number + + @column() + declare value: string + + @column.dateTime() + declare expiresAt: DateTime + + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime + + get isValid() { + return this.expiresAt > DateTime.now() + } + + @belongsTo(() => User) + declare user: BelongsTo + + // #region Methods + + /** + * Creates a password reset token and sends a "forgot password" email + * @param email user's email + * @returns + */ + static async send(email: string) { + const user = await User.findBy('email', email) + const value = string.generateRandom(32) + const encryptedValue = encryption.encrypt(value) + + // silently fail if email does not exist + if (!user) return + + await this.expireAllForUser(user) + await this.create({ + expiresAt: DateTime.now().plus(this.validFor), + userId: user.id, + value, + }) + + const resetLink = router + .builder() + .prefixUrl(env.get('APP_URL')) + .params({ value: encryptedValue }) + .make('auth.password.reset') + + await mail.sendLater((message) => { + message + .subject(\`Reset your ${app.appName} password\`) + .to(user.email) + .htmlView('emails/auth/forgot_password', { + user, + resetLink, + validFor: Object.keys(this.validFor).reduce( + (acc, key) => `${acc} ${this.validFor[key as keyof DurationLikeObject]} ${key}`.trim(), + '' + ), + }) + }) + } + + /** + * Validates the password reset token and update's the user's password + * @param encryptedValue encrypted password reset token value + * @param password user's new password + * @returns + */ + static async reset(encryptedValue: string, password: string) { + const { isValid, user } = await this.verify(encryptedValue) + + // if the token is invalid or not matched to a user, throw invalid exception + if (!isValid || !user) { + throw new Exception('The password reset token provided is invalid or expired', { + status: 403, + code: 'E_INVALID_PASSWORD_RESET_TOKEN', + }) + } + + await user.merge({ password }).save() + await this.expireAllForUser(user) + + const loginLink = router.builder().prefixUrl(env.get('APP_URL')).make('auth.login.show') + + await mail.sendLater((message) => { + message + .subject(`Your ${app.appName} password has been reset`) + .to(user.email) + .htmlView('emails/auth/password_reset', { + user, + loginLink, + }) + }) + + return user + } + + /** + * Verifies the password reset token value and matches to a user + * @param encryptedValue encrypted password reset token value + * @returns + */ + static async verify(encryptedValue: string) { + const value = encryption.decrypt(encryptedValue) + const token = await this.findBy({ value }) + const user = await token?.related('user').query().first() + + return { + isValid: token?.isValid, + token, + user, + } + } + + /** + * Expires all pending password reset tokens for the provided user + * @param user user model + */ + static async expireAllForUser(user: User) { + await PasswordResetToken.query() + .where('userId', user.id) + .where('expiresAt', '>=', DateTime.now().toSQL({ includeOffset: false })) + .update({ + expiresAt: DateTime.now().toSQL({ includeOffset: false }), + updatedAt: DateTime.now().toSQL({ includeOffset: false }), + }) + } + + // #endregion +} diff --git a/stubs/routes/auth.stub b/stubs/routes/auth.stub new file mode 100644 index 0000000..b28e62f --- /dev/null +++ b/stubs/routes/auth.stub @@ -0,0 +1,29 @@ +import { middleware } from '#start/kernel' +import router from '@adonisjs/core/services/router' +const LoginController = () => import('#controllers/auth/login_controller') +const LogoutController = () => import('#controllers/auth/logout_controller') +const RegisterController = () => import('#controllers/auth/register_controller') +const ForgotPasswordsController = () => import('#controllers/auth/forgot_passwords_controller') + +// ignore formatting, easier to visually scan single-line routes +/* prettier-ignore-start */ +/* eslint-disable */ + +//* LOGIN, REGISTER, LOGOUT +router.get('/login', [LoginController, 'show']).as('auth.login.show').use(middleware.guest()) +router.post('/login', [LoginController, 'store']).as('auth.login.store').use([middleware.guest()]) +router.get('/register', [RegisterController, 'show']).as('auth.register.show').use(middleware.guest()) +router.post('/register', [RegisterController, 'store']).as('auth.register.store').use([middleware.guest()]) +router.post('/logout', [LogoutController, 'handle']).as('auth.logout').use(middleware.auth()) + +//* FORGOT PASSWORD +router.get('/forgot-password', [ForgotPasswordsController, 'index']).as('auth.password.index').use([middleware.guest()]) +router.post('/forgot-password', [ForgotPasswordsController, 'send']).as('auth.password.send').use([middleware.guest()]) +router.get('/forgot-password/reset/:value', [ForgotPasswordsController, 'reset']).as('auth.password.reset').use([middleware.guest()]) +router.post('/forgot-password/reset', [ForgotPasswordsController, 'update']).as('auth.password.update').use([middleware.guest()]) + +{{{ + exports({ + to: app.makePath(app.startPath(), 'routes/auth.ts'), + }) +}}} diff --git a/stubs/routes/web.stub b/stubs/routes/web.stub new file mode 100644 index 0000000..b5c0a66 --- /dev/null +++ b/stubs/routes/web.stub @@ -0,0 +1,25 @@ +import { middleware } from '#start/kernel' +import router from '@adonisjs/core/services/router' +const ProfileController = () => import('#controllers/settings/profile_controller') +const AccountController = () => import('#controllers/settings/account_controller') + +// ignore formatting, easier to visually scan single-line routes +/* prettier-ignore-start */ +/* eslint-disable */ + +router.on('/welcome').render('pages/welcome').as('welcome') + +//* SETTINGS -> ACCOUNT +router.get('/settings/account', [AccountController, 'index']).as('settings.account').use(middleware.auth()) +router.put('/settings/account/email', [AccountController, 'updateEmail']).as('settings.account.email').use(middleware.auth()) +router.delete('/settings/account', [AccountController, 'destroy']).as('settings.account.destroy').use(middleware.auth()) + +//* SETTINGS -> PROFILE +router.get('/settings/profile', [ProfileController, 'index']).as('settings.profile').use(middleware.auth()) +router.put('/settings/profile', [ProfileController, 'update']).as('settings.profile.update').use(middleware.auth()) + +{{{ + exports({ + to: app.makePath(app.startPath(), 'routes/web.ts'), + }) +}}} diff --git a/stubs/services/edge_form_service.stub b/stubs/services/edge_form_service.stub new file mode 100644 index 0000000..262c54a --- /dev/null +++ b/stubs/services/edge_form_service.stub @@ -0,0 +1,56 @@ +import router from '@adonisjs/core/services/router' +import { MakeUrlOptions } from '@adonisjs/core/types/http' + +export default class EdgeFormService { + static post( + routeIdentifier: string, + params?: any[] | Record | undefined, + options?: MakeUrlOptions | undefined + ) { + return router.makeUrl(routeIdentifier, params, options) + } + + static put( + routeIdentifier: string, + params?: any[] | Record | undefined, + options?: MakeUrlOptions | undefined + ) { + return router.makeUrl(routeIdentifier, params, this.spoof('put', options)) + } + + static patch( + routeIdentifier: string, + params?: any[] | Record | undefined, + options?: MakeUrlOptions | undefined + ) { + return router.makeUrl(routeIdentifier, params, this.spoof('patch', options)) + } + + static delete( + routeIdentifier: string, + params?: any[] | Record | undefined, + options?: MakeUrlOptions | undefined + ) { + return router.makeUrl(routeIdentifier, params, this.spoof('delete', options)) + } + + static generateInputId() { + return '_' + Math.random().toString(36).substr(2, 9) + } + + private static spoof(method: 'post' | 'put' | 'patch' | 'delete', options: MakeUrlOptions = {}) { + return { + ...options, + qs: { + ...(options.qs || {}), + _method: method, + }, + } + } +} + +{{{ + exports({ + to: app.makePath(app.servicesPath(), 'edge_form_service.ts'), + }) +}}} diff --git a/stubs/start/globals.stub b/stubs/start/globals.stub new file mode 100644 index 0000000..48f7a87 --- /dev/null +++ b/stubs/start/globals.stub @@ -0,0 +1,18 @@ +import EdgeFormService from '#services/edge_form_service' +import edge from 'edge.js' +import { edgeIconify, addCollection } from 'edge-iconify' +import { icons as phicons } from '@iconify-json/ph' +import { icons as svgspinners } from '@iconify-json/svg-spinners' + +addCollection(phicons) +addCollection(svgspinners) + +edge.use(edgeIconify) + +edge.global('form', EdgeFormService) + +{{{ + exports({ + to: app.makePath(app.startPath(), 'globals.ts'), + }) +}}} diff --git a/stubs/validators/auth.stub b/stubs/validators/auth.stub new file mode 100644 index 0000000..9eb1336 --- /dev/null +++ b/stubs/validators/auth.stub @@ -0,0 +1,41 @@ +import vine from '@vinejs/vine' + +export const emailRule = () => vine.string().maxLength(254).email().normalizeEmail() + +export const loginValidator = vine.compile( + vine.object({ + email: emailRule(), + password: vine.string().minLength(8), + remember: vine.boolean().optional(), + }) +) + +export const registerValidator = vine.compile( + vine.object({ + fullName: vine.string().maxLength(254).optional(), + email: emailRule().unique(async (db, value) => { + const exists = await db.from('users').where('email', value).select('id').first() + return !exists + }), + password: vine.string().minLength(8), + }) +) + +export const passwordResetSendValidator = vine.compile( + vine.object({ + email: emailRule(), + }) +) + +export const passwordResetValidator = vine.compile( + vine.object({ + value: vine.string(), + password: vine.string().minLength(8), + }) +) + +{{{ + exports({ + to: app.makePath(app.validatorsPath(), 'auth.ts'), + }) +}}} diff --git a/stubs/validators/settings.stub b/stubs/validators/settings.stub new file mode 100644 index 0000000..a98d9fd --- /dev/null +++ b/stubs/validators/settings.stub @@ -0,0 +1,24 @@ +import vine from '@vinejs/vine' +import { emailRule } from './auth.js' + +export const updateEmailValidator = vine.compile( + vine.object({ + email: emailRule().unique(async (db, value) => { + const match = await db.from('users').where('email', value).select('id').first() + return !match + }), + password: vine.string(), + }) +) + +export const updateProfileValidator = vine.compile( + vine.object({ + fullName: vine.string().maxLength(254).optional().nullable(), + }) +) + +{{{ + exports({ + to: app.makePath(app.validatorsPath(), 'settings.ts'), + }) +}}} diff --git a/stubs/views/components/button/index.edge b/stubs/views/components/button/index.edge new file mode 100644 index 0000000..08b1bb9 --- /dev/null +++ b/stubs/views/components/button/index.edge @@ -0,0 +1,19 @@ +@let(tag = $props.href ? 'a' : 'button') +@let(variant = $props.variant ?? 'dark') +@let(variants = new Map([ + ['dark', 'bg-black text-white hover:bg-gray-900 focus:bg-gray-900'], + ['ghost', 'bg-white text-gray-900 hover:bg-gray-100 focus:bg-gray-100'], + ['blue', 'bg-blue-600 text-white hover:bg-blue-700 focus:bg-blue-700'], + ['red', 'bg-red-600 text-white hover:bg-red-700 focus:bg-red-700'], +])) +@let(baseClasses = `py-2 px-3 inline-flex items-center justify-center gap-x-2 text-sm font-medium rounded border border-transparent focus:outline-none disabled:opacity-50 disabled:pointer-events-none ${variants.get(variant)}`) + +<{{ tag }} {{ $props.except(['variant']).merge({ class: baseClasses }).toAttrs() }}> + @if (type === 'submit') + + @svg('svg-spinners:blocks-shuffle-3') + + @endif + + {{{ await $slots.main() }}} + diff --git a/stubs/views/components/card/index.edge b/stubs/views/components/card/index.edge new file mode 100644 index 0000000..eb3c15c --- /dev/null +++ b/stubs/views/components/card/index.edge @@ -0,0 +1,21 @@ +
+
+ @if (title || description) +
+ @if (title) +

+ {{ title }} +

+ @endif + + @if (description) +

+ {{ description }} +

+ @endif +
+ @endif + + {{{ await $slots.main() }}} +
+
diff --git a/stubs/views/components/form/checkbox.edge b/stubs/views/components/form/checkbox.edge new file mode 100644 index 0000000..18b5e48 --- /dev/null +++ b/stubs/views/components/form/checkbox.edge @@ -0,0 +1,20 @@ +@let(id = $props.id ?? form.generateInputId()) +@let(errors = $props.errors ?? flashMessages.get(`errors.${name}`)) +@let(baseClasses = 'shrink-0 mt-0.5 border-gray-200 rounded text-blue-600 focus:ring-blue-500') + +
+
+ +
+
+ +
+
+ +@!form.errors({ id, errors }) diff --git a/stubs/views/components/form/errors.edge b/stubs/views/components/form/errors.edge new file mode 100644 index 0000000..5ece3fb --- /dev/null +++ b/stubs/views/components/form/errors.edge @@ -0,0 +1,8 @@ +@let(id = $props.id ?? $context.id) +@let(errors = $props.errors || $context.errors) + +@if (errors) +

+ {{ errors.join(', ') }} +

+@endif diff --git a/stubs/views/components/form/group.edge b/stubs/views/components/form/group.edge new file mode 100644 index 0000000..c1d5068 --- /dev/null +++ b/stubs/views/components/form/group.edge @@ -0,0 +1,19 @@ +@let(id = $props.id ?? form.generateInputId()) +@let(errors = $props.errors ?? flashMessages.get(`errors.${name}`)) + +@inject({ + id, + name, + errors, +}) + +
+ @if (label) + @!form.label({ id, label }) + @elseif ($slots.label) + {{{ await $slots.label() }}} + @endif + + {{{ await $slots.main() }}} + @!form.errors({ id, errors }) +
diff --git a/stubs/views/components/form/index.edge b/stubs/views/components/form/index.edge new file mode 100644 index 0000000..64fa626 --- /dev/null +++ b/stubs/views/components/form/index.edge @@ -0,0 +1,16 @@ +@let(useCSRF = $props.csrf ?? true) +@let(method = $props.method ?? 'POST') + +
+ @if (useCSRF) + {{ csrfField() }} + @endif + + {{{ await $slots.main() }}} +
diff --git a/stubs/views/components/form/input.edge b/stubs/views/components/form/input.edge new file mode 100644 index 0000000..cb5ff51 --- /dev/null +++ b/stubs/views/components/form/input.edge @@ -0,0 +1,40 @@ +@let($$props = Object.assign($context, $props)) +@let(id = $$props.id) +@let(name = $$props.name) +@let(type = $$props.type ?? 'text') +@let(value = (name ? old(name, $props.value) : $props.value) ?? '') +@let(baseClasses = 'py-3 px-4 block w-full border border-gray-200 rounded text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none') + +
+ + + {{-- error icon --}} + @if ($$props.errors) +
+ @!svg('ph:exclamation-mark-fill', { class: 'size-5 text-red-500' }) +
+ @endif + + {{-- password visibility toggle --}} + @if (type === 'password') + + @endif +
diff --git a/stubs/views/components/form/label.edge b/stubs/views/components/form/label.edge new file mode 100644 index 0000000..9ac6df2 --- /dev/null +++ b/stubs/views/components/form/label.edge @@ -0,0 +1,8 @@ + diff --git a/stubs/views/components/layout/auth.edge b/stubs/views/components/layout/auth.edge new file mode 100644 index 0000000..160665e --- /dev/null +++ b/stubs/views/components/layout/auth.edge @@ -0,0 +1,28 @@ + + + + + + + @if ($slots.head) + {{{ await $slots.head() }}} + @endif + + + {{ title || app.appName }} - AdonisJS + + + @vite(['resources/css/app.css', 'resources/js/app.js']) + + +
+
+ {{{ await $slots.main() }}} +
+
+ + @!toast.flash() + + + + diff --git a/stubs/views/components/layout/index.edge b/stubs/views/components/layout/index.edge new file mode 100644 index 0000000..c314204 --- /dev/null +++ b/stubs/views/components/layout/index.edge @@ -0,0 +1,90 @@ + + + + + + + @if ($slots.head) + {{{ await $slots.head() }}} + @endif + + + {{ title || app.appName }} - AdonisJS + + + @vite(['resources/css/app.css', 'resources/js/app.js']) + + + +
+
+ + +
+ @if (await auth.check()) +
+ + +
+
+ + Profile Settings + + + Account Settings + + +
+ + @form({ action: route('auth.logout') }) + + @end +
+
+
+ @else + @button({ href: route('auth.login.show'), variant: 'ghost' }) + Login + @end + + @button({ href: route('auth.register.show') }) + Register + @end + @endif +
+
+
+ + +
+ {{{ await $slots.main() }}} +
+ + @!toast.flash() + + + + diff --git a/stubs/views/components/toast/flash.edge b/stubs/views/components/toast/flash.edge new file mode 100644 index 0000000..34fcc74 --- /dev/null +++ b/stubs/views/components/toast/flash.edge @@ -0,0 +1,13 @@ +
+ @if (flashMessages.has('info')) + @!toast({ variant: 'info', text: flashMessages.get('info') }) + @elseif (flashMessages.has('success')) + @!toast({ variant: 'success', text: flashMessages.get('success') }) + @elseif (flashMessages.has('error')) + @!toast({ variant: 'error', text: flashMessages.get('error') }) + @elseif (flashMessages.has('errorsBag')) + @!toast({ variant: 'error', text: Object.values(flashMessages.get('errorsBag')).join(', ') }) + @elseif (flashMessages.has('warning')) + @!toast({ variant: 'warning', text: flashMessages.get('warning') }) + @endif +
diff --git a/stubs/views/components/toast/index.edge b/stubs/views/components/toast/index.edge new file mode 100644 index 0000000..d505130 --- /dev/null +++ b/stubs/views/components/toast/index.edge @@ -0,0 +1,35 @@ +{{-- Markup Sourced From: https://preline.co/docs/toasts.html --}} +@let(variant = $props.variant || 'info') +@let(icons = new Map([ + ['info', ``], + ['success', ``], + ['error', ``], + ['warning', ``] +])) + + diff --git a/stubs/views/emails/account/email_changed.edge b/stubs/views/emails/account/email_changed.edge new file mode 100644 index 0000000..6e569f1 --- /dev/null +++ b/stubs/views/emails/account/email_changed.edge @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + +
+

+ Your Email Was Changed

+

+ Hi {{ user.fullName || 'there' }}! Your {{ app.appName }} account email was recently changed and this email we're + writing you to today is no longer the email in use.

+

+ If this is incorrect, please contact support.

+ + + + + + +
+

+  

+

+ All the best,
The {{ app.appName }} Team

+
+ + + diff --git a/stubs/views/emails/auth/forgot_password.edge b/stubs/views/emails/auth/forgot_password.edge new file mode 100644 index 0000000..4bee67e --- /dev/null +++ b/stubs/views/emails/auth/forgot_password.edge @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + +
+

+ Reset Your Password

+

+ Hi {{ user.fullName || 'there' }}! We received a request that you'd like to reset your {{ app.appName }} password. + Please click the link below to do so. This link will only be valid for {{ validFor }}.

+ + + + + + +
Reset + Password +
+ + + + + + +
+

+  

+

+ All the best, +
+ The {{ app.appName }} Team +

+

+  

+

+ {{ resetLink + }} +

+
+ + + diff --git a/stubs/views/emails/auth/password_reset.edge b/stubs/views/emails/auth/password_reset.edge new file mode 100644 index 0000000..054aae4 --- /dev/null +++ b/stubs/views/emails/auth/password_reset.edge @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + +
+

+ Your password has been reset

+

+ Hi {{ user.fullName || 'there' }}! Your {{ app.appName }} password was just reset.

+ + + + + + +
Login to {[ app.appName }} +
+ + + + + + +
+

+  

+

+ All the best, +
+ The {{ app.appName }} Team +

+

+  

+

+ {{ loginLink + }} +

+
+ + + diff --git a/stubs/views/pages/auth/forgot_password/index.edge b/stubs/views/pages/auth/forgot_password/index.edge new file mode 100644 index 0000000..166e77a --- /dev/null +++ b/stubs/views/pages/auth/forgot_password/index.edge @@ -0,0 +1,46 @@ +{{-- Markup Sourced From: https://preline.co/examples/forms-authentication.html --}} +@layout.auth({ title: 'Forgot Password' }) +
+

+ Forgot password? +

+

+ Remember your password? + + Login here + +

+
+ + @if (isSent) + +
+ @!svg('ph:info', { class: 'w-5 h-5 -translate-y-0.5' }) +
+ Please check your email +
+
+ We have sent a password reset link to your email. Please check your email and click on the + link to reset your password. +
+
+ + + + @else + @form({ action: form.post('auth.password.send'), class: 'mt-5 grid gap-y-4' }) + @form.group({ label: 'Email address', name: 'email' }) + @!form.input({ type: 'email', required: true }) + @end + + @button({ type: 'submit' }) + Reset password + @end + @end + @endif +@end diff --git a/stubs/views/pages/auth/forgot_password/reset.edge b/stubs/views/pages/auth/forgot_password/reset.edge new file mode 100644 index 0000000..7526e63 --- /dev/null +++ b/stubs/views/pages/auth/forgot_password/reset.edge @@ -0,0 +1,51 @@ +{{-- Markup Sourced From: https://preline.co/examples/forms-authentication.html --}} +@layout.auth({ title: 'Reset Password' }) + @slot('head') + + @endslot + +
+

+ Reset password? +

+

+ Remember your password? + + Login here + +

+
+ + @if (!isValid) + +
+ @!svg('ph:info', { class: 'w-5 h-5 -translate-y-0.5' }) +
+ Link is invalid or expired +
+
+ This password reset link is invalid or has expired. Please try again. +
+
+ + + + @else + @form({ action: form.post('auth.password.update'), class: 'mt-5 grid gap-y-4' }) + + + @form.group({ label: 'New password', name: 'password' }) + @!form.input({ type: 'password', required: true }) + @end + + @button({ type: 'submit' }) + Reset password + @end + @end + @endif +@end diff --git a/stubs/views/pages/auth/login.edge b/stubs/views/pages/auth/login.edge new file mode 100644 index 0000000..be3ecd2 --- /dev/null +++ b/stubs/views/pages/auth/login.edge @@ -0,0 +1,44 @@ +{{-- Markup Sourced From: https://preline.co/examples/forms-authentication.html --}} +@layout.auth({ title: 'Login' }) + +
+

+ Login +

+

+ Don't have an account yet? + + Register here + +

+
+ +
+ @form({ action: form.post('auth.login.store'), class: 'grid gap-y-4' }) + @form.group({ label: 'Email address', name: 'email' }) + @!form.input({ type: 'email', required: true }) + @end + + @form.group({ name: 'password' }) + @slot('label') +
+ @!form.label({ label: 'Password' }) + + + Forgot password? + +
+ @endslot + + @!form.input({ type: 'password', required: true }) + @end + + @!form.checkbox({ label: 'Remember me', name: 'remember' }) + + @button({ type: 'submit' }) + Login + @end + @end +
+ +@end diff --git a/stubs/views/pages/auth/register.edge b/stubs/views/pages/auth/register.edge new file mode 100644 index 0000000..6a59ae7 --- /dev/null +++ b/stubs/views/pages/auth/register.edge @@ -0,0 +1,36 @@ +{{-- Markup Sourced From: https://preline.co/examples/forms-authentication.html --}} +@layout.auth({ title: 'Register' }) + +
+

+ Register +

+

+ Already have an account? + + Login here + +

+
+ +
+ @form({ action: form.post('auth.register.store'), class: 'grid gap-y-4' }) + @form.group({ label: 'Full name', name: 'fullName' }) + @!form.input() + @end + + @form.group({ label: 'Email address', name: 'email' }) + @!form.input({ type: 'email', required: true }) + @end + + @form.group({ label: 'Password', name: 'password' }) + @!form.input({ type: 'password', required: true }) + @end + + @button({ type: 'submit' }) + Register + @end + @end +
+ +@end diff --git a/stubs/views/pages/settings/account.edge b/stubs/views/pages/settings/account.edge new file mode 100644 index 0000000..00f0529 --- /dev/null +++ b/stubs/views/pages/settings/account.edge @@ -0,0 +1,41 @@ +@layout({ title: 'Account Settings' }) + + @card({ + title: 'Update Email', + description: "Update your account's email address." + }) + @form({ action: form.put('settings.account.email'), class: 'grid gap-y-4' }) + @form.group({ label: 'Email address', name: 'email' }) + @!form.input({ type: 'email', required: true, placeholder: auth.user.email }) + @end + + @form.group({ label: 'Confirm your password', name: 'password' }) + @!form.input({ type: 'password', required: true }) + @end + +
+ @button({ type: 'submit' }) + Update Email Address + @end +
+ @end + @end + + @card({ + title: 'Delete Account', + description: "Delete your account and all your data." + }) + @form({ action: form.delete('settings.account.destroy'), class: 'grid gap-y-4' }) + @form.group({ label: 'Please enter your account email to confirm deletion', name: 'confirmEmail' }) + @!form.input({ type: 'email', required: true, placeholder: auth.user.email }) + @end + +
+ @button({ type: 'submit', variant: 'red' }) + Delete Account + @end +
+ @end + @end + +@end diff --git a/stubs/views/pages/settings/profile.edge b/stubs/views/pages/settings/profile.edge new file mode 100644 index 0000000..a83cf91 --- /dev/null +++ b/stubs/views/pages/settings/profile.edge @@ -0,0 +1,20 @@ +@layout({ title: 'Profile Settings' }) + + @card({ + title: 'Profile', + description: 'Manage your name and other profile settings.' + }) + @form({ action: form.put('settings.profile.update'), class: 'grid gap-y-4' }) + @form.group({ label: 'Full name', name: 'fullName' }) + @!form.input({ placeholder: auth.user.fullName ?? '' }) + @end + +
+ @button({ type: 'submit' }) + Update Profile + @end +
+ @end + @end + +@end diff --git a/stubs/views/pages/welcome.edge b/stubs/views/pages/welcome.edge new file mode 100644 index 0000000..f19895e --- /dev/null +++ b/stubs/views/pages/welcome.edge @@ -0,0 +1,7 @@ +@layout({ title: 'Welcome' }) + +

+ Page contents here +

+ +@end diff --git a/tests/example.spec.ts b/tests/example.spec.ts new file mode 100644 index 0000000..893ea1a --- /dev/null +++ b/tests/example.spec.ts @@ -0,0 +1,7 @@ +import { test } from '@japa/runner' + +test.group('Example', () => { + test('add two numbers', ({ assert }) => { + assert.equal(1 + 1, 2) + }) +}) diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..0cfd318 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "@adonisjs/tsconfig/tsconfig.package.json", + "compilerOptions": { + "rootDir": "./", + "outDir": "./build", + } +} diff --git a/tsnode.esm.js b/tsnode.esm.js new file mode 100644 index 0000000..0cce922 --- /dev/null +++ b/tsnode.esm.js @@ -0,0 +1,18 @@ +/* +|-------------------------------------------------------------------------- +| TS-Node ESM hook +|-------------------------------------------------------------------------- +| +| Importing this file before any other file will allow you to run TypeScript +| code directly using TS-Node + SWC. For example +| +| node --import="./tsnode.esm.js" bin/test.ts +| node --import="./tsnode.esm.js" index.ts +| +| +| Why not use "--loader=ts-node/esm"? +| Because, loaders have been deprecated. +*/ + +import { register } from 'node:module' +register('ts-node/esm', import.meta.url)