1
0
mirror of synced 2026-02-03 18:01:02 -05:00

Compare commits

...

13 Commits

Author SHA1 Message Date
github-actions[bot]
0bc107fd7f Version Packages (alpha) (#3684)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-08-10 10:36:04 +02:00
Dillon Raphael
cb55ed266d check if DocumentHead is self closing in the codemod step (#3702) 2022-08-09 13:21:26 -04:00
Aleksandra
271c58ac62 Fix Cannot find module 'generate' error (#3700) 2022-08-09 14:32:22 +02:00
Dillon Raphael
06427f67f2 Throw error if cookiePrefix is undefined during codemod (#3696)
* throws error if cookiePrefix is undefined

* create ExpectedError class
2022-08-08 16:35:17 -04:00
Dillon Raphael
f120f6723a Add DocumentProps to codemod import map (#3695)
* add DocumentProps & DocumentContext to import map & clean up post structuring of _document imports from next/document
2022-08-08 16:10:33 -04:00
Blitz.js Bot
bac5e740ba (meta) added @oltdaniel as contributor 2022-08-08 15:35:24 -04:00
Daniel Oltmanns
630c718129 Fixes #3614 - changed console logs to standard logger (#3693)
* Fixes #3614 - changed console logs to standard logger

I tried to keep the logging format close to what has been present before, by also including the chalk package for coloring.

* Create great-candles-stare.md

Co-authored-by: Dillon Raphael <dillon@creatorsneverdie.com>
2022-08-08 15:35:20 -04:00
Aleksandra
078fe47419 Add '@testing-library/jest-dom' to new app dependecies (#3694) 2022-08-08 19:23:33 +02:00
Aleksandra
8dfaad088d Set correct packages versions in package.json with upgrade-legacy codemod (#3678) 2022-08-08 18:54:21 +02:00
Aleksandra
dd299ae89f Add ts-jest dependency to the new app templates (#3688) 2022-08-08 18:10:22 +02:00
Aleksandra
41608c4c34 Run codegen tasks after installing dependecies in the new command (#3692) 2022-08-08 17:57:39 +02:00
Aleksandra
70b334a2f7 Remove trailing comma from tsconfig.json in new app template (#3687) 2022-08-08 12:12:18 +02:00
Dillon Raphael
f0ca738d56 Run the codegen tasks on blitz dev (#3683) 2022-08-05 19:13:45 +02:00
50 changed files with 679 additions and 344 deletions

View File

@@ -3660,6 +3660,16 @@
"doc",
"code"
]
},
{
"login": "oltdaniel",
"name": "Daniel Oltmanns",
"avatar_url": "https://avatars.githubusercontent.com/u/53529846?v=4",
"profile": "oltdaniel.eu",
"contributions": [
"doc",
"code"
]
}
],
"contributorsPerLine": 7,

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---
Throw error if cookiePrefix is undefined when running codemod

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---
Add DocumentProps & DocumentContext to the codemod import map

View File

@@ -0,0 +1,5 @@
---
"blitz": patch
---
Comment out generate command import until we add the full support back

View File

@@ -0,0 +1,6 @@
---
"@blitzjs/rpc": patch
"blitz": patch
---
Use internal branded blitz logger for @blitzjs/rpc

View File

@@ -0,0 +1,5 @@
---
"blitz": patch
---
Run codegen tasks on blitz dev command

View File

@@ -22,6 +22,7 @@
},
"changesets": [
"big-phones-bow",
"blue-pigs-tan",
"breezy-cameras-double",
"breezy-moose-behave",
"bright-mangos-run",
@@ -29,8 +30,10 @@
"calm-nails-wait",
"calm-tomatoes-drive",
"clean-walls-wink",
"clever-radios-lie",
"cool-doors-invent",
"cool-horses-check",
"curly-rules-speak",
"curly-seas-serve",
"dirty-monkeys-greet",
"dirty-planets-chew",
@@ -52,6 +55,7 @@
"good-insects-wink",
"gorgeous-buses-scream",
"gorgeous-games-obey",
"great-candles-stare",
"great-months-train",
"great-terms-rescue",
"green-papayas-do",
@@ -62,6 +66,7 @@
"hot-cups-rhyme",
"hot-drinks-approve",
"hungry-baboons-swim",
"kind-walls-suffer",
"late-steaks-give",
"lemon-games-press",
"lemon-seas-push",
@@ -102,6 +107,7 @@
"red-badgers-retire",
"rich-chairs-invent",
"rich-queens-travel",
"rotten-rocks-remember",
"shaggy-carpets-brake",
"sharp-falcons-begin",
"shy-olives-hang",
@@ -109,14 +115,17 @@
"silent-colts-reply",
"silly-apricots-share",
"six-apricots-kick",
"slimy-humans-impress",
"slimy-needles-taste",
"slow-walls-poke",
"small-socks-confess",
"smooth-planets-admire",
"smooth-stingrays-drum",
"smooth-tools-train",
"soft-adults-smell",
"sour-lemons-hunt",
"spicy-beds-float",
"stale-jobs-drum",
"strong-apes-reply",
"stupid-walls-sell",
"sweet-kiwis-cross",
@@ -133,12 +142,14 @@
"three-lies-pull",
"tidy-clouds-smoke",
"tough-toes-pull",
"twelve-hornets-sip",
"twelve-lemons-smile",
"twenty-beans-pump",
"two-carpets-rhyme",
"two-eyes-knock",
"two-kiwis-help",
"two-tigers-type",
"unlucky-avocados-fix",
"unlucky-papayas-sleep",
"violet-bags-leave",
"violet-lions-help",

View File

@@ -0,0 +1,5 @@
---
"blitz": patch
---
Run codegen tasks after creating a new app if user chose yarn as a package manager

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Remove trailing comma from tsconfig.json file in the new app template"

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Add ts-jest to dependencies in new app templates

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---
Set correct packages versions in package.json with upgrade-legacy codemod

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---
Fix codemod to accept a self closing `DocumentHead` in the `_document` page

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Add `@testing-library/jest-dom` to new app dependecies

View File

@@ -6,7 +6,7 @@
<img alt="" src="https://img.shields.io/badge/Join%20our%20community-6700EB.svg?style=for-the-badge&labelColor=000000&logoWidth=20&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAQ9SURBVHgB7d3dVdtAEIbhcSpICUoH0IEogQqSVBBSAU4FSSpIOoAORAfQgSghHXzZ1U/YcMD4R9rZmf2ec3y448LyiNf27iLiGIAmPLrweC9Un3DhrzG6EarLNP09nlwJ1SOZ/lQr5N80/S/p2QMVCBf5N17XCfm1Y/rBHqjAG9PPHvBsz+mf9WAP+HLA9M/YA14cOP2payH7jpj+VCtk1wnTP+vj7xCy6cTpn7EHLMLp059iD1iD8eveJbVCNsSLheX1YA/YgOWnf8YeKB3Wmf7Ud6Fy4f/FHmtpxbl3YlC4MJ/Cj0bWdwPnPbARg+L0S54XQHS32WwuxClzd4CM0z9rPfeAuTtA5ulPXYQ7wZ04Y+oOoDD9KZc9YOoOoDj9s4dwFzgXR6w1wIPoOvPWA9buAHEJ173o3gWiy3AnuBUHLEbgmYwvAk1/wuM8vAgexThzbwPDkx7/DHwVXfFOxP2GmsKd4Ab6zPeAyU8CI7AHFmH2BRCBPXAyk18GzUrqAXCTiR4ssyj0VFw/oCU8+e+RZ33AWz6KMaYbIIWxB+JSLs1bsbkeMN0AqakHvoku9oA2sAfqBvbAQdw0QArsgb25aYBUQT3QgT2gB+yBuqGcHij2UCqXDZACe2Anlw2QYg/QAOyBuoE98CL3DZDCuK4/rh/Q7oGL6U+TOvcNkJoijN8X1C48+T+g75eQDrAH/qmqAVJgDwyqaoAUe4AGYA/UDZX3QLUNkEIZPRCd5+6BahsgVUgPROwBTSijB7jpVAvGHriHvmw9wAZ4BpX1ABvgmakHtPcbRuwBTWAPULgAV9D/jKDY9YRvwvgEaurD44uQHvAol7qBW7WKluVtIHiUS7GyvA0s6CiXDnxrpQfsgbqBS7GKk/2jYHCrVlGyfxTMrVo0ALdq1Q3sgSKofh0M9oA61a+D2QM0AHugbmAPqClmSRjK2apVVQ8UsySsoK1aHdgDesCtWnUDeyCrIpeFg1u3sylyWTi3btMA7IG6gT2wuuK3hoE9sKrit4YVslWLPaAN7IG6ocKt2zmY2h4O9sDiTG0PZw/QANy6XTewBxZj9ogYVHy025LMHhEz9cBn0We6B0yfERReBLfhx0/R1YQHPx/QBPbA0VwcEwf2wNFcHBPHHjiem3MC2QPHcXdSaJjA+KfgTPQ8hhfjBzHC40mhlzJ+Xq9lK4a4PCs43AVaGTed5mZq+iOXZwWHi3AnOj2wFWNcnxYe7gTxLtBKHuamP/J+Wnh8a5irB7ZC5Yk9gPX1QuXC+usHWqGyhYvUYR0a7zboUOFCNVhnk0krZAOW7wFOvzXhom2xnEbIHizTA1wEYhWW6YFGyC6c1gOcfg9wfA80Qj7g8B7g9HuCww+haIR8wf49wOn3Cvv9k8tGyC/s7gFOv3fY3QONkH+v9MBWqB7PeqDn9FcIT//kcitUn6kHOu/T/xfWzlQy3dEHhwAAAABJRU5ErkJggg==">
</a>
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
<a aria-label="All Contributors" href="#contributors-"><img alt="" src="https://img.shields.io/badge/all_contributors-388-17BB8A.svg?style=for-the-badge&labelColor=000000"></a>
<a aria-label="All Contributors" href="#contributors-"><img alt="" src="https://img.shields.io/badge/all_contributors-389-17BB8A.svg?style=for-the-badge&labelColor=000000"></a>
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<a aria-label="License" href="https://github.com/blitz-js/blitz/blob/canary/LICENSE">
<img alt="" src="https://img.shields.io/npm/l/blitz.svg?style=for-the-badge&labelColor=000000&color=blue">
@@ -708,6 +708,7 @@ Thanks to these wonderful people ([emoji key](https://allcontributors.org/docs/e
<td align="center"><a href="https://github.com/tommywong-dev"><img src="https://avatars.githubusercontent.com/u/79971095?v=4?s=100" width="100px;" alt=""/><br /><sub><b>tommywong-dev</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=tommywong-dev" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/datner"><img src="https://avatars.githubusercontent.com/u/22598347?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Datner</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=datner" title="Documentation">📖</a> <a href="https://github.com/blitz-js/blitz/commits?author=datner" title="Code">💻</a></td>
<td align="center"><a href="https://chaiwattsw.com/"><img src="https://avatars.githubusercontent.com/u/30198386?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Chaiwat Trisuwan</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=chaiwattsw" title="Documentation">📖</a> <a href="https://github.com/blitz-js/blitz/commits?author=chaiwattsw" title="Code">💻</a></td>
<td align="center"><a href="oltdaniel.eu"><img src="https://avatars.githubusercontent.com/u/53529846?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Daniel Oltmanns</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=oltdaniel" title="Documentation">📖</a> <a href="https://github.com/blitz-js/blitz/commits?author=oltdaniel" title="Code">💻</a></td>
</tr>
</table>

View File

@@ -29,7 +29,7 @@
"@blitzjs/rpc": "workspace:*",
"@hookform/resolvers": "2.8.8",
"@prisma/client": "4.0.0",
"blitz": "workspace:2.0.0-alpha.67",
"blitz": "workspace:2.0.0-alpha.68",
"next": "12.2.0",
"prisma": "4.0.0",
"react": "18.0.0",

View File

@@ -1,5 +1,15 @@
# @blitzjs/auth
## 2.0.0-alpha.68
### Patch Changes
- Updated dependencies [271c58ac]
- Updated dependencies [630c7181]
- Updated dependencies [f0ca738d]
- Updated dependencies [41608c4c]
- blitz@2.0.0-alpha.68
## 2.0.0-alpha.67
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/auth",
"version": "2.0.0-alpha.67",
"version": "2.0.0-alpha.68",
"scripts": {
"build": "unbuild",
"predev": "wait-on -d 250 ../blitz/dist/index-server.d.ts",
@@ -26,7 +26,7 @@
"@types/secure-password": "3.1.1",
"b64-lite": "1.4.0",
"bad-behavior": "1.0.1",
"blitz": "2.0.0-alpha.67",
"blitz": "2.0.0-alpha.68",
"cookie": "0.4.1",
"cookie-session": "2.0.0",
"debug": "4.3.3",
@@ -40,7 +40,7 @@
"url": "0.11.0"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.67",
"@blitzjs/config": "workspace:2.0.0-alpha.68",
"@testing-library/react": "13.0.0",
"@testing-library/react-hooks": "7.0.2",
"@types/cookie": "0.4.1",

View File

@@ -1,5 +1,12 @@
# @blitzjs/next
## 2.0.0-alpha.68
### Patch Changes
- Updated dependencies [630c7181]
- @blitzjs/rpc@2.0.0-alpha.68
## 2.0.0-alpha.67
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/next",
"version": "2.0.0-alpha.67",
"version": "2.0.0-alpha.68",
"scripts": {
"build": "unbuild",
"dev": "pnpm predev && pnpm watch unbuild src --wait=0.2",
@@ -24,7 +24,7 @@
"eslint.js"
],
"dependencies": {
"@blitzjs/rpc": "2.0.0-alpha.67",
"@blitzjs/rpc": "2.0.0-alpha.68",
"@tanstack/react-query": "4.0.10",
"@types/hoist-non-react-statics": "3.3.1",
"debug": "4.3.3",
@@ -34,7 +34,7 @@
"supports-color": "8.1.1"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.67",
"@blitzjs/config": "workspace:2.0.0-alpha.68",
"@testing-library/dom": "8.13.0",
"@testing-library/jest-dom": "5.16.3",
"@testing-library/react": "13.0.0",
@@ -44,7 +44,7 @@
"@types/react": "18.0.1",
"@types/react-dom": "17.0.14",
"@types/testing-library__react-hooks": "4.0.0",
"blitz": "2.0.0-alpha.67",
"blitz": "2.0.0-alpha.68",
"cross-spawn": "7.0.3",
"find-up": "4.1.0",
"next": "12.2.0",

View File

@@ -1,5 +1,12 @@
# @blitzjs/rpc
## 2.0.0-alpha.68
### Patch Changes
- 630c7181: Use internal branded blitz logger for @blitzjs/rpc
- @blitzjs/auth@2.0.0-alpha.68
## 2.0.0-alpha.67
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/rpc",
"version": "2.0.0-alpha.67",
"version": "2.0.0-alpha.68",
"scripts": {
"build": "unbuild",
"predev": "wait-on -d 250 ../blitz/dist/index-server.d.ts && wait-on -d 250 ../blitz-auth/dist/index-browser.d.ts",
@@ -20,7 +20,7 @@
"dist/**"
],
"dependencies": {
"@blitzjs/auth": "2.0.0-alpha.67",
"@blitzjs/auth": "2.0.0-alpha.68",
"@tanstack/react-query": "4.0.10",
"b64-lite": "1.4.0",
"bad-behavior": "1.0.1",
@@ -30,11 +30,11 @@
"supports-color": "8.1.1"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.67",
"@blitzjs/config": "workspace:2.0.0-alpha.68",
"@types/debug": "4.1.7",
"@types/react": "18.0.1",
"@types/react-dom": "17.0.14",
"blitz": "2.0.0-alpha.67",
"blitz": "2.0.0-alpha.68",
"next": "12.2.0",
"react": "18.0.0",
"react-dom": "18.0.0",

View File

@@ -1,7 +1,8 @@
import {assert, Ctx, prettyMs} from "blitz"
import {assert, baseLogger, Ctx, newLine, prettyMs} from "blitz"
import {NextApiRequest, NextApiResponse} from "next"
import {deserialize, serialize as superjsonSerialize} from "superjson"
import {resolve} from "path"
import chalk from "chalk"
// TODO - optimize end user server bundles by not exporting all client stuff here
export * from "./index-browser"
@@ -156,6 +157,13 @@ export function rpcHandler(config: RpcConfig) {
const relativeRoutePath = (req.query.blitz as string[])?.join("/")
const routePath = "/" + relativeRoutePath
const log = baseLogger().getChildLogger({
prefix: [routePath.replace("/api/rpc/", "") + "()"],
})
const customChalk = new chalk.Instance({
level: log.settings.type === "json" ? 0 : chalk.level,
})
const loadableResolver = resolverMap?.[routePath]
if (!loadableResolver) {
throw new Error("No resolver for path: " + routePath)
@@ -175,7 +183,7 @@ export function rpcHandler(config: RpcConfig) {
if (typeof req.body.params === "undefined") {
const error = {message: "Request body is missing the `params` key"}
console.error(error.message)
log.error(error.message)
res.status(400).json({
result: null,
error,
@@ -189,11 +197,11 @@ export function rpcHandler(config: RpcConfig) {
meta: req.body.meta?.params,
})
console.info("Starting with input:", data ? data : JSON.stringify(data))
log.info(customChalk.dim("Starting with input:"), data ? data : JSON.stringify(data))
const startTime = Date.now()
const result = await resolver(data, (res as any).blitzCtx)
const resolverDuration = Date.now() - startTime
console.debug("Result:", result ? result : JSON.stringify(result))
log.debug(customChalk.dim("Result:"), result ? result : JSON.stringify(result))
const serializerStartTime = Date.now()
const serializedResult = superjsonSerialize(result)
@@ -207,16 +215,22 @@ export function rpcHandler(config: RpcConfig) {
result: serializedResult.meta,
},
})
console.debug(`Next.js serialization:${prettyMs(Date.now() - nextSerializerStartTime)}`)
log.debug(
customChalk.dim(
`Next.js serialization:${prettyMs(Date.now() - nextSerializerStartTime)}`,
),
)
const serializerDuration = Date.now() - serializerStartTime
const duration = Date.now() - startTime
console.info(
`Finished: resolver:${prettyMs(resolverDuration)} serializer:${prettyMs(
serializerDuration,
)} total:${prettyMs(duration)}`,
log.info(
customChalk.dim(
`Finished: resolver:${prettyMs(resolverDuration)} serializer:${prettyMs(
serializerDuration,
)} total:${prettyMs(duration)}`,
),
)
console.log("\n")
newLine()
return
} catch (error: any) {
@@ -226,8 +240,8 @@ export function rpcHandler(config: RpcConfig) {
config.onError?.(error)
console.error(error)
console.log("\n")
log.error(error)
newLine()
if (!error.statusCode) {
error.statusCode = 500
@@ -246,7 +260,7 @@ export function rpcHandler(config: RpcConfig) {
}
} else {
// Everything else is error
console.warn(`${req.method} method not supported`)
log.warn(`${req.method} method not supported`)
res.status(404).end()
return
}

View File

@@ -1,5 +1,18 @@
# blitz
## 2.0.0-alpha.68
### Patch Changes
- 271c58ac: Comment out generate command import until we add the full support back
- 630c7181: Use internal branded blitz logger for @blitzjs/rpc
- f0ca738d: Run codegen tasks on blitz dev command
- 41608c4c: Run codegen tasks after creating a new app if user chose yarn as a package manager
- Updated dependencies [70b334a2]
- Updated dependencies [dd299ae8]
- Updated dependencies [078fe474]
- @blitzjs/generator@2.0.0-alpha.68
## 2.0.0-alpha.67
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "blitz",
"version": "2.0.0-alpha.67",
"version": "2.0.0-alpha.68",
"scripts": {
"build": "unbuild",
"dev": "watch unbuild src --wait=0.2",
@@ -23,7 +23,7 @@
"blitz": "bin/blitz"
},
"dependencies": {
"@blitzjs/generator": "2.0.0-alpha.67",
"@blitzjs/generator": "2.0.0-alpha.68",
"arg": "5.0.1",
"boxen": "7.0.0",
"chalk": "^4.1.0",
@@ -55,7 +55,7 @@
"watchpack": "2.1.1"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.67",
"@blitzjs/config": "workspace:2.0.0-alpha.68",
"@types/cookie": "0.4.1",
"@types/cross-spawn": "6.0.2",
"@types/debug": "4.1.7",

View File

@@ -1,261 +1,268 @@
export {}
// import arg from "arg"
// import {CliCommand} from "../index"
// import prompts from "prompts"
import arg from "arg"
import {CliCommand} from "../index"
import prompts from "prompts"
import {
capitalize,
pluralCamel,
pluralPascal,
singleCamel,
singlePascal,
uncapitalize,
} from "@blitzjs/generator"
// const getIsTypeScript = async () =>
// require("fs").existsSync(require("path").join(process.cwd(), "tsconfig.json"))
const getIsTypeScript = async () =>
require("fs").existsSync(require("path").join(process.cwd(), "tsconfig.json"))
// enum ResourceType {
// All = "all",
// Crud = "crud",
// Model = "model",
// Pages = "pages",
// Queries = "queries",
// Query = "query",
// Mutations = "mutations",
// Mutation = "mutation",
// Resource = "resource",
// }
enum ResourceType {
All = "all",
Crud = "crud",
Model = "model",
Pages = "pages",
Queries = "queries",
Query = "query",
Mutations = "mutations",
Mutation = "mutation",
Resource = "resource",
}
// function modelName(input: string = "") {
// return singleCamel(input)
// }
// function modelNames(input: string = "") {
// return pluralCamel(input)
// }
// function ModelName(input: string = "") {
// return singlePascal(input)
// }
// function ModelNames(input: string = "") {
// return pluralPascal(input)
// }
function modelName(input: string = "") {
return singleCamel(input)
}
function modelNames(input: string = "") {
return pluralCamel(input)
}
function ModelName(input: string = "") {
return singlePascal(input)
}
function ModelNames(input: string = "") {
return pluralPascal(input)
}
// const generatorMap = {
// [ResourceType.All]: [
// PageGenerator,
// FormGenerator,
// QueriesGenerator,
// MutationsGenerator,
// ModelGenerator,
// ],
// [ResourceType.Crud]: [MutationsGenerator, QueriesGenerator],
// [ResourceType.Model]: [ModelGenerator],
// [ResourceType.Pages]: [PageGenerator, FormGenerator],
// [ResourceType.Queries]: [QueriesGenerator],
// [ResourceType.Query]: [QueryGenerator],
// [ResourceType.Mutations]: [MutationsGenerator],
// [ResourceType.Mutation]: [MutationGenerator],
// [ResourceType.Resource]: [QueriesGenerator, MutationsGenerator, ModelGenerator],
// }
const generatorMap = {
// [ResourceType.All]: [
// PageGenerator,
// FormGenerator,
// QueriesGenerator,
// MutationsGenerator,
// ModelGenerator,
// ],
// [ResourceType.Crud]: [MutationsGenerator, QueriesGenerator],
// [ResourceType.Model]: [ModelGenerator],
// [ResourceType.Pages]: [PageGenerator, FormGenerator],
// [ResourceType.Queries]: [QueriesGenerator],
// [ResourceType.Query]: [QueryGenerator],
// [ResourceType.Mutations]: [MutationsGenerator],
// [ResourceType.Mutation]: [MutationGenerator],
// [ResourceType.Resource]: [QueriesGenerator, MutationsGenerator, ModelGenerator],
}
// const args = arg(
// {
// // Types
// "--help": Boolean,
// "--type": String,
// "--name": String,
// "--context": String,
// "--parent": String,
// "--dry-run": Boolean,
// "--env": String,
const args = arg(
{
// Types
"--help": Boolean,
"--type": String,
"--name": String,
"--context": String,
"--parent": String,
"--dry-run": Boolean,
"--env": String,
// // Aliases
// "-e": "--env",
// "-n": "--name",
// "-t": "--type",
// "-c": "--context",
// "-p": "--dry-run",
// },
// {
// permissive: true,
// },
// )
// Aliases
"-e": "--env",
"-n": "--name",
"-t": "--type",
"-c": "--context",
"-p": "--dry-run",
},
{
permissive: true,
},
)
// let selectedType: string | keyof typeof generatorMap
// let selectedModelName: string | undefined
// let selectedContext: string | undefined
// let selectedParent: string | undefined = args["--parent"] ?? undefined
let selectedType: string | keyof typeof generatorMap
let selectedModelName: string | undefined
let selectedContext: string | undefined
let selectedParent: string | undefined = args["--parent"] ?? undefined
// const getModelNameAndContext = (
// modelName: string,
// context?: string,
// ): {model: string; context?: string} => {
// const modelSegments = modelName.split(/[\\/]/)
const getModelNameAndContext = (
modelName: string,
context?: string,
): {model: string; context?: string} => {
const modelSegments = modelName.split(/[\\/]/)
// if (modelSegments.length > 1) {
// return {
// model: modelSegments[modelSegments.length - 1] as string,
// context: require("path").join(...modelSegments.slice(0, modelSegments.length - 1)),
// }
// }
if (modelSegments.length > 1) {
return {
model: modelSegments[modelSegments.length - 1] as string,
context: require("path").join(...modelSegments.slice(0, modelSegments.length - 1)),
}
}
// if (Boolean(context)) {
// const contextSegments = (context as string).split(/[\\/]/)
if (Boolean(context)) {
const contextSegments = (context as string).split(/[\\/]/)
// return {
// model: modelName,
// context: require("path").join(...contextSegments),
// }
// }
return {
model: modelName,
context: require("path").join(...contextSegments),
}
}
// return {
// model: modelName,
// }
// }
return {
model: modelName,
}
}
// const validateModelName = (modelName: string): void => {
// const RESERVED_MODEL_NAMES = ["page", "api", "query", "mutation"]
// if (RESERVED_MODEL_NAMES.includes(modelName)) {
// throw new Error(`Names ${RESERVED_MODEL_NAMES} or their plurals cannot be used as model names`)
// }
// if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(modelName)) {
// throw new Error(
// `Invalid model name: "${modelName}". Model names need to adhere to this regular expression: [A-Za-z][A-Za-z0-9_]*`,
// )
// }
// }
const validateModelName = (modelName: string): void => {
const RESERVED_MODEL_NAMES = ["page", "api", "query", "mutation"]
if (RESERVED_MODEL_NAMES.includes(modelName)) {
throw new Error(`Names ${RESERVED_MODEL_NAMES} or their plurals cannot be used as model names`)
}
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(modelName)) {
throw new Error(
`Invalid model name: "${modelName}". Model names need to adhere to this regular expression: [A-Za-z][A-Za-z0-9_]*`,
)
}
}
// const determineType = async () => {
// if (
// !args["_"].slice(1)[0] ||
// (args["_"].slice(1)[0] &&
// !Object.keys(generatorMap).includes(args["_"].slice(1)[0]?.toLowerCase() as string))
// ) {
// const res = await prompts({
// type: "select",
// name: "type",
// message: "Which files to generate",
// initial: 0,
// choices: Object.entries(generatorMap).map((c) => {
// return {title: c[0], value: c[0]}
// }),
// })
const determineType = async () => {
if (
!args["_"].slice(1)[0] ||
(args["_"].slice(1)[0] &&
!Object.keys(generatorMap).includes(args["_"].slice(1)[0]?.toLowerCase() as string))
) {
const res = await prompts({
type: "select",
name: "type",
message: "Which files to generate",
initial: 0,
choices: Object.entries(generatorMap).map((c) => {
return {title: c[0], value: c[0]}
}),
})
// selectedType = res.type
// } else {
// selectedType = args["_"].slice(1)[0]?.toLowerCase() as string
// }
// }
selectedType = res.type
} else {
selectedType = args["_"].slice(1)[0]?.toLowerCase() as string
}
}
// const determineName = async () => {
// if (!args["_"].slice(1)[1]) {
// const res = await prompts({
// type: "text",
// name: "model",
// message: `The name of your model, like "user". Can be singular or plural - same result`,
// })
const determineName = async () => {
if (!args["_"].slice(1)[1]) {
const res = await prompts({
type: "text",
name: "model",
message: `The name of your model, like "user". Can be singular or plural - same result`,
})
// const {model, context} = getModelNameAndContext(res.model)
// selectedModelName = model
// selectedContext = context
// } else {
// const {model, context} = getModelNameAndContext(args["_"].slice(1)[1]!)
// selectedModelName = model
// selectedContext = context
// }
// }
const {model, context} = getModelNameAndContext(res.model)
selectedModelName = model
selectedContext = context
} else {
const {model, context} = getModelNameAndContext(args["_"].slice(1)[1]!)
selectedModelName = model
selectedContext = context
}
}
// const determineContext = async () => {
// if (args["--context"] && !selectedModelName) {
// if (args["--name"] && args["--name"].includes("/")) {
// throw new Error("Your model should not contain a context when supplying a context explicitly")
// }
const determineContext = async () => {
if (args["--context"] && !selectedModelName) {
if (args["--name"] && args["--name"].includes("/")) {
throw new Error("Your model should not contain a context when supplying a context explicitly")
}
// const res = await prompts({
// type: "text",
// name: "model",
// message: `The name of your model, like "user". Can be singular or plural - same result`,
// })
const res = await prompts({
type: "text",
name: "model",
message: `The name of your model, like "user". Can be singular or plural - same result`,
})
// if (res.model.includes("/")) {
// throw new Error("Your model should not contain a context when supplying a context explicitly")
// }
// const {model, context} = getModelNameAndContext(res.model, args["--context"])
// selectedModelName = model
// selectedContext = context
// }
// }
if (res.model.includes("/")) {
throw new Error("Your model should not contain a context when supplying a context explicitly")
}
const {model, context} = getModelNameAndContext(res.model, args["--context"])
selectedModelName = model
selectedContext = context
}
}
// const getHelp = async () => {
// if (args["--help"]) {
// console.log(`
// # The 'crud' type will generate all queries & mutations for a model
const getHelp = async () => {
if (args["--help"]) {
console.log(`
# The 'crud' type will generate all queries & mutations for a model
// > blitz generate --type crud --name productVariant
> blitz generate --type crud --name productVariant
// # The 'all' generator will scaffold out everything possible for a model
# The 'all' generator will scaffold out everything possible for a model
// > blitz generate --type all --name products
> blitz generate --type all --name products
// # The '--context' flag will allow you to generate files in a nested folder
# The '--context' flag will allow you to generate files in a nested folder
// > blitz generate --type pages --name projects --context admin
> blitz generate --type pages --name projects --context admin
// # Context can also be supplied in the model name directly
# Context can also be supplied in the model name directly
// > blitz generate --type pages --name admin/projects
> blitz generate --type pages --name admin/projects
// # To generate nested routes for dependent models (e.g. Projects that contain Tasks), specify a parent model.
// For example, this command generates pages under app/tasks/pages/projects/[projectId]/tasks/
# To generate nested routes for dependent models (e.g. Projects that contain Tasks), specify a parent model.
For example, this command generates pages under app/tasks/pages/projects/[projectId]/tasks/
// > blitz generate --type all --name tasks --parent=projects
> blitz generate --type all --name tasks --parent=projects
// # Database models can also be generated directly from the CLI.
// Model fields can be specified with any generator that generates a database model ("all", "model", "resource").
// Both of the commands below will generate the proper database model for a Task.
# Database models can also be generated directly from the CLI.
Model fields can be specified with any generator that generates a database model ("all", "model", "resource").
Both of the commands below will generate the proper database model for a Task.
// > blitz generate --type model --name task name:string completed:boolean:default=false belongsTo:project?
> blitz generate --type model --name task name:string completed:boolean:default=false belongsTo:project?
// > blitz generate --type all --name tasks name:string completed:boolean:default=false belongsTo:project?
> blitz generate --type all --name tasks name:string completed:boolean:default=false belongsTo:project?
// `)
`)
// process.exit(0)
// }
// }
process.exit(0)
}
}
// const generate: CliCommand = async (argv) => {
// await getHelp()
// await determineType()
// await determineContext()
// if (!selectedModelName) {
// await determineName()
// }
const generate: CliCommand = async (argv) => {
await getHelp()
await determineType()
await determineContext()
if (!selectedModelName) {
await determineName()
}
// try {
// const singularRootContext = modelName(selectedModelName)
// validateModelName(singularRootContext)
try {
const singularRootContext = modelName(selectedModelName)
validateModelName(singularRootContext)
// // const {loadConfigProduction} = await import("next/dist/server/config-shared")
// // const blitzConfig = loadConfigProduction(process.cwd())
// const generators = generatorMap[selectedType as keyof typeof generatorMap]
// const {loadConfigProduction} = await import("next/dist/server/config-shared")
// const blitzConfig = loadConfigProduction(process.cwd())
const generators = generatorMap[selectedType as keyof typeof generatorMap]
// for (const GeneratorClass of generators) {
// const generator = new GeneratorClass({
// destinationRoot: require("path").resolve(),
// // templateDir: blitzConfig.codegen?.templateDir,
// extraArgs: args["_"].slice(3) as string[],
// modelName: singularRootContext,
// modelNames: modelNames(singularRootContext),
// ModelName: ModelName(singularRootContext),
// ModelNames: ModelNames(singularRootContext),
// parentModel: modelName(selectedParent),
// parentModels: modelNames(selectedParent),
// ParentModel: ModelName(selectedParent),
// ParentModels: ModelNames(selectedParent),
// name: uncapitalize(selectedModelName!),
// Name: capitalize(selectedModelName!),
// dryRun: args["--dry-run"],
// context: selectedContext,
// useTs: await getIsTypeScript(),
// })
// await generator.run()
// }
// } catch (error) {
// console.log(error)
// process.exit(1)
// }
// }
for (const GeneratorClass of generators) {
const generator = new GeneratorClass({
destinationRoot: require("path").resolve(),
// templateDir: blitzConfig.codegen?.templateDir,
extraArgs: args["_"].slice(3) as string[],
modelName: singularRootContext,
modelNames: modelNames(singularRootContext),
ModelName: ModelName(singularRootContext),
ModelNames: ModelNames(singularRootContext),
parentModel: modelName(selectedParent),
parentModels: modelNames(selectedParent),
ParentModel: ModelName(selectedParent),
ParentModels: ModelNames(selectedParent),
name: uncapitalize(selectedModelName!),
Name: capitalize(selectedModelName!),
dryRun: args["--dry-run"],
context: selectedContext,
useTs: await getIsTypeScript(),
})
await generator.run()
}
} catch (error) {
console.log(error)
process.exit(1)
}
}
// export {generate}
export {generate}

View File

@@ -8,6 +8,7 @@ import {AppGenerator, AppGeneratorOptions, getLatestVersion} from "@blitzjs/gene
import {loadEnvConfig} from "../../utils/env"
import {runPrisma} from "../../utils/run-prisma"
import {checkLatestVersion} from "../utils/check-latest-version"
import {codegenTasks} from "../utils/codegen-tasks"
const forms: Record<AppGeneratorOptions["form"], string> = {
finalform: "React Final Form (recommended)",
@@ -269,6 +270,10 @@ const newApp: CliCommand = async (argv) => {
)
const result = await runPrisma(["migrate", "dev", "--name", "Initial migration"], true)
if (!result.success) throw new Error()
if (projectPkgManger === "yarn") {
await codegenTasks()
}
} catch (error) {
postInstallSteps.push(
"blitz prisma migrate dev (when asked, you can name the migration anything)",

View File

@@ -41,7 +41,7 @@ export const codegenTasks = async () => {
let prismaSpinner = log.spinner(`Generating Prisma client`).start()
const result = await runPrisma(["generate"], true)
if (result.success) {
prismaSpinner.succeed()
prismaSpinner.succeed(log.greenText("Generated Prisma client"))
} else {
prismaSpinner.fail()
console.log("\n" + result.stderr)

View File

@@ -20,6 +20,7 @@ export async function build(config: ServerConfig) {
export async function dev(config: ServerConfig) {
const {rootFolder, nextBin} = await normalize({...config, env: "dev"})
await codegenTasks()
// void checkLatestVersion()
if (customServerExists()) {
console.log("Using your custom server")

View File

@@ -58,17 +58,19 @@ export function readVersions() {
return versions
}
export function resolveVersionType(version: string) {
export function resolveVersionType(
version: string,
): "alpha" | "beta" | "canary" | "stable" | "danger" | "latest" {
if (version.includes("alpha")) {
return "alpha" as const
return "alpha"
}
if (version.includes("beta")) {
return "beta" as const
return "beta"
}
if (version.includes("danger")) {
return "danger" as const
return "danger"
}
if (version.includes("canary")) {

View File

@@ -92,6 +92,10 @@ const withProgress = (str: string) => {
return withCaret(str)
}
const greenText = (str: string) => {
return `${c.green(str)}`
}
/**
* Logs a branded purple message to stdout.
*
@@ -182,6 +186,7 @@ export const log = {
progress,
spinner,
success,
greenText,
error,
variable,
debug,

View File

@@ -1,5 +1,23 @@
# @blitzjs/codemod
## 2.0.0-alpha.68
### Patch Changes
- 06427f67: Throw error if cookiePrefix is undefined when running codemod
- f120f672: Add DocumentProps & DocumentContext to the codemod import map
- 8dfaad08: Set correct packages versions in package.json with upgrade-legacy codemod
- cb55ed26: Fix codemod to accept a self closing `DocumentHead` in the `_document` page
- Updated dependencies [271c58ac]
- Updated dependencies [630c7181]
- Updated dependencies [f0ca738d]
- Updated dependencies [41608c4c]
- Updated dependencies [70b334a2]
- Updated dependencies [dd299ae8]
- Updated dependencies [078fe474]
- blitz@2.0.0-alpha.68
- @blitzjs/generator@2.0.0-alpha.68
## 2.0.0-alpha.67
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/codemod",
"version": "2.0.0-alpha.67",
"version": "2.0.0-alpha.68",
"scripts": {
"build": "unbuild",
"dev": "watch unbuild src --wait=0.2",
@@ -25,9 +25,9 @@
"@babel/plugin-proposal-class-properties": "7.17.12",
"@babel/plugin-syntax-jsx": "7.17.12",
"@babel/plugin-syntax-typescript": "7.17.12",
"@blitzjs/generator": "2.0.0-alpha.67",
"@blitzjs/generator": "2.0.0-alpha.68",
"arg": "5.0.1",
"blitz": "2.0.0-alpha.67",
"blitz": "2.0.0-alpha.68",
"chalk": "^4.1.0",
"cross-spawn": "7.0.3",
"debug": "4.3.3",

View File

@@ -1,4 +1,4 @@
import j, {ImportDeclaration} from "jscodeshift"
import j, {ImportDeclaration, ImportDefaultSpecifier, ImportSpecifier} from "jscodeshift"
import * as fs from "fs-extra"
import path from "path"
import {
@@ -11,13 +11,22 @@ import {
getAllFiles,
getCollectionFromSource,
wrapDeclaration,
findIdentifier,
removeImport,
replaceImport,
replaceIdentifiers,
replaceBlitzPkgsVersions,
} from "./utils"
import {log} from "blitz"
const CURRENT_BLITZ_TAG = "alpha"
class ExpectedError extends Error {
constructor(message: string) {
super(message)
this.name = "Expected Error"
}
}
const isInternalBlitzMonorepoDevelopment = fs.existsSync(
path.join(__dirname, "../../../blitz-next"),
)
@@ -81,19 +90,11 @@ const upgradeLegacy = async () => {
steps.push({
name: "update dependencies in package.json",
action: async () => {
let packageJsonPath = require(path.resolve("package.json"))
packageJsonPath.dependencies["react"] = "latest"
packageJsonPath.dependencies["react-dom"] = "latest"
packageJsonPath.dependencies["@blitzjs/next"] = "alpha"
packageJsonPath.dependencies["@blitzjs/rpc"] = "alpha"
packageJsonPath.dependencies["@blitzjs/auth"] = "alpha"
packageJsonPath.dependencies["blitz"] = "alpha"
packageJsonPath.dependencies["next"] = "latest"
packageJsonPath.dependencies["prisma"] = "latest"
packageJsonPath.dependencies["@prisma/client"] = "latest"
packageJsonPath.devDependencies["typescript"] = isTypescript && "latest"
const packageJson = require(path.resolve("package.json"))
fs.writeFileSync(path.resolve("package.json"), JSON.stringify(packageJsonPath, null, " "))
const newPackageJson = await replaceBlitzPkgsVersions(packageJson, CURRENT_BLITZ_TAG)
fs.writeFileSync(path.resolve("package.json"), JSON.stringify(newPackageJson, null, " "))
},
})
@@ -111,6 +112,8 @@ const upgradeLegacy = async () => {
Document: "next/document",
DocumentHead: "next/document",
DocumentProps: "next/document",
DocumentContext: "next/document",
Html: "next/document",
Main: "next/document",
BlitzScript: "next/document",
@@ -401,7 +404,7 @@ const upgradeLegacy = async () => {
replaceTemplateValues(blitzClient),
)
} else {
throw new Error("App directory doesn't exit")
throw new ExpectedError("App directory doesn't exit")
}
},
})
@@ -416,19 +419,25 @@ const upgradeLegacy = async () => {
)
if (cookieIdentifier.length) {
const cookiePrefix = cookieIdentifier.get().parentPath.value.value.value
const blitzClientProgram = getCollectionFromSource(
path.join(appDir, `blitz-client.${isTypescript ? "ts" : "js"}`),
)
const cookieIdentifierBlitzClient = blitzClientProgram.find(
j.Identifier,
(node) => node.name === "cookiePrefix",
)
cookieIdentifierBlitzClient.get().parentPath.value.value.value = cookiePrefix
if (cookiePrefix) {
const blitzClientProgram = getCollectionFromSource(
path.join(appDir, `blitz-client.${isTypescript ? "ts" : "js"}`),
)
const cookieIdentifierBlitzClient = blitzClientProgram.find(
j.Identifier,
(node) => node.name === "cookiePrefix",
)
cookieIdentifierBlitzClient.get().parentPath.value.value.value = cookiePrefix
fs.writeFileSync(
`${appDir}/blitz-client.${isTypescript ? "ts" : "js"}`,
blitzClientProgram.toSource(),
)
fs.writeFileSync(
`${appDir}/blitz-client.${isTypescript ? "ts" : "js"}`,
blitzClientProgram.toSource(),
)
} else {
throw new ExpectedError(
"Cookie Prefix is undefined & not a string. Please set your cookie prefix manually in app/blitz-client",
)
}
} else {
log.error("Cookie Prefix not found in blitz config file")
}
@@ -921,28 +930,58 @@ const upgradeLegacy = async () => {
)
const importStatements = findImport(program, "next/document")
importStatements?.remove()
let nextDocumentImportPaths: (ImportSpecifier | ImportDefaultSpecifier)[] = []
importStatements?.forEach((path) => {
path.value.specifiers?.forEach((s) => {
if (s.type === "ImportSpecifier") {
// Go through the typical imports required for Next.js and build the correct import specifier
switch (s.imported.name) {
case "Document":
nextDocumentImportPaths.unshift(
j.importDefaultSpecifier(j.identifier("Document")),
)
break
case "BlitzScript":
nextDocumentImportPaths.push(j.importSpecifier(j.identifier("NextScript")))
break
case "Html":
nextDocumentImportPaths.push(j.importSpecifier(j.identifier("Html")))
break
case "Main":
nextDocumentImportPaths.push(j.importSpecifier(j.identifier("Main")))
break
case "DocumentHead":
nextDocumentImportPaths.push(j.importSpecifier(j.identifier("Head")))
break
case "DocumentProps":
nextDocumentImportPaths.push(j.importSpecifier(j.identifier("DocumentProps")))
break
case "DocumentContext":
nextDocumentImportPaths.push(j.importSpecifier(j.identifier("DocumentContext")))
break
}
}
})
})
// Add new import statement to the top of the _document page
program
.get()
.value.program.body.unshift(
j.importDeclaration(
[
j.importDefaultSpecifier(j.identifier("Document")),
j.importSpecifier(j.identifier("Html")),
j.importSpecifier(j.identifier("Head")),
j.importSpecifier(j.identifier("Main")),
j.importSpecifier(j.identifier("NextScript")),
],
j.stringLiteral("next/document"),
),
j.importDeclaration([...nextDocumentImportPaths], j.stringLiteral("next/document")),
)
// Remove the old import statements
importStatements?.remove()
const documentHead = program
.find(j.JSXElement, (node) => node.openingElement.name.name === "DocumentHead")
.get()
documentHead.value.openingElement.name.name = "Head"
documentHead.value.closingElement.name.name = "Head"
if (documentHead.value.closingElement) {
documentHead.value.closingElement.name.name = "Head"
}
const blitzScript = program.find(j.Identifier, (node) => node.name === "BlitzScript").get()
blitzScript.value.name = "NextScript"
@@ -1026,7 +1065,7 @@ const upgradeLegacy = async () => {
})
if (errors > 0) {
throw new Error("Local middleware is not supported")
throw new ExpectedError("Local middleware is not supported")
}
},
})
@@ -1093,7 +1132,7 @@ const upgradeLegacy = async () => {
})
if (errors > 0) {
throw new Error(
throw new ExpectedError(
"\n invokeWithMiddleware is not supported. \n Use invokeWithCtx instead: https://canary.blitzjs.com/docs/resolver-server-utilities#invoke-with-ctx \n Fix the files above, then run the codemod again.",
)
}
@@ -1166,7 +1205,7 @@ const upgradeLegacy = async () => {
"Don't panic, go to the file with the error & manually fix it. Then run the codemod again. It will continue where it left off.",
),
)
} else {
} else if (!(err instanceof ExpectedError)) {
log.error(
log.withBrand(
"This is an unexpected error. Please ask for help in the discord #general-help channel. https://discord.blitzjs.com",

View File

@@ -12,6 +12,8 @@ import j, {
Identifier,
} from "jscodeshift"
import {parseSync} from "@babel/core"
import {fetchDistTags} from "@blitzjs/generator"
import {PromiseReturnType} from "blitz"
export function findIdentifier(program: Collection<any>, name: string): Collection<Identifier> {
return program.find(j.Identifier, (node) => node.name === name)
@@ -326,3 +328,30 @@ export function replaceIdentifiers(
path.value.name = "NextApiRequest"
})
}
export const replaceBlitzPkgsVersions = async (
packageJson: {dependencies?: Record<string, any>},
npmTag: string,
) => {
let blitzPkgVersion = npmTag
const result = await fetchDistTags("blitz")
if (npmTag in result) {
blitzPkgVersion = result[npmTag]
}
if (!packageJson.dependencies) {
packageJson.dependencies = {}
}
packageJson.dependencies["@blitzjs/next"] = blitzPkgVersion
packageJson.dependencies["@blitzjs/rpc"] = blitzPkgVersion
packageJson.dependencies["@blitzjs/auth"] = blitzPkgVersion
packageJson.dependencies["blitz"] = blitzPkgVersion
packageJson.dependencies["next"] = "12.2.0"
// for zod, we want to use the latest version
const zodResult = await fetchDistTags("zod")
packageJson.dependencies["zod"] = zodResult["latest"] || "latest"
return packageJson
}

View File

@@ -0,0 +1,90 @@
import {describe, it, expect, vi, afterAll} from "vitest"
import {replaceBlitzPkgsVersions} from "../src/utils"
describe("replaceBlitzPkgsVersions", () => {
afterAll(() => {
vi.clearAllMocks()
})
vi.mock("@blitzjs/generator", async () => {
return {
fetchDistTags: vi.fn((pkg: string) => {
if (pkg === "blitz") {
return {alpha: "1.0.0", beta: "2.0.0", danger: "3.0.0"}
}
if (pkg === "zod") {
return {latest: "1.2.3"}
}
}),
}
})
const pkgJson = {
dependencies: {},
}
it("correctly updates versions with the alpha tag", async () => {
expect(await replaceBlitzPkgsVersions(pkgJson, "alpha")).toEqual({
dependencies: {
blitz: "1.0.0",
"@blitzjs/rpc": "1.0.0",
"@blitzjs/auth": "1.0.0",
"@blitzjs/next": "1.0.0",
next: "12.2.0",
zod: "1.2.3",
},
})
})
it("correctly updates versions with the beta tag", async () => {
expect(await replaceBlitzPkgsVersions(pkgJson, "beta")).toEqual({
dependencies: {
blitz: "2.0.0",
"@blitzjs/rpc": "2.0.0",
"@blitzjs/auth": "2.0.0",
"@blitzjs/next": "2.0.0",
next: "12.2.0",
zod: "1.2.3",
},
})
})
it("correctly updates versions with the danger tag", async () => {
expect(await replaceBlitzPkgsVersions(pkgJson, "danger")).toEqual({
dependencies: {
blitz: "3.0.0",
"@blitzjs/rpc": "3.0.0",
"@blitzjs/auth": "3.0.0",
"@blitzjs/next": "3.0.0",
next: "12.2.0",
zod: "1.2.3",
},
})
})
it("sets version as a provided tag if it wasn't found with fetchDistTag function", async () => {
expect(await replaceBlitzPkgsVersions(pkgJson, "custom")).toEqual({
dependencies: {
blitz: "custom",
"@blitzjs/rpc": "custom",
"@blitzjs/auth": "custom",
"@blitzjs/next": "custom",
next: "12.2.0",
zod: "1.2.3",
},
})
})
it("handles package.json without dependecies key", async () => {
expect(await replaceBlitzPkgsVersions({}, "custom")).toEqual({
dependencies: {
blitz: "custom",
"@blitzjs/rpc": "custom",
"@blitzjs/auth": "custom",
"@blitzjs/next": "custom",
next: "12.2.0",
zod: "1.2.3",
},
})
})
})

View File

@@ -1,5 +1,7 @@
# @blitzjs/config
## 2.0.0-alpha.68
## 2.0.0-alpha.67
## 2.0.0-alpha.66

View File

@@ -1,7 +1,7 @@
{
"name": "@blitzjs/config",
"private": true,
"version": "2.0.0-alpha.67",
"version": "2.0.0-alpha.68",
"license": "MIT",
"dependencies": {
"@typescript-eslint/eslint-plugin": "5.9.1",

View File

@@ -1,5 +1,13 @@
# @blitzjs/generator
## 2.0.0-alpha.68
### Patch Changes
- 70b334a2: Remove trailing comma from tsconfig.json file in the new app template"
- dd299ae8: Add ts-jest to dependencies in new app templates
- 078fe474: Add `@testing-library/jest-dom` to new app dependecies
## 2.0.0-alpha.67
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/generator",
"version": "2.0.0-alpha.67",
"version": "2.0.0-alpha.68",
"scripts": {
"dev": "watch unbuild src --wait=0.2",
"build": "unbuild && pnpm build:templates",
@@ -46,7 +46,7 @@
"vinyl": "2.2.1"
},
"devDependencies": {
"@blitzjs/config": "2.0.0-alpha.67",
"@blitzjs/config": "2.0.0-alpha.68",
"@juanm04/cpx": "2.0.1",
"@types/babel__core": "7.1.19",
"@types/diff": "5.0.2",

View File

@@ -27,7 +27,7 @@ export interface AppGeneratorOptions extends GeneratorOptions {
version: string
skipInstall: boolean
skipGit: boolean
form?: "finalform" | "hookform" | "formik"
form: "finalform" | "hookform" | "formik"
onPostInstall?: () => Promise<void>
}
@@ -120,7 +120,7 @@ export class AppGenerator extends Generator<AppGeneratorOptions> {
] = await Promise.all([
fetchLatestVersionsFor(pkg.dependencies),
fetchLatestVersionsFor(pkg.devDependencies),
getBlitzDependencyVersion(this.options.version),
getBlitzDependencyVersion(),
])
pkg.dependencies = newDependencies

View File

@@ -9,6 +9,8 @@ export * from "./generators/form-generator"
export * from "./generator"
export * from "./conflict-checker"
export {getLatestVersion} from "./utils/get-latest-version"
export * from "./utils/npm-fetch"
export * from "./utils/get-blitz-dependency-version"
export {
singleCamel,
singlePascal,

View File

@@ -1,16 +1,14 @@
import {Fallbackable} from "./fallbackable"
import {logFailedVersionFetch} from "./get-latest-version"
import {fetchDistTags} from "./npm-fetch"
export const getBlitzDependencyVersion = async (
cliVersion: string,
): Promise<Fallbackable<string>> => {
try {
// TODO: Need to update this to handle alpha, beta and major
const {alpha} = await fetchDistTags("blitz")
const CURRENT_BLITZ_TAG = "alpha"
if (alpha) {
return {value: alpha}
export const getBlitzDependencyVersion = async () => {
try {
const result = await fetchDistTags("blitz")
if (CURRENT_BLITZ_TAG in result) {
return {value: result}
}
logFailedVersionFetch("blitz")

View File

@@ -1,25 +1,23 @@
import got from "got"
type PackageInformation = any
type NpmDepResponse = {versions: Record<string, PackageInformation>}
export type NpmDepResponse = {versions: Record<string, PackageInformation>}
export const fetchAllVersions = async (dependency: string) => {
const res = await got(`https://registry.npmjs.org/${dependency}`, {
const res = (await got(`https://registry.npmjs.org/${dependency}`, {
retry: {limit: 3},
timeout: 3000,
responseType: "json",
}).json<NpmDepResponse>()
}).json<NpmDepResponse>()) as unknown as NpmDepResponse
return Object.keys(res.versions)
}
type NpmDistTagsResponse = {latest: string; canary: string; alpha: string}
export const fetchDistTags = async (dependency: string) => {
const res = await got(`https://registry.npmjs.org/-/package/${dependency}/dist-tags`, {
const res = (await got(`https://registry.npmjs.org/-/package/${dependency}/dist-tags`, {
retry: {limit: 3},
timeout: 3000,
responseType: "json",
}).json<NpmDistTagsResponse>()
}).json()) as unknown as Record<string, any>
return res
}

View File

@@ -35,6 +35,7 @@
},
"devDependencies": {
"@next/bundle-analyzer": "12.0.8",
"@testing-library/jest-dom": "5.16.3",
"@types/jest": "27.4.1",
"@types/node": "17.0.16",
"@types/preview-email": "2.0.1",

View File

@@ -35,6 +35,7 @@
},
"devDependencies": {
"@next/bundle-analyzer": "12.0.8",
"@testing-library/jest-dom": "5.16.3",
"@types/jest": "27.4.1",
"@types/node": "17.0.16",
"@types/preview-email": "2.0.1",
@@ -50,6 +51,7 @@
"prettier-plugin-prisma": "3.8.0",
"pretty-quick": "3.1.3",
"preview-email": "3.x",
"ts-jest": "28.0.7",
"typescript": "^4.5.3"
},
"private": true

View File

@@ -17,7 +17,7 @@
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"tsBuildInfoFile": ".tsbuildinfo",
"tsBuildInfoFile": ".tsbuildinfo"
},
"exclude": ["node_modules", "**/*.e2e.ts", "cypress"],
"include": ["blitz-env.d.ts", "**/*.ts", "**/*.tsx", "types"]

View File

@@ -27,6 +27,7 @@
},
"devDependencies": {
"@next/bundle-analyzer": "12.0.8",
"@testing-library/jest-dom": "5.16.3",
"@types/jest": "27.4.1",
"@types/node": "17.0.16",
"@types/react": "18.0.1",

View File

@@ -29,6 +29,7 @@
},
"devDependencies": {
"@next/bundle-analyzer": "12.0.8",
"@testing-library/jest-dom": "5.16.3",
"@types/jest": "27.4.1",
"@types/node": "17.0.16",
"@types/react": "18.0.1",
@@ -41,6 +42,7 @@
"lint-staged": "12.1.7",
"prettier": "^2.5.1",
"pretty-quick": "3.1.3",
"ts-jest": "28.0.7",
"typescript": "^4.5.3"
},
"private": true

View File

@@ -25,7 +25,7 @@
"@typescript-eslint/parser": "5.9.1"
},
"devDependencies": {
"@blitzjs/config": "2.0.0-alpha.67",
"@blitzjs/config": "2.0.0-alpha.68",
"@types/react": "18.0.1",
"@types/react-dom": "17.0.14",
"react": "18.0.0",

38
pnpm-lock.yaml generated
View File

@@ -49,7 +49,7 @@ importers:
"@types/preview-email": 2.0.1
"@types/react": 18.0.1
"@typescript-eslint/eslint-plugin": 5.9.1
blitz: workspace:2.0.0-alpha.66
blitz: workspace:2.0.0-alpha.67
eslint: 7.32.0
eslint-config-next: 12.2.0
eslint-config-prettier: 8.5.0
@@ -475,8 +475,8 @@ importers:
packages/blitz:
specifiers:
"@blitzjs/config": workspace:2.0.0-alpha.66
"@blitzjs/generator": 2.0.0-alpha.66
"@blitzjs/config": workspace:2.0.0-alpha.67
"@blitzjs/generator": 2.0.0-alpha.67
"@types/cookie": 0.4.1
"@types/cross-spawn": 6.0.2
"@types/debug": 4.1.7
@@ -586,7 +586,7 @@ importers:
packages/blitz-auth:
specifiers:
"@blitzjs/config": workspace:2.0.0-alpha.66
"@blitzjs/config": workspace:2.0.0-alpha.67
"@testing-library/react": 13.0.0
"@testing-library/react-hooks": 7.0.2
"@types/b64-lite": 1.3.0
@@ -600,7 +600,7 @@ importers:
"@types/secure-password": 3.1.1
b64-lite: 1.4.0
bad-behavior: 1.0.1
blitz: 2.0.0-alpha.66
blitz: 2.0.0-alpha.67
cookie: 0.4.1
cookie-session: 2.0.0
debug: 4.3.3
@@ -653,8 +653,8 @@ importers:
packages/blitz-next:
specifiers:
"@blitzjs/config": workspace:2.0.0-alpha.66
"@blitzjs/rpc": 2.0.0-alpha.66
"@blitzjs/config": workspace:2.0.0-alpha.67
"@blitzjs/rpc": 2.0.0-alpha.67
"@tanstack/react-query": 4.0.10
"@testing-library/dom": 8.13.0
"@testing-library/jest-dom": 5.16.3
@@ -666,7 +666,7 @@ importers:
"@types/react": 18.0.1
"@types/react-dom": 17.0.14
"@types/testing-library__react-hooks": 4.0.0
blitz: 2.0.0-alpha.66
blitz: 2.0.0-alpha.67
cross-spawn: 7.0.3
debug: 4.3.3
find-up: 4.1.0
@@ -716,15 +716,15 @@ importers:
packages/blitz-rpc:
specifiers:
"@blitzjs/auth": 2.0.0-alpha.66
"@blitzjs/config": workspace:2.0.0-alpha.66
"@blitzjs/auth": 2.0.0-alpha.67
"@blitzjs/config": workspace:2.0.0-alpha.67
"@tanstack/react-query": 4.0.10
"@types/debug": 4.1.7
"@types/react": 18.0.1
"@types/react-dom": 17.0.14
b64-lite: 1.4.0
bad-behavior: 1.0.1
blitz: 2.0.0-alpha.66
blitz: 2.0.0-alpha.67
chalk: ^4.1.0
debug: 4.3.3
next: 12.2.0
@@ -767,12 +767,12 @@ importers:
"@babel/plugin-syntax-typescript": 7.17.12
"@babel/preset-env": 7.12.10
"@blitzjs/config": workspace:*
"@blitzjs/generator": 2.0.0-alpha.66
"@blitzjs/generator": 2.0.0-alpha.67
"@types/jscodeshift": 0.11.2
"@types/node": 17.0.16
arg: 5.0.1
ast-types: 0.14.2
blitz: 2.0.0-alpha.66
blitz: 2.0.0-alpha.67
chalk: ^4.1.0
cross-spawn: 7.0.3
debug: 4.3.3
@@ -827,7 +827,7 @@ importers:
"@babel/plugin-transform-typescript": 7.12.1
"@babel/preset-env": 7.12.10
"@babel/types": 7.12.10
"@blitzjs/config": 2.0.0-alpha.66
"@blitzjs/config": 2.0.0-alpha.67
"@juanm04/cpx": 2.0.1
"@mrleebo/prisma-ast": 0.2.6
"@types/babel__core": 7.1.19
@@ -920,7 +920,7 @@ importers:
packages/pkg-template:
specifiers:
"@blitzjs/config": 2.0.0-alpha.66
"@blitzjs/config": 2.0.0-alpha.67
"@types/react": 18.0.1
"@types/react-dom": 17.0.14
"@typescript-eslint/eslint-plugin": 5.9.1
@@ -3060,7 +3060,6 @@ packages:
semver: 5.7.1
transitivePeerDependencies:
- supports-color
dev: false
/@babel/preset-flow/7.17.12_@babel+core@7.18.2:
resolution:
@@ -5491,7 +5490,6 @@ packages:
typescript: 4.6.3
transitivePeerDependencies:
- supports-color
dev: false
/@typescript-eslint/experimental-utils/5.28.0_hrkuebk64jiu2ut2d2sm4oylnu:
resolution:
@@ -9315,7 +9313,6 @@ packages:
transitivePeerDependencies:
- eslint-import-resolver-webpack
- supports-color
dev: false
/eslint-config-next/12.2.4_hrkuebk64jiu2ut2d2sm4oylnu:
resolution:
@@ -9353,7 +9350,6 @@ packages:
hasBin: true
peerDependencies:
eslint: ">=7.0.0"
dev: false
/eslint-config-prettier/8.5.0_eslint@7.32.0:
resolution:
@@ -12018,7 +12014,7 @@ packages:
pretty-format: 27.5.1
slash: 3.0.0
strip-json-comments: 3.1.1
ts-node: 10.7.0_fxg3r7oju3tntkxsvleuiot4fa
ts-node: 10.7.0_typescript@4.6.3
transitivePeerDependencies:
- bufferutil
- canvas
@@ -17304,6 +17300,7 @@ packages:
typescript: 4.6.3
v8-compile-cache-lib: 3.0.1
yn: 3.1.1
dev: false
/ts-node/10.7.0_typescript@4.6.3:
resolution:
@@ -17336,7 +17333,6 @@ packages:
typescript: 4.6.3
v8-compile-cache-lib: 3.0.1
yn: 3.1.1
dev: false
/tsconfig-paths/3.14.1:
resolution: