1
0
mirror of synced 2026-02-04 12:08:33 -05:00

Compare commits

...

57 Commits

Author SHA1 Message Date
github-actions[bot]
dff9fd042a Version Packages (beta) (#3730)
* Version Packages (beta)

* Update version number

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: beerose <alexsandra.sikora@gmail.com>
2022-08-15 10:38:03 +02:00
Aleksandra
2cc888eff8 Update changeset config (#3729) 2022-08-15 10:13:57 +02:00
github-actions[bot]
8a0a97bebb Version Packages (alpha) (#3724)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-08-14 15:57:22 +02:00
Aleksandra
176c7b8b57 Use correct path for log utilities import (#3721) 2022-08-14 15:49:43 +02:00
Aleksandra
b307931f2e Point to main branch instead of canary in README.md 2022-08-13 11:33:47 +02:00
Aleksandra
14375e25c4 Update sponsors list (#3720) 2022-08-13 11:30:30 +02:00
github-actions[bot]
8b755574b5 Version Packages (alpha) (#3717)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-08-12 20:05:18 +02:00
Aleksandra
4656e6ecd6 Print model added or updated in schema.prisma after running model generator (#3718) 2022-08-12 20:01:15 +02:00
Aleksandra
1e0ec7a972 Add missing BlitzPage type to Home page (#3716) 2022-08-12 19:43:40 +02:00
Dillon Raphael
f88702c1c1 Minimal codemod fixes (#3715)
* fix removing trailing comma when removing BlitzConfig from next.config.js during codemod

* fix codemod for consolidating pages
2022-08-12 13:21:25 -04:00
github-actions[bot]
8b9ad3f40c Version Packages (alpha) (#3705)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-08-12 13:37:07 +02:00
Daniel Bannert
37623a4f4c add missing g in next.config.js file name (#3713)
* feat: added missing g in confi.js

* Add Changeset

Co-authored-by: beerose <alexsandra.sikora@gmail.com>
2022-08-12 13:28:47 +02:00
Aleksandra
6baab1907e Add type checking to next.config.js files in templates (#3710) 2022-08-12 11:37:06 +02:00
JH.Lee
b5de25c3d8 (meta) add @orionmiz as contributor (#3712) 2022-08-12 11:24:26 +02:00
Dillon Raphael
86af6dec5f Wrap middlewares with BlitzServerMiddleware function with codemod (#3711)
* wrap middlewares with BlitzServerMiddleware function & fix generating next config file
2022-08-11 14:39:59 -04:00
Blitz.js Bot
52a6338772 (meta) added @siddhsuresh as contributor 2022-08-11 11:11:28 -04:00
Siddharth Suresh
72a332e013 #3602 Fix the way next.config.js file is created by the codemod (#3709)
* #3602 fix the way next.config.js file is created by the codemod

* Update upgrade-legacy.ts

* remove middleware block
2022-08-11 11:11:23 -04:00
Dillon Raphael
fd31e56bc5 blitz generate changeset 2022-08-11 10:47:03 -04:00
Dillon Raphael
e2fac297fd Add back generate command (#3707)
* add back generate command

* use Routes object in generator templates

* update query & mutation templates to use resolver
2022-08-11 10:34:57 -04:00
Aleksandra
a3c92cb863 Allow using RouteUrlObject as redirect.destination in getStaticProps and getServerSideProps (#3699) 2022-08-11 13:20:57 +02:00
Dillon Raphael
2d1482fc8b Store error for cookiePrefix if undefined & show error at the end of codemod (#3704)
* store error for cookiePrefix if undefined & show error at the end

* rename to collectedErrors

* fix type & update error message
2022-08-10 15:40:17 -04:00
Blitz.js Bot
85b15a9cfb (meta) added @edrickleong as contributor 2022-08-10 05:17:42 -04:00
Edrick Leong
4902802402 Add getQueryData utility to get an existing query's cached data (#3648)
* feat: add getQueryData

* test: add integration test for getQueryData

* Add changeset

Co-authored-by: Aleksandra <alexsandra.sikora@gmail.com>
2022-08-10 11:17:37 +02:00
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
github-actions[bot]
1010858446 Version Packages (alpha) (#3680)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-08-05 15:44:22 +02:00
Dillon Raphael
ebd74b4e97 Fix template path for the generator (#3679) 2022-08-05 15:35:31 +02:00
Aleksandra
8870580710 Utilities cleanup (#3677) 2022-08-05 14:42:25 +02:00
github-actions[bot]
414d758fe8 Version Packages (alpha) (#3653)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-08-05 00:04:16 +02:00
Blitz.js Bot
fce0f3135a (meta) added @chaiwattsw as contributor 2022-08-04 17:57:34 -04:00
Chaiwat Trisuwan
9620ef6b1e chore: move zod to devDependencies (#3674) 2022-08-04 23:57:29 +02:00
Dillon Raphael
240f3f3471 exports BlitzServerMiddleware util function (#3671) 2022-08-04 18:54:40 +02:00
Dillon Raphael
91aa535632 Include .env.test to generator templates (#3672)
* adds env test file to generator templates
2022-08-04 18:43:13 +02:00
Aleksandra
ccb1af8d08 Avoid Next's invalid config detected warnings by deleting "blitz" key from the config object (#3670) 2022-08-04 13:21:50 +02:00
Dillon Raphael
807a2b5645 removes peer dependencies and adds to build externals (#3667) 2022-08-04 01:51:13 +02:00
Dillon Raphael
a3e6c49c4d Fixes the supports-color warning for pnpm (#3666)
* add supports-color to package.json
2022-08-04 01:13:33 +02:00
Aleksandra
4d7d126d9c Run prisma generate as a blitz codegen step (#3662) 2022-08-03 18:02:03 +02:00
Aleksandra
890b0c0c9d various blitz new fixes and improvements (#3661) 2022-08-03 12:46:00 +02:00
Dillon Raphael
928e840b59 Fixes loading production env variables by default for blitz build command (#3659) 2022-08-03 01:21:58 +02:00
Dillon Raphael
55b1cb2044 runs codegen on build & remove stopWatcher console log (#3658) 2022-08-03 01:07:44 +02:00
Blitz.js Bot
3a6677b307 (meta) updated @dillonraphael contributions 2022-08-02 16:19:49 -04:00
Dillon Raphael
f202aac183 fixes mock in forgotPassword mutation test & uses hardcoded blitz package versions instead of the alpha tag (#3655) 2022-08-02 22:19:43 +02:00
Aleksandra
065db256d7 Update generator templates to use resolver function (#3652) 2022-08-02 14:49:31 +02:00
github-actions[bot]
ada5cac7e3 Version Packages (alpha) (#3650)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Aleksandra <alexsandra.sikora@gmail.com>
2022-08-02 11:02:12 +02:00
Blitz.js Bot
e286bcb3ff (meta) added @datner as contributor 2022-08-02 04:57:42 -04:00
Datner
dd5f51744f Move enchancePrisma to a browser entrypoint (#3609)
Co-authored-by: Aleksandra <alexsandra.sikora@gmail.com>
2022-08-02 10:57:37 +02:00
154 changed files with 3468 additions and 827 deletions

View File

@@ -971,7 +971,8 @@
"profile": "https://twitter.com/dillonraphael",
"contributions": [
"code",
"doc"
"doc",
"test"
]
},
{
@@ -3639,6 +3640,69 @@
"contributions": [
"doc"
]
},
{
"login": "datner",
"name": "Datner",
"avatar_url": "https://avatars.githubusercontent.com/u/22598347?v=4",
"profile": "https://github.com/datner",
"contributions": [
"doc",
"code"
]
},
{
"login": "chaiwattsw",
"name": "Chaiwat Trisuwan",
"avatar_url": "https://avatars.githubusercontent.com/u/30198386?v=4",
"profile": "https://chaiwattsw.com/",
"contributions": [
"doc",
"code"
]
},
{
"login": "oltdaniel",
"name": "Daniel Oltmanns",
"avatar_url": "https://avatars.githubusercontent.com/u/53529846?v=4",
"profile": "oltdaniel.eu",
"contributions": [
"doc",
"code"
]
},
{
"login": "edrickleong",
"name": "Edrick Leong",
"avatar_url": "https://avatars.githubusercontent.com/u/10529706?v=4",
"profile": "https://github.com/edrickleong",
"contributions": [
"doc",
"code",
"test"
]
},
{
"login": "siddhsuresh",
"name": "Siddharth Suresh",
"avatar_url": "https://avatars.githubusercontent.com/u/83594610?v=4",
"profile": "https://github.com/siddhsuresh",
"contributions": [
"doc",
"code"
]
},
{
"login": "orionmiz",
"name": "JH.Lee",
"avatar_url": "https://avatars.githubusercontent.com/u/39466936?v=4",
"profile": "http://jins.dev",
"contributions": [
"code",
"test",
"maintenance",
"doc"
]
}
],
"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/generator": patch
---
Print model added or updated in schema.prisma after running model generator

View File

@@ -0,0 +1,6 @@
---
"blitz": patch
"@blitzjs/generator": patch
---
Add back blitz generate command

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Include `.env.test` file to the generator templates

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Add `BlitzPage` type to Home pages in app templates

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/next": patch
---
Allow using `RouteUrlObject` as `redirect.destination` in `getStaticProps` and `getServerSideProps`

View File

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

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---
Wrap middlewares with BlitzServerMiddleware function with codemod

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,5 @@
---
"blitz": patch
---
Fixes loading production env variables by default for blitz build command

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Use correct path for log utilities import

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/next": patch
---
Avoid `invalid config detected` warnings by deleting `"blitz"` key from next config object

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
---
Add BlitzServerMiddleware utility function to wrap middleware in blitz server file

View File

@@ -0,0 +1,5 @@
---
"blitz": patch
---
Runs the codegen on the blitz build command

View File

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

View File

@@ -0,0 +1,5 @@
---
"blitz": patch
---
Run `prisma generate` as a `blitz codegen` step if "prisma" is found in project's dependencies

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Add type checking to next.config.js files in new app templates

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---
Remove trailing comma when removing BlitzConfig from next.config.js & Fix codemod so if route (eg. `app/auth/pages`) convert to (eg. `pages/`) instead of (eg. `pages/auth`)

View File

@@ -0,0 +1,6 @@
---
"blitz": patch
"@blitzjs/generator": patch
---
Improve `blitz new` messaging and fix minor issues

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/codemod": patch
---
Wrap `blitz.config.ts` with the `withBlitz` function during the codemod step instead of creating a blank `next.config.js` file.

View File

@@ -1,44 +1,56 @@
{
"mode": "pre",
"tag": "alpha",
"tag": "beta",
"initialVersions": {
"web": "0.0.0",
"test-auth": "0.0.0",
"test-rpc": "0.0.0",
"test-utils": "0.0.0",
"blitz": "2.0.0-alpha.0",
"@blitzjs/auth": "2.0.0-alpha.0",
"@blitzjs/next": "2.0.0-alpha.0",
"@blitzjs/rpc": "2.0.0-alpha.0",
"blitz": "2.0.0-beta.0",
"@blitzjs/auth": "2.0.0-beta.0",
"@blitzjs/next": "2.0.0-beta.0",
"@blitzjs/rpc": "2.0.0-beta.0",
"@blitzjs/config": "0.0.0",
"@blitzjs/generator": "2.0.0-alpha.0",
"@blitzjs/codemod": "2.0.0-alpha.0",
"@blitzjs/generator": "2.0.0-beta.0",
"@blitzjs/codemod": "2.0.0-beta.0",
"template": "0.0.0",
"toolkit-app": "1.0.0",
"test-qm": "0.0.0",
"test-no-suspense": "0.0.0",
"test-trailing-slash": "0.0.0",
"test-middleware": "0.0.0"
"test-middleware": "0.0.0",
"test-react-query-utils": "0.0.0"
},
"changesets": [
"big-phones-bow",
"blue-pigs-tan",
"breezy-cameras-double",
"breezy-moose-behave",
"bright-mangos-run",
"brown-avocados-wink",
"calm-carpets-deny",
"calm-horses-tie",
"calm-nails-wait",
"calm-tomatoes-drive",
"chilled-carrots-own",
"clean-hats-pump",
"clean-walls-wink",
"clever-radios-lie",
"cool-doors-invent",
"cool-horses-check",
"cuddly-pugs-crash",
"curly-rules-speak",
"curly-seas-serve",
"dirty-monkeys-greet",
"dirty-planets-chew",
"eleven-humans-sort",
"empty-berries-rule",
"empty-turkeys-wave",
"fair-carrots-guess",
"fair-wombats-sneeze",
"famous-kings-explain",
"fast-trainers-kneel",
"few-dogs-fetch",
"flat-bees-approve",
"four-brooms-juggle",
"four-meals-fry",
@@ -49,17 +61,25 @@
"good-apes-drum",
"good-insects-wink",
"gorgeous-buses-scream",
"gorgeous-games-obey",
"great-candles-stare",
"great-months-train",
"great-terms-rescue",
"green-papayas-do",
"green-pillows-hammer",
"happy-hotels-visit",
"healthy-rice-shout",
"heavy-apes-judge",
"hot-cups-rhyme",
"hot-drinks-approve",
"hungry-baboons-swim",
"kind-walls-suffer",
"late-steaks-give",
"lemon-games-press",
"lemon-seas-push",
"light-donkeys-double",
"long-bees-hope",
"lovely-berries-sell",
"lovely-colts-share",
"lucky-cows-try",
"mean-gorillas-reply",
@@ -76,10 +96,12 @@
"nine-onions-admire",
"ninety-lies-press",
"ninety-pets-heal",
"ninety-rice-tickle",
"olive-bees-buy",
"olive-feet-rhyme",
"olive-sheep-rhyme",
"perfect-eyes-repeat",
"perfect-trains-double",
"plenty-bottles-swim",
"polite-lizards-love",
"poor-peas-lick",
@@ -92,46 +114,63 @@
"quiet-feet-travel",
"quiet-pans-hunt",
"quiet-sloths-rule",
"red-badgers-retire",
"rich-chairs-invent",
"rich-queens-travel",
"rotten-rocks-remember",
"shaggy-carpets-brake",
"sharp-falcons-begin",
"shy-olives-hang",
"shy-pumpkins-try",
"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-rice-clap",
"smooth-stingrays-drum",
"smooth-tools-train",
"soft-adults-smell",
"sour-lemons-hunt",
"sour-mails-lick",
"spicy-beds-float",
"spotty-dingos-stare",
"stale-jobs-drum",
"strong-apes-reply",
"stupid-walls-sell",
"sweet-kiwis-cross",
"swift-drinks-dress",
"tall-meals-learn",
"tame-keys-reply",
"tasty-maps-fetch",
"tasty-news-collect",
"ten-hairs-listen",
"ten-rivers-burn",
"tender-pianos-check",
"thick-parrots-float",
"thirty-countries-build",
"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",
"weak-suns-shave",
"wicked-ghosts-cough",
"wicked-rings-walk",
"wise-frogs-give"
"wise-eels-visit",
"wise-frogs-give",
"wise-rabbits-complain"
]
}

View File

@@ -0,0 +1,8 @@
---
"blitz": patch
"@blitzjs/next": patch
"@blitzjs/rpc": patch
"@blitzjs/generator": patch
---
Fixes peer dependency warnings

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
---
Fix template path for the generator

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
---
Fix typo in a next.config.js file name

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
---
Allow codemod to finish if `cookiePrefix` is undefined. Then show error at the end of running the codemod.

View File

@@ -0,0 +1,8 @@
---
"@blitzjs/auth": patch
"@blitzjs/next": patch
"@blitzjs/rpc": patch
"blitz": patch
"@blitzjs/generator": patch
---
Fixes the supports-color warning for pnpm

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/rpc": patch
---
Add `getQueryData` utility to get an existing query's cached data

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 @@
---
"blitz": patch
---
Fix `enhancePrisma is undefined` errors by moving the utility function to a browser entrypoint

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/rpc": patch
---
moves zod to devDependencies

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
---
Update new app templates to use blitz-rpc's resolver function

View File

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

View File

@@ -0,0 +1,11 @@
---
"blitz": patch
"@blitzjs/auth": patch
"@blitzjs/next": patch
"@blitzjs/rpc": patch
"@blitzjs/codemod": patch
"@blitzjs/config": patch
"@blitzjs/generator": patch
---
Beta release

View File

@@ -0,0 +1,5 @@
---
"@blitzjs/generator": patch
---
Mocks @blitzjs/auth instead of blitz inside the forgotPassword mutation test & hardcodes blitz package version types instead of just using the alpha tag.

View File

@@ -6,9 +6,9 @@
<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-386-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-391-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">
<a aria-label="License" href="https://github.com/blitz-js/blitz/blob/main/LICENSE">
<img alt="" src="https://img.shields.io/npm/l/blitz.svg?style=for-the-badge&labelColor=000000&color=blue">
</a>
<a aria-label="NPM version" href="https://www.npmjs.com/package/blitz">
@@ -66,16 +66,16 @@ Your financial contributions help ensure Blitz continues to be developed and mai
<table>
<tr>
<td><a aria-label="Andreas Asprou" href="https://andreas.fyi">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/andreas.jpg" width="40px"/>
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/andreas.jpg" width="40px"/>
</a></td>
<td><a aria-label="Digas" href="https://digsas.com">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/digsas.svg" width="40px"/>
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/digsas.svg" width="40px"/>
</a></td>
<td><a aria-label="userTrack" href="https://www.usertrack.net/?ref=blitzjs">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/usertrack.png" width="40px"/>
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/usertrack.png" width="40px"/>
</a></td>
<td><a aria-label="MeetKai" href="https://meetkai.com/?ref=blitzjs">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/meetkai.png" width="40px"/>
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/meetkai.png" width="40px"/>
</a></td>
</tr>
</table>
@@ -85,14 +85,11 @@ Your financial contributions help ensure Blitz continues to be developed and mai
<table>
<tr>
<td><a aria-label="Render.com" href="https://render.com?utm_source=BlitzJS&utm_medium=sponsorship&utm_campaign=BlitzJS_Sponsorship_2020">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/render-logo-color2.png" width="200px">
</a></td>
<td><a aria-label="RIT" href="https://rit-inc.co.jp/?utm_source=BlitzJS&utm_medium=sponsorship&utm_campaign=BlitzJS_Sponsorship_2021">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/rit_logo.png" width="200px">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/rit_logo.png" width="200px">
</a></td>
<td><a aria-label="Boostry" href="https://boostry.co.jp/?utm_source=BlitzJS&utm_medium=sponsorship&utm_campaign=BlitzJS_Sponsorship_2021">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/boostry.svg" width="200px">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/boostry.svg" width="200px">
</a></td>
</tr>
</table>
@@ -105,7 +102,7 @@ Your financial contributions help ensure Blitz continues to be developed and mai
<tr>
<td>
<a aria-label="Fauna" href="https://dashboard.fauna.com/accounts/register?utm_source=BlitzJS&utm_medium=sponsorship&utm_campaign=BlitzJS_Sponsorship_2020">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/canary/assets/Fauna_Logo_Blue.png" width="300px">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/Fauna_Logo_Blue.png" width="300px">
</a>
</td>
</tr>
@@ -119,9 +116,13 @@ Your financial contributions help ensure Blitz continues to be developed and mai
### 💎 Diamond Sponsors
<a aria-label="Your Company" href="#">
<img alt="" src="https://dummyimage.com/1000x330/efe8ff/000000.png&text=Your+Logo+Here" width="500px">
</a>
<table>
<tr>
<a aria-label="Flightcontrol" href="https://www.flightcontrol.dev?ref=blitzjs">
<img alt="" src="https://raw.githubusercontent.com/blitz-js/blitz/main/assets/flightcontrol.png" width="400px">
</a>
</tr>
</table>
<br>
@@ -151,6 +152,7 @@ _Code ownership, pull request approvals and merging, etc_ (see [Maintainers L2](
<table>
<tr>
<td align="center"><a href="http://simonknott.de"><img src="https://avatars1.githubusercontent.com/u/14912729?v=4" width="100px;" alt=""/><br /><sub><b>Simon Knott</b></sub></a><br />SuperJSON</td>
<td align="center"><a href="http://jins.dev"><img src="https://avatars.githubusercontent.com/u/39466936?v=4" width="100px;" alt=""/><br /><sub><b>JH.Lee</b></sub></a><br />SuperJSON</td>
<td align="center"><a href="https://juanm04.com"><img src="https://avatars0.githubusercontent.com/u/16712703?v=4" width="100px;" alt=""/><br /><sub><b>Juan Martín Seery</b></sub></a><br />Website/Docs</td>
</tr>
</table>
@@ -337,7 +339,7 @@ Thanks to these wonderful people ([emoji key](https://allcontributors.org/docs/e
</tr>
<tr>
<td align="center"><a href="https://github.com/jschepmans"><img src="https://avatars2.githubusercontent.com/u/5782977?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Johan Schepmans</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=jschepmans" title="Code">💻</a></td>
<td align="center"><a href="https://twitter.com/dillonraphael"><img src="https://avatars0.githubusercontent.com/u/3496193?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dillon Raphael</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=dillonraphael" title="Code">💻</a> <a href="https://github.com/blitz-js/blitz/commits?author=dillonraphael" title="Documentation">📖</a></td>
<td align="center"><a href="https://twitter.com/dillonraphael"><img src="https://avatars0.githubusercontent.com/u/3496193?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dillon Raphael</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=dillonraphael" title="Code">💻</a> <a href="https://github.com/blitz-js/blitz/commits?author=dillonraphael" title="Documentation">📖</a> <a href="https://github.com/blitz-js/blitz/commits?author=dillonraphael" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/clgeoio"><img src="https://avatars2.githubusercontent.com/u/37571416?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Cody G</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=clgeoio" title="Code">💻</a> <a href="https://github.com/blitz-js/blitz/commits?author=clgeoio" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/madflow"><img src="https://avatars0.githubusercontent.com/u/183248?v=4?s=100" width="100px;" alt=""/><br /><sub><b>madflow</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=madflow" title="Documentation">📖</a></td>
<td align="center"><a href="https://twitter.com/nitaking_"><img src="https://avatars2.githubusercontent.com/u/10850034?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Satoshi Nitawaki</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=nitaking" title="Code">💻</a> <a href="#maintenance-nitaking" title="Maintenance">🚧</a> <a href="#question-nitaking" title="Answering Questions">💬</a> <a href="https://github.com/blitz-js/blitz/commits?author=nitaking" title="Documentation">📖</a></td>
@@ -706,6 +708,12 @@ Thanks to these wonderful people ([emoji key](https://allcontributors.org/docs/e
</tr>
<tr>
<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>
<td align="center"><a href="https://github.com/edrickleong"><img src="https://avatars.githubusercontent.com/u/10529706?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Edrick Leong</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=edrickleong" title="Documentation">📖</a> <a href="https://github.com/blitz-js/blitz/commits?author=edrickleong" title="Code">💻</a> <a href="https://github.com/blitz-js/blitz/commits?author=edrickleong" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/siddhsuresh"><img src="https://avatars.githubusercontent.com/u/83594610?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Siddharth Suresh</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=siddhsuresh" title="Documentation">📖</a> <a href="https://github.com/blitz-js/blitz/commits?author=siddhsuresh" title="Code">💻</a></td>
<td align="center"><a href="http://jins.dev"><img src="https://avatars.githubusercontent.com/u/39466936?v=4" width="100px;" alt=""/><br /><sub><b>JH.Lee</b></sub></a><br /><a href="https://github.com/blitz-js/blitz/commits?author=orionmiz" title="Code">💻</a> <a href="https://github.com/blitz-js/blitz/commits?author=orionmiz" title="Tests">⚠️</a> <a href="#maintenance-orionmiz" title="Maintenance">🚧</a> <a href="https://github.com/blitz-js/blitz/commits?author=orionmiz" title="Documentation">📖</a></td>
</tr>
</table>

View File

@@ -1,10 +1,15 @@
// @ts-check
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
})
const { withBlitz } = require("@blitzjs/next")
module.exports = withBlitz(
withBundleAnalyzer({
reactStrictMode: true,
})
)
/**
* @type {import('@blitzjs/next').BlitzConfig}
**/
const config = {
reactStrictMode: true,
}
module.exports = withBlitz(withBundleAnalyzer(config))

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.64",
"blitz": "workspace:2.0.0-beta.0",
"next": "12.2.0",
"prisma": "4.0.0",
"react": "18.0.0",

View File

@@ -6,7 +6,7 @@ import { useCurrentUser } from "app/core/hooks/useCurrentUser"
import logout from "app/auth/mutations/logout"
import logo from "public/logo.png"
import { useMutation } from "@blitzjs/rpc"
import { Routes } from "@blitzjs/next"
import { Routes, BlitzPage } from "@blitzjs/next"
/*
* This file is just for a pleasant getting started page for your new app.
@@ -53,7 +53,7 @@ const UserInfo = () => {
}
}
const Home = () => {
const Home: BlitzPage = () => {
return (
<Layout title="Home">
<div className="container">

View File

@@ -4,7 +4,7 @@
"private": true,
"scripts": {
"start:dev": "pnpm run prisma:start && next dev",
"buildapp": "prisma generate && next build",
"buildapp": "NODE_ENV=production pnpm blitz codegen && pnpm prisma generate && next build",
"start": "next start",
"lint": "next lint",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",

View File

@@ -0,0 +1,7 @@
export default function Post() {
return (
<div>
<h1>Post</h1>
</div>
)
}

View File

@@ -0,0 +1,24 @@
import {getQueryData, useQuery} from "@blitzjs/rpc"
import getBasic from "../app/queries/getBasic"
import {useState} from "react"
function PageWithGetQueryData() {
const [data] = useQuery(getBasic, {})
const [newData, setNewData] = useState<string>()
return (
<div>
<div>{data}</div>
{newData && <div id="new-data">{newData}</div>}
<button
onClick={async () => {
const newData = getQueryData(getBasic, {})
setNewData(newData)
}}
>
Call getQueryData
</button>
</div>
)
}
export default PageWithGetQueryData

View File

@@ -0,0 +1,27 @@
import {SessionContext} from "@blitzjs/auth"
import {Routes} from "@blitzjs/next"
import {gSSP} from "app/blitz-server"
type Props = {
userId: unknown
publicData: SessionContext["$publicData"]
}
export const getServerSideProps = gSSP<Props>(async ({ctx}) => {
const {session} = ctx
return {
redirect: {destination: Routes.Post({postId: "1"})},
props: {
userId: session.userId,
publicData: session.$publicData,
publishedAt: new Date(0),
},
}
})
function PageWithGsspRedirect(props: Props) {
return <div>{JSON.stringify(props, null, 2)}</div>
}
export default PageWithGsspRedirect

BIN
assets/flightcontrol.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

View File

@@ -0,0 +1,2 @@
SESSION_SECRET_KEY=hsdenhJfpLHrGjgdgg3jdF8g2bYD2PaQ
HEADLESS=true

View File

@@ -0,0 +1 @@
module.exports = require("@blitzjs/config/eslint")

View File

@@ -0,0 +1,3 @@
node_modules
# Keep environment variables out of version control
*.sqlite

View File

@@ -0,0 +1,14 @@
import {BlitzRpcPlugin} from "@blitzjs/rpc"
import {setupBlitzClient} from "@blitzjs/next"
import {AuthClientPlugin} from "@blitzjs/auth"
const {withBlitz} = setupBlitzClient({
plugins: [
AuthClientPlugin({
cookiePrefix: "react-query-utils-tests-cookie-prefix",
}),
BlitzRpcPlugin({}),
],
})
export {withBlitz}

View File

@@ -0,0 +1,16 @@
import {setupBlitzServer} from "@blitzjs/next"
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
import db from "../db"
const {gSSP, gSP, api} = setupBlitzServer({
plugins: [
AuthServerPlugin({
cookiePrefix: "react-query-utils-tests-cookie-prefix",
storage: PrismaStorage(db),
isAuthorized: simpleRolesIsAuthorized,
}),
],
})
export {gSSP, gSP, api}

View File

@@ -0,0 +1,3 @@
export default async function getBasic() {
return "basic-result"
}

View File

@@ -0,0 +1,8 @@
import {enhancePrisma} from "blitz"
import {PrismaClient} from "@prisma/client"
const EnhancedPrisma = enhancePrisma(PrismaClient)
export * from "@prisma/client"
const prisma = new EnhancedPrisma()
export default prisma

View File

@@ -0,0 +1,47 @@
-- CreateTable
CREATE TABLE "User" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"name" TEXT,
"email" TEXT NOT NULL,
"hashedPassword" TEXT,
"role" TEXT NOT NULL DEFAULT 'user'
);
-- CreateTable
CREATE TABLE "Session" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"expiresAt" DATETIME,
"handle" TEXT NOT NULL,
"userId" INTEGER,
"hashedSessionToken" TEXT,
"antiCSRFToken" TEXT,
"publicData" TEXT,
"privateData" TEXT,
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "Token" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"hashedToken" TEXT NOT NULL,
"type" TEXT NOT NULL,
"expiresAt" DATETIME NOT NULL,
"sentTo" TEXT NOT NULL,
"userId" INTEGER NOT NULL,
CONSTRAINT "Token_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Session_handle_key" ON "Session"("handle");
-- CreateIndex
CREATE UNIQUE INDEX "Token_hashedToken_type_key" ON "Token"("hashedToken", "type");

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "sqlite"

View File

@@ -0,0 +1,50 @@
datasource sqlite {
provider = "sqlite"
url = "file:./db.sqlite"
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String?
email String @unique
hashedPassword String?
role String @default("user")
sessions Session[]
tokens Token[]
}
model Session {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
expiresAt DateTime?
handle String @unique
user User? @relation(fields: [userId], references: [id])
userId Int?
hashedSessionToken String?
antiCSRFToken String?
publicData String?
privateData String?
}
model Token {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
hashedToken String
type String
expiresAt DateTime
sentTo String
user User @relation(fields: [userId], references: [id])
userId Int
@@unique([hashedToken, type])
}

View File

@@ -0,0 +1,7 @@
import prisma from "./index"
const seed = async () => {
await prisma.$reset()
}
export default seed

View File

@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View File

@@ -0,0 +1,2 @@
const {withBlitz} = require("@blitzjs/next")
module.exports = withBlitz({})

View File

@@ -0,0 +1,44 @@
{
"name": "test-react-query-utils",
"version": "0.0.0",
"private": true,
"scripts": {
"start:dev": "pnpm run prisma:start && next dev",
"test": "pnpm run prisma:start && vitest run",
"test-watch": "vitest",
"start": "next start",
"lint": "next lint",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",
"prisma:start": "prisma generate && prisma migrate deploy",
"prisma:studio": "prisma studio"
},
"prisma": {
"schema": "db/schema.prisma"
},
"dependencies": {
"@blitzjs/auth": "workspace:*",
"@blitzjs/next": "workspace:*",
"@blitzjs/rpc": "workspace:*",
"@prisma/client": "4.0.0",
"blitz": "workspace:*",
"lowdb": "3.0.0",
"next": "12.2.0",
"prisma": "4.0.0",
"react": "18.0.0",
"react-dom": "18.0.0"
},
"devDependencies": {
"@blitzjs/config": "workspace:*",
"@next/bundle-analyzer": "12.0.8",
"@types/express": "4.17.13",
"@types/fs-extra": "9.0.13",
"@types/node-fetch": "2.6.1",
"@types/react": "18.0.1",
"b64-lite": "1.4.0",
"eslint": "7.32.0",
"fs-extra": "10.0.1",
"get-port": "6.1.2",
"node-fetch": "3.2.3",
"typescript": "^4.5.3"
}
}

View File

@@ -0,0 +1,36 @@
import {ErrorFallbackProps, ErrorComponent, ErrorBoundary, AppProps} from "@blitzjs/next"
import {AuthenticationError, AuthorizationError} from "blitz"
import React, {Suspense} from "react"
import {withBlitz} from "../app/blitz-client"
function RootErrorFallback({error}: ErrorFallbackProps) {
if (error instanceof AuthenticationError) {
return <div>Error: You are not authenticated</div>
} else if (error instanceof AuthorizationError) {
return (
<ErrorComponent
statusCode={error.statusCode}
title="Sorry, you are not authorized to access this"
/>
)
} else {
return (
<ErrorComponent
statusCode={(error as any)?.statusCode || 400}
title={error.message || error.name}
/>
)
}
}
function MyApp({Component, pageProps}: AppProps) {
return (
<Suspense fallback="Loading...">
<ErrorBoundary FallbackComponent={RootErrorFallback}>
<Component {...pageProps} />
</ErrorBoundary>
</Suspense>
)
}
export default withBlitz(MyApp)

View File

@@ -0,0 +1,4 @@
import {rpcHandler} from "@blitzjs/rpc"
import {api} from "../../../app/blitz-server"
export default api(rpcHandler({onError: console.log}))

View File

@@ -0,0 +1,35 @@
import {getQueryData, useQuery} from "@blitzjs/rpc"
import {Suspense, useState} from "react"
import getBasic from "../app/queries/getBasic"
function Content() {
const [data] = useQuery(getBasic, undefined)
const [newData, setNewData] = useState<string>()
return (
<div>
<div>{data}</div>
{newData && <div id="new-data">{newData}</div>}
<button
id="button"
onClick={async () => {
const newData = getQueryData(getBasic, undefined)
setNewData(newData)
}}
>
Call getQueryData
</button>
</div>
)
}
function PageWithGetQueryData() {
return (
<div id="page">
<Suspense fallback={"Loading..."}>
<Content />
</Suspense>
</div>
)
}
export default PageWithGetQueryData

View File

@@ -0,0 +1,59 @@
import {describe, it, expect, beforeAll, afterAll} from "vitest"
import {killApp, findPort, launchApp, nextBuild, nextStart} from "../../utils/next-test-utils"
import webdriver from "../../utils/next-webdriver"
import {join} from "path"
let app: any
let appPort: number
const appDir = join(__dirname, "../")
const runTests = (mode?: string) => {
describe("get query data", () => {
it(
"should work",
async () => {
const browser = await webdriver(appPort, "/page-with-get-query-data")
browser.waitForElementByCss("#button", 0)
await browser.elementByCss("#button").click()
browser.waitForElementByCss("#new-data", 0)
const newText = await browser.elementByCss("#new-data").text()
expect(newText).toMatch(/basic-result/)
if (browser) await browser.close()
},
5000 * 60 * 2,
)
})
}
describe("React Query Utils Tests", () => {
describe("dev mode", () => {
beforeAll(async () => {
try {
appPort = await findPort()
app = await launchApp(appDir, appPort, {cwd: process.cwd()})
} catch (error) {
console.log(error)
}
}, 5000 * 60 * 2)
afterAll(async () => await killApp(app))
runTests()
})
describe("server mode", () => {
beforeAll(async () => {
try {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort, {cwd: process.cwd()})
} catch (err) {
console.log(err)
}
}, 5000 * 60 * 2)
afterAll(async () => await killApp(app))
runTests()
})
})

View File

@@ -0,0 +1,11 @@
{
"extends": "@blitzjs/config/tsconfig.nextjs.json",
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "types"],
"compilerOptions": {
"paths": {
"react": ["./node_modules/@types/react"]
}
},
"exclude": ["node_modules"],
"baseUrl": "."
}

View File

@@ -0,0 +1,15 @@
import {SimpleRolesIsAuthorized} from "@blitzjs/auth"
import {User} from "./db"
export type Role = "ADMIN" | "USER"
declare module "@blitzjs/auth" {
export interface Session {
isAuthorized: SimpleRolesIsAuthorized<Role>
PublicData: {
userId: User["id"]
role: Role
views?: number
}
}
}

View File

@@ -11,7 +11,7 @@
"preinstall": "npx only-allow pnpm",
"prepare": "husky install",
"build": "turbo run build",
"build:apps": "turbo run buildapp",
"build:apps": "turbo run buildapp --concurrency=1",
"dev": "turbo run dev --no-cache --parallel",
"lint": "turbo run lint",
"test": "turbo run test",
@@ -33,7 +33,7 @@
"prettier": "^2.5.1",
"prettier-plugin-prisma": "3.8.0",
"pretty-quick": "3.1.3",
"turbo": "1.1.5",
"turbo": "1.4.2",
"vitest": "0.8.2",
"wait-on": "6.0.1"
},

View File

@@ -1,5 +1,69 @@
# @blitzjs/auth
## 2.0.0-beta.72
### Patch Changes
- 2cc888ef: Beta release
- Updated dependencies [2cc888ef]
- blitz@2.0.0-beta.72
## 2.0.0-alpha.71
### Patch Changes
- blitz@2.0.0-alpha.71
## 2.0.0-alpha.70
### Patch Changes
- blitz@2.0.0-alpha.70
## 2.0.0-alpha.69
### Patch Changes
- Updated dependencies [fd31e56b]
- blitz@2.0.0-alpha.69
## 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
- blitz@2.0.0-alpha.67
## 2.0.0-alpha.66
### Patch Changes
- a3e6c49c: Fixes the supports-color warning for pnpm
- Updated dependencies [928e840b]
- Updated dependencies [240f3f34]
- Updated dependencies [55b1cb20]
- Updated dependencies [4d7d126d]
- Updated dependencies [890b0c0c]
- Updated dependencies [807a2b56]
- Updated dependencies [a3e6c49c]
- blitz@2.0.0-alpha.66
## 2.0.0-alpha.65
### Patch Changes
- Updated dependencies [dd5f5174]
- blitz@2.0.0-alpha.65
## 2.0.0-alpha.64
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/auth",
"version": "2.0.0-alpha.64",
"version": "2.0.0-beta.0",
"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.64",
"blitz": "2.0.0-beta.0",
"cookie": "0.4.1",
"cookie-session": "2.0.0",
"debug": "4.3.3",
@@ -36,10 +36,11 @@
"passport": "0.5.2",
"path": "0.12.7",
"secure-password": "4.0.0",
"supports-color": "8.1.1",
"url": "0.11.0"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.64",
"@blitzjs/config": "workspace:2.0.0-beta.0",
"@testing-library/react": "13.0.0",
"@testing-library/react-hooks": "7.0.2",
"@types/cookie": "0.4.1",

View File

@@ -1,5 +1,64 @@
# @blitzjs/next
## 2.0.0-beta.72
### Patch Changes
- 2cc888ef: Beta release
- Updated dependencies [2cc888ef]
- @blitzjs/rpc@2.0.0-beta.72
## 2.0.0-alpha.71
### Patch Changes
- @blitzjs/rpc@2.0.0-alpha.71
## 2.0.0-alpha.70
### Patch Changes
- @blitzjs/rpc@2.0.0-alpha.70
## 2.0.0-alpha.69
### Patch Changes
- a3c92cb8: Allow using `RouteUrlObject` as `redirect.destination` in `getStaticProps` and `getServerSideProps`
- Updated dependencies [49028024]
- @blitzjs/rpc@2.0.0-alpha.69
## 2.0.0-alpha.68
### Patch Changes
- Updated dependencies [630c7181]
- @blitzjs/rpc@2.0.0-alpha.68
## 2.0.0-alpha.67
### Patch Changes
- @blitzjs/rpc@2.0.0-alpha.67
## 2.0.0-alpha.66
### Patch Changes
- ccb1af8d: Avoid `invalid config detected` warnings by deleting `"blitz"` key from next config object
- 807a2b56: Fixes peer dependency warnings
- a3e6c49c: Fixes the supports-color warning for pnpm
- Updated dependencies [807a2b56]
- Updated dependencies [a3e6c49c]
- Updated dependencies [9620ef6b]
- @blitzjs/rpc@2.0.0-alpha.66
## 2.0.0-alpha.65
### Patch Changes
- @blitzjs/rpc@2.0.0-alpha.65
## 2.0.0-alpha.64
### Patch Changes

View File

@@ -2,7 +2,7 @@ import {BuildConfig} from "unbuild"
const config: BuildConfig = {
entries: ["./src/index-browser", "./src/index-server"],
externals: ["index-browser.cjs", "index-browser.mjs", "blitz", ".blitz"],
externals: ["index-browser.cjs", "index-browser.mjs", "blitz", ".blitz", "next", "react"],
declaration: true,
rollup: {
emitCJS: true,

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/next",
"version": "2.0.0-alpha.64",
"version": "2.0.0-beta.0",
"scripts": {
"build": "unbuild",
"dev": "pnpm predev && pnpm watch unbuild src --wait=0.2",
@@ -24,16 +24,17 @@
"eslint.js"
],
"dependencies": {
"@blitzjs/rpc": "2.0.0-alpha.64",
"@blitzjs/rpc": "2.0.0-beta.0",
"@tanstack/react-query": "4.0.10",
"@types/hoist-non-react-statics": "3.3.1",
"debug": "4.3.3",
"fs-extra": "10.0.1",
"hoist-non-react-statics": "3.3.2",
"superjson": "1.8.0"
"superjson": "1.8.0",
"supports-color": "8.1.1"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.64",
"@blitzjs/config": "workspace:2.0.0-beta.0",
"@testing-library/dom": "8.13.0",
"@testing-library/jest-dom": "5.16.3",
"@testing-library/react": "13.0.0",
@@ -43,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.64",
"blitz": "2.0.0-beta.0",
"cross-spawn": "7.0.3",
"find-up": "4.1.0",
"next": "12.2.0",
@@ -57,9 +58,5 @@
},
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"next": ">=12.2.0",
"react": "*"
}
}

View File

@@ -1,5 +1,5 @@
import type {NextConfig} from "next"
import {
import type {
NextConfig,
GetServerSideProps,
GetServerSidePropsResult,
GetStaticProps,
@@ -30,6 +30,8 @@ import {IncomingMessage, ServerResponse} from "http"
import {withSuperJsonProps} from "./superjson"
import {ParsedUrlQuery} from "querystring"
import {PreviewData} from "next/types"
import {resolveHref} from "next/dist/shared/lib/router/router"
import {RouteUrlObject, isRouteUrlObject} from "blitz"
export * from "./index-browser"
@@ -50,6 +52,25 @@ type SetupBlitzOptions = {
onError?: (err: Error) => void
}
export type Redirect =
| {
statusCode: 301 | 302 | 303 | 307 | 308
destination: string | RouteUrlObject
basePath?: false
}
| {
permanent: boolean
destination: string | RouteUrlObject
basePath?: false
}
export type BlitzGSSPResult<P> = {props: P | Promise<P>} | {redirect: Redirect} | {notFound: true}
export type BlitzGSPResult<P> =
| {props: P; revalidate?: number | boolean}
| {redirect: Redirect; revalidate?: number | boolean}
| {notFound: true; revalidate?: number | boolean}
export type BlitzGSSPHandler<
TProps,
Query extends ParsedUrlQuery = ParsedUrlQuery,
@@ -59,8 +80,8 @@ export type BlitzGSSPHandler<
req,
res,
...args
}: Parameters<GetServerSideProps<TProps, Query, PD>>[0] & {ctx: Ctx}) => ReturnType<
GetServerSideProps<TProps, Query, PD>
}: Parameters<GetServerSideProps<TProps, Query, PD>>[0] & {ctx: Ctx}) => Promise<
BlitzGSSPResult<TProps>
>
export type BlitzGSPHandler<
@@ -70,9 +91,9 @@ export type BlitzGSPHandler<
> = ({
ctx,
...args
}: Parameters<GetStaticProps<TProps, Query, PD>>[0] & {ctx: Ctx}) => ReturnType<
GetStaticProps<TProps, Query, PD>
>
}: Parameters<GetStaticProps<TProps, Query, PD>>[0] & {ctx: Ctx}) =>
| Promise<BlitzGSPResult<TProps>>
| BlitzGSPResult<TProps>
export type BlitzAPIHandler<TResult> = (
req: NextApiRequest,
@@ -123,7 +144,12 @@ export const setupBlitzServer = ({plugins, onError}: SetupBlitzOptions) => {
try {
const result = await handler({req, res, ctx, ...rest})
return withSuperJsonProps(withDehydratedState(result, getClient()))
return withSuperJsonProps(
withDehydratedState(
normalizeRedirectValues<GetServerSidePropsResult<TProps>>(result),
getClient(),
),
)
} catch (err: any) {
onError?.(err)
throw err
@@ -143,7 +169,12 @@ export const setupBlitzServer = ({plugins, onError}: SetupBlitzOptions) => {
try {
const result = await handler({...context, ctx: ctx})
return withSuperJsonProps(withDehydratedState(result, getClient()))
return withSuperJsonProps(
withDehydratedState(
normalizeRedirectValues<GetStaticPropsResult<TProps>>(result),
getClient(),
),
)
} catch (err: any) {
onError?.(err)
throw err
@@ -209,7 +240,8 @@ export function withBlitz(nextConfig: BlitzConfig = {}) {
},
})
return config
const {blitz, ...rest} = config
return rest
}
export type PrefetchQueryFn = <T extends AsyncFunc, TInput = FirstParam<T>>(
@@ -218,6 +250,7 @@ export type PrefetchQueryFn = <T extends AsyncFunc, TInput = FirstParam<T>>(
options?: DefaultOptions,
) => Promise<void>
type BlitzResult = Partial<BlitzGSPResult<any> & BlitzGSSPResult<any>>
type Result = Partial<GetServerSidePropsResult<any> & GetStaticPropsResult<any>>
function withDehydratedState<T extends Result>(result: T, queryClient: QueryClient | null) {
@@ -228,6 +261,27 @@ function withDehydratedState<T extends Result>(result: T, queryClient: QueryClie
return {...result, props: {...("props" in result ? result.props : undefined), dehydratedState}}
}
// Converts Blitz's GetServerSidePropsResult and GetStaticPropsResult to a NextJS compatible format
// Blitz accepts string | RouteUrlObject as redirect.destination — this function converts it to a string
const normalizeRedirectValues = <NormalizedResult extends Result>(
result: BlitzResult,
): NormalizedResult => {
if ("redirect" in result) {
const dest = result.redirect?.destination
if (dest && isRouteUrlObject(dest)) {
// Todo: find a better way to resolve href without `as any` assertion.
const resolvedDest = resolveHref({asPath: "/", pathname: "/"} as any, dest, true)
return {
...result,
redirect: {...result.redirect, destination: resolvedDest[1] || resolvedDest[0]},
} as NormalizedResult
}
}
return result as NormalizedResult
}
declare module "blitz" {
export interface Ctx {
prefetchQuery: PrefetchQueryFn

View File

@@ -1,5 +1,63 @@
# @blitzjs/rpc
## 2.0.0-beta.72
### Patch Changes
- 2cc888ef: Beta release
- Updated dependencies [2cc888ef]
- @blitzjs/auth@2.0.0-beta.72
## 2.0.0-alpha.71
### Patch Changes
- @blitzjs/auth@2.0.0-alpha.71
## 2.0.0-alpha.70
### Patch Changes
- @blitzjs/auth@2.0.0-alpha.70
## 2.0.0-alpha.69
### Patch Changes
- 49028024: Add `getQueryData` utility to get an existing query's cached data
- @blitzjs/auth@2.0.0-alpha.69
## 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
- @blitzjs/auth@2.0.0-alpha.67
## 2.0.0-alpha.66
### Patch Changes
- 807a2b56: Fixes peer dependency warnings
- a3e6c49c: Fixes the supports-color warning for pnpm
- 9620ef6b: moves zod to devDependencies
- Updated dependencies [a3e6c49c]
- @blitzjs/auth@2.0.0-alpha.66
## 2.0.0-alpha.65
### Patch Changes
- Updated dependencies [dd5f5174]
- blitz@2.0.0-alpha.65
- @blitzjs/auth@2.0.0-alpha.65
## 2.0.0-alpha.64
### Patch Changes

View File

@@ -14,6 +14,9 @@ const config: BuildConfig = {
"index-server.cjs",
"index-server.mjs",
"react",
"blitz",
"next",
"zod",
],
declaration: true,
rollup: {

View File

@@ -1,6 +1,6 @@
{
"name": "@blitzjs/rpc",
"version": "2.0.0-alpha.64",
"version": "2.0.0-beta.0",
"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,31 +20,28 @@
"dist/**"
],
"dependencies": {
"@blitzjs/auth": "2.0.0-alpha.64",
"@blitzjs/auth": "2.0.0-beta.0",
"@tanstack/react-query": "4.0.10",
"b64-lite": "1.4.0",
"bad-behavior": "1.0.1",
"chalk": "^4.1.0",
"debug": "4.3.3",
"superjson": "1.8.0",
"zod": "3.17.3"
"supports-color": "8.1.1"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.64",
"@blitzjs/config": "workspace:2.0.0-beta.0",
"@types/debug": "4.1.7",
"@types/react": "18.0.1",
"@types/react-dom": "17.0.14",
"blitz": "2.0.0-alpha.64",
"blitz": "2.0.0-beta.0",
"next": "12.2.0",
"react": "18.0.0",
"react-dom": "18.0.0",
"typescript": "^4.5.3",
"unbuild": "0.7.6",
"watch": "1.0.2"
},
"peerDependencies": {
"blitz": "2.0.0-alpha.64",
"next": ">=12.2.0"
"watch": "1.0.2",
"zod": "3.17.3"
},
"publishConfig": {
"access": "public"

View File

@@ -7,6 +7,7 @@ export {
invalidateQuery,
setQueryData,
getQueryClient,
getQueryData,
} from "./react-query-utils"
export {
useQueryErrorResetBoundary,

View File

@@ -1,4 +1,4 @@
import {QueryClient} from "@tanstack/react-query"
import {QueryClient, QueryFilters} from "@tanstack/react-query"
import {serialize} from "superjson"
import {isClient, isServer, AsyncFunc} from "blitz"
import {ResolverType, RpcClient} from "./rpc"
@@ -199,3 +199,15 @@ export function setQueryData<TInput, TResult, T extends AsyncFunc>(
}
})
}
export function getQueryData<TInput, TResult, T extends AsyncFunc>(
resolver: T | Resolver<TInput, TResult> | RpcClient<TInput, TResult>,
params: TInput,
): TResult | undefined {
if (typeof resolver === "undefined") {
throw new Error("getQueryData is missing the first argument - it must be a resolver function")
}
const queryKey = getQueryKey(resolver, params)
return getQueryClient().getQueryData(queryKey)
}

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"
@@ -68,6 +69,11 @@ interface WebpackRule {
export interface InstallWebpackConfigOptions {
webpackConfig: {
resolve: {
alias: {
[key: string]: boolean
}
}
module: {
rules: WebpackRule[]
}
@@ -79,6 +85,8 @@ export function installWebpackConfig({
webpackConfig,
webpackRuleOptions,
}: InstallWebpackConfigOptions) {
webpackConfig.resolve.alias["npm-which"] = false
webpackConfig.resolve.alias["cross-spawn"] = false
webpackConfig.module.rules.push({
test: /[\\/]\[\[\.\.\.blitz]]\.[jt]sx?$/,
use: [
@@ -149,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)
@@ -168,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,
@@ -182,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)
@@ -200,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) {
@@ -219,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
@@ -239,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,84 @@
# blitz
## 2.0.0-beta.72
### Patch Changes
- 2cc888ef: Beta release
- Updated dependencies [2cc888ef]
- @blitzjs/generator@2.0.0-beta.72
## 2.0.0-alpha.71
### Patch Changes
- Updated dependencies [176c7b8b]
- @blitzjs/generator@2.0.0-alpha.71
## 2.0.0-alpha.70
### Patch Changes
- Updated dependencies [4656e6ec]
- Updated dependencies [1e0ec7a9]
- @blitzjs/generator@2.0.0-alpha.70
## 2.0.0-alpha.69
### Patch Changes
- fd31e56b: Add back blitz generate command
- Updated dependencies [fd31e56b]
- Updated dependencies [6baab190]
- Updated dependencies [37623a4f]
- @blitzjs/generator@2.0.0-alpha.69
## 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
- Updated dependencies [ebd74b4e]
- @blitzjs/generator@2.0.0-alpha.67
## 2.0.0-alpha.66
### Patch Changes
- 928e840b: Fixes loading production env variables by default for blitz build command
- 240f3f34: Add BlitzServerMiddleware utility function to wrap middleware in blitz server file
- 55b1cb20: Runs the codegen on the blitz build command
- 4d7d126d: Run `prisma generate` as a `blitz codegen` step if "prisma" is found in project's dependencies
- 890b0c0c: Improve `blitz new` messaging and fix minor issues
- 807a2b56: Fixes peer dependency warnings
- a3e6c49c: Fixes the supports-color warning for pnpm
- Updated dependencies [91aa5356]
- Updated dependencies [890b0c0c]
- Updated dependencies [807a2b56]
- Updated dependencies [a3e6c49c]
- Updated dependencies [065db256]
- Updated dependencies [f202aac1]
- @blitzjs/generator@2.0.0-alpha.66
## 2.0.0-alpha.65
### Patch Changes
- dd5f5174: Fix `enhancePrisma is undefined` errors by moving the utility function to a browser entrypoint
- @blitzjs/generator@2.0.0-alpha.65
## 2.0.0-alpha.64
### Patch Changes

View File

@@ -2,7 +2,7 @@ import {BuildConfig} from "unbuild"
const config: BuildConfig = {
entries: ["./src/index-browser", "./src/index-server", "./src/cli/index"],
externals: ["index-browser.cjs", "index-browser.mjs", "index.cjs", "zod"],
externals: ["index-browser.cjs", "index-browser.mjs", "index.cjs", "zod", "react"],
declaration: true,
rollup: {
emitCJS: true,

View File

@@ -1,6 +1,6 @@
{
"name": "blitz",
"version": "2.0.0-alpha.64",
"version": "2.0.0-beta.0",
"scripts": {
"build": "unbuild",
"dev": "watch unbuild src --wait=0.2",
@@ -23,7 +23,7 @@
"blitz": "bin/blitz"
},
"dependencies": {
"@blitzjs/generator": "2.0.0-alpha.64",
"@blitzjs/generator": "2.0.0-beta.0",
"arg": "5.0.1",
"boxen": "7.0.0",
"chalk": "^4.1.0",
@@ -48,13 +48,14 @@
"resolve-cwd": "3.0.0",
"resolve-from": "5.0.0",
"superjson": "1.8.0",
"supports-color": "8.1.1",
"ts-node": "10.7.0",
"tsconfig-paths": "4.0.0",
"tslog": "3.3.1",
"watchpack": "2.1.1"
},
"devDependencies": {
"@blitzjs/config": "workspace:2.0.0-alpha.64",
"@blitzjs/config": "workspace:2.0.0-beta.0",
"@types/cookie": "0.4.1",
"@types/cross-spawn": "6.0.2",
"@types/debug": "4.1.7",
@@ -78,9 +79,6 @@
"watch": "1.0.2",
"zod": "3.17.3"
},
"peerDependencies": {
"react": "*"
},
"publishConfig": {
"access": "public"
}

View File

@@ -1,37 +1,14 @@
import {CliCommand} from "../index"
/* @ts-ignore */
import {generateManifest} from "../utils/routes-manifest"
import resolveCwd from "resolve-cwd"
import {join} from "path"
import fs from "fs-extra"
import {codegenTasks} from "../utils/codegen-tasks"
const codegen: CliCommand = async () => {
try {
/*
Updates the user's nextjs file and adds onRecoverableError to the hydrateRoot 3rd parameter object.
We can remove this when https://github.com/vercel/next.js/pull/38207 is merged into next.js
*/
const nextDir = await resolveCwd("next")
const nextClientIndex = join(nextDir, "../..", "client", "index.js")
const readFile = await fs.readFile(nextClientIndex)
const updatedFile = readFile
.toString()
.replace(
/ReactDOM\.hydrateRoot\(.*?\);/,
`ReactDOM.hydrateRoot(domEl, reactEl, process.env.NODE_ENV === 'development' ? {onRecoverableError: (err) => err.toString().includes("could not finish this Suspense boundary") ? null : console.error(err)} : undefined);`,
)
await fs.writeFile(nextClientIndex, updatedFile)
await codegenTasks()
process.exit(0)
} catch (err) {
console.log(err)
process.exit(1)
}
try {
await generateManifest()
} catch (err) {
console.log(err)
}
process.exit(0)
}
export {codegen}

View File

@@ -1,22 +1,21 @@
import {
capitalize,
FormGenerator,
ModelGenerator,
MutationGenerator,
MutationsGenerator,
PageGenerator,
pluralCamel,
pluralPascal,
QueriesGenerator,
QueryGenerator,
singleCamel,
singlePascal,
uncapitalize,
} from "@blitzjs/generator"
import arg from "arg"
import {CliCommand} from "../index"
import prompts from "prompts"
import chalk from "chalk"
import {
capitalize,
pluralCamel,
pluralPascal,
singleCamel,
singlePascal,
uncapitalize,
PageGenerator,
FormGenerator,
QueriesGenerator,
MutationGenerator,
MutationsGenerator,
ModelGenerator,
QueryGenerator,
} from "@blitzjs/generator"
const getIsTypeScript = async () =>
require("fs").existsSync(require("path").join(process.cwd(), "tsconfig.json"))
@@ -69,7 +68,6 @@ const args = arg(
// Types
"--help": Boolean,
"--type": String,
"--name": String,
"--context": String,
"--parent": String,
"--dry-run": Boolean,
@@ -77,10 +75,10 @@ const args = arg(
// Aliases
"-e": "--env",
"-n": "--name",
"-t": "--type",
"-c": "--context",
"-p": "--dry-run",
"-p": "--parent",
"-d": "--dry-run",
},
{
permissive: true,
@@ -172,23 +170,8 @@ const determineName = async () => {
}
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`,
})
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 (args["--context"] && selectedModelName && !selectedContext) {
selectedContext = args["--context"]
}
}
@@ -196,33 +179,33 @@ 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 crud productVariant
# The 'all' generator will scaffold out everything possible for a model
> blitz generate --type all --name products
# The '--context' flag will allow you to generate files in a nested folder
> blitz generate --type pages --name projects --context admin
> blitz generate all products
# The '--context' flag will allow you to generate files such as components, queries & mutations in a nested folder
> blitz generate pages projects --context=admin
# Context can also be supplied in the model name directly
> 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/
> blitz generate --type all --name tasks --parent=projects
> blitz generate pages 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 pages/projects/[projectId]/tasks/
> blitz generate all 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").
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 all --name tasks name:string completed:boolean:default=false belongsTo:project?
> blitz generate model task name:string completed:boolean:default=false belongsTo:project?
> blitz generate all tasks name:string completed:boolean:default=false belongsTo:project?
`)
@@ -230,26 +213,23 @@ const getHelp = async () => {
}
}
const generate: CliCommand = async (argv) => {
const generate: CliCommand = async () => {
await getHelp()
await determineType()
await determineContext()
if (!selectedModelName) {
await determineName()
}
await determineContext()
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]
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),

View File

@@ -1,4 +1,3 @@
import {loadEnvConfig} from "../../env-utils"
import prompts from "prompts"
import path from "path"
import chalk from "chalk"
@@ -6,20 +5,20 @@ import hasbin from "hasbin"
import {CliCommand} from "../index"
import arg from "arg"
import {AppGenerator, AppGeneratorOptions, getLatestVersion} from "@blitzjs/generator"
import {runPrisma} from "../../prisma-utils"
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 = {
"react-final-form": "React Final Form" as const,
"react-hook-form": "React Hook Form" as const,
formik: "Formik" as const,
const forms: Record<AppGeneratorOptions["form"], string> = {
finalform: "React Final Form (recommended)",
hookform: "React Hook Form",
formik: "Formik",
}
type TForms = keyof typeof forms
const language = {
typescript: "TypeScript",
javascript: "Javascript",
javascript: "JavaScript",
}
type TLanguage = keyof typeof language
@@ -75,7 +74,7 @@ const args = arg(
let projectName: string = ""
let projectPath: string = ""
let projectLanguage: string | TLanguage = ""
let projectFormLib: AppGeneratorOptions["form"] = undefined
let projectFormLib: AppGeneratorOptions["form"] = "finalform"
let projectTemplate: AppGeneratorOptions["template"] = templates.full
let projectPkgManger: TPkgManager = PREFERABLE_PKG_MANAGER
let shouldInstallDeps: boolean = true
@@ -110,7 +109,7 @@ const determineLanguage = async () => {
const res = await prompts({
type: "select",
name: "language",
message: "Pick which language you'd like to use for your new blitz project",
message: "Pick a new project's language",
initial: 0,
choices: Object.entries(language).map((c) => {
return {title: c[1], value: c[1]}
@@ -129,16 +128,16 @@ const determineFormLib = async () => {
const res = await prompts({
type: "select",
name: "form",
message: "Pick which form you'd like to use for your new blitz project",
message: "Pick a form library (you can switch to something else later if you want)",
initial: 0,
choices: Object.entries(forms).map((c) => {
return {title: c[1], value: c[1]}
return {value: c[0], title: c[1]}
}),
})
projectFormLib = res.form
} else {
projectFormLib = forms[args["--form"] as TForms]
projectFormLib = args["--form"] as AppGeneratorOptions["form"]
}
}
@@ -148,14 +147,17 @@ const determineTemplate = async () => {
!args["--template"] ||
(args["--template"] && !Object.keys(templates).includes(args["--template"].toLowerCase()))
) {
const choices: Array<{value: keyof typeof templates; title: string}> = [
{value: "full", title: "Full - includes DB and auth (Recommended)"},
{value: "minimal", title: "Minimal — no DB, no auth"},
]
const res = await prompts({
type: "select",
name: "template",
message: "Pick which template you'd like to use for your new blitz project",
message: "Pick your new app template",
initial: 0,
choices: Object.entries(templates).map((c) => {
return {title: c[0], value: c[0]}
}),
choices,
})
projectTemplate = templates[res.template as TTemplate]
@@ -203,7 +205,11 @@ const determinePkgManagerToInstallDeps = async () => {
],
})
projectPkgManger = res.pkgManager
if (res.pkgManager === "skip") {
projectPkgManger = PREFERABLE_PKG_MANAGER
} else {
projectPkgManger = res.pkgManager
}
shouldInstallDeps = res.pkgManager !== "skip"
} else {
@@ -264,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

@@ -15,7 +15,7 @@ const build: CliCommand = async () => {
const config: ServerConfig = {
rootFolder: process.cwd(),
inspect: nextArgs["--inspect"],
env: process.env.NODE_ENV === "production" ? "prod" : "dev",
env: "prod",
}
await import("../../utils/next-commands").then((i) => i.build(config))

View File

@@ -1,38 +1,6 @@
import {Readable} from "stream"
import {getCommandBin} from "../utils/config"
import {CliCommand} from "../index"
import arg from "arg"
let prismaBin: string
export const runPrisma = async (args: string[], silent = false) => {
if (!prismaBin) {
try {
prismaBin = await getCommandBin("prisma")
} catch (err) {
throw err
}
}
const cp = require("cross-spawn").spawn(prismaBin, args, {
stdio: silent ? "pipe" : "inherit",
env: process.env,
})
const cp_stderr: string[] = []
if (silent) {
cp.stderr.on("data", (chunk: Readable) => {
cp_stderr.push(chunk.toString())
})
}
const code = await require("p-event")(cp, "exit", {rejectionEvents: []})
return {
success: code === 0,
stderr: silent ? cp_stderr.join("") : undefined,
}
}
import {runPrisma} from "../../utils/run-prisma"
export const runPrismaExitOnError = async (...args: Parameters<typeof runPrisma>) => {
const result = await runPrisma(...args)

View File

@@ -1,7 +1,7 @@
import arg from "arg"
import spawn from "cross-spawn"
import {loadEnvConfig} from "../env-utils"
import {loadEnvConfig} from "../utils/env"
import {NON_STANDARD_NODE_ENV} from "./utils/constants"
import {getCommandBin} from "./utils/config"
import {readVersions} from "./utils/read-versions"
@@ -41,7 +41,7 @@ const aliases: Record<string, keyof typeof commands> = {
b: "build",
s: "start",
n: "new",
g: "generate",
// g: "generate",
}
type Command = keyof typeof commands
@@ -124,7 +124,6 @@ async function main() {
if (args["--env"]) {
process.env.APP_ENV = args["--env"]
}
loadEnvConfig(process.cwd(), undefined, {error: console.error, info: console.info})
// Version is inlined into the file using taskr build pipeline
if (args["_"].length === 0 && args["--version"]) {
@@ -145,7 +144,7 @@ async function main() {
}
process.env.NODE_ENV = process.env.NODE_ENV || defaultEnv
loadEnvConfig(process.cwd(), undefined, {error: console.error, info: console.info})
// Make sure commands gracefully respect termination signals (e.g. from Docker)
process.on("SIGTERM", () => process.exit(0))
process.on("SIGINT", () => process.exit(0))

View File

@@ -0,0 +1,54 @@
import {generateManifest} from "./routes-manifest"
import {log} from "../../logging"
import resolveCwd from "resolve-cwd"
import {join} from "path"
import fs from "fs-extra"
import {getPackageJson} from "./get-package-json"
import {runPrisma} from "../../utils/run-prisma"
export const codegenTasks = async () => {
try {
/*
Updates the user's nextjs file and adds onRecoverableError to the hydrateRoot 3rd parameter object.
We can remove this when https://github.com/vercel/next.js/pull/38207 is merged into next.js
*/
const nextDir = await resolveCwd("next")
const nextClientIndex = join(nextDir, "../..", "client", "index.js")
const readFile = await fs.readFile(nextClientIndex)
const updatedFile = readFile
.toString()
.replace(
/ReactDOM\.hydrateRoot\(.*?\);/,
`ReactDOM.hydrateRoot(domEl, reactEl, process.env.NODE_ENV === 'development' ? {onRecoverableError: (err) => err.toString().includes("could not finish this Suspense boundary") ? null : console.error(err)} : undefined);`,
)
await fs.writeFile(nextClientIndex, updatedFile)
log.success("Next.js was successfully patched with a React Suspense fix")
} catch (err) {
log.error(JSON.stringify(err, null, 2))
}
try {
await generateManifest()
log.success("Routes manifest was successfully generated")
const {dependencies, devDependencies} = await getPackageJson()
const hasPrisma = Object.keys({...dependencies, ...devDependencies}).some(
(name) => name === "prisma",
)
if (hasPrisma) {
let prismaSpinner = log.spinner(`Generating Prisma client`).start()
const result = await runPrisma(["generate"], true)
if (result.success) {
prismaSpinner.succeed(log.greenText("Generated Prisma client"))
} else {
prismaSpinner.fail()
console.log("\n" + result.stderr)
process.exit(1)
}
}
} catch (err) {
log.error(JSON.stringify(err, null, 2))
}
}

View File

@@ -0,0 +1,11 @@
import {existsSync} from "fs"
import {readJSON} from "fs-extra"
import {join} from "path"
export const getPackageJson = async () => {
const pkgJsonPath = join(process.cwd(), "package.json")
if (existsSync(pkgJsonPath)) {
return readJSON(pkgJsonPath)
}
return {}
}

View File

@@ -8,17 +8,19 @@ import {
buildCustomServer,
} from "./next-utils"
import {checkLatestVersion} from "./check-latest-version"
import {readBlitzConfig} from "../../server-utils"
import {readBlitzConfig} from "../../utils/server"
import {codegenTasks} from "./codegen-tasks"
export async function build(config: ServerConfig) {
const {rootFolder, nextBin, watch} = await normalize(config)
await codegenTasks()
await nextBuild(nextBin, rootFolder, {} as any, config)
if (customServerExists()) await buildCustomServer({watch})
}
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

@@ -590,7 +590,7 @@ export async function stopWatcher(): Promise<void> {
if (!webpackWatcher) {
return
}
console.log("stopWatcher")
webpackWatcher.close()
webpackWatcher = null
}

View File

@@ -79,7 +79,7 @@ if (typeof window !== "undefined" && process.env.NODE_ENV === "development") {
}
export * from "./utils"
export * from "./ts-utils"
export * from "./types"
export * from "./errors"
export * from "./zod-utils"
export * from "./utils/zod"
export * from "./utils/prisma"

View File

@@ -1,19 +1,14 @@
import "./global"
import {IncomingMessage, ServerResponse} from "http"
import {Ctx} from "./types"
// import {findBlitzConfigDirectory} from "./cli/utils/routes-manifest"
// import {readFileSync} from "fs-extra"
export * from "./index-browser"
export * from "./types"
export * from "./prisma-utils"
export * from "./utils/run-prisma"
export * from "./middleware"
export * from "./paginate"
export {baseLogger, newLine, log} from "./logging"
export {startWatcher, stopWatcher} from "./cli/utils/routes-manifest"
// const blitzConfig = findBlitzConfigDirectory() as string
// const file = readFileSync(blitzConfig)
// export const Routes = eval(file.toString())
export interface MiddlewareResponse<C extends Ctx = Ctx> extends ServerResponse {
blitzCtx: C
@@ -59,3 +54,11 @@ export function createSetupServer<TMiddleware extends RequestMiddleware, TExport
) {
return setupServerConstructor
}
export const BlitzServerMiddleware = <
TMiddleware extends RequestMiddleware<any, any> = RequestMiddleware,
>(
middleware: TMiddleware,
): BlitzServerPlugin => ({
requestMiddlewares: [middleware],
})

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,38 +0,0 @@
export type AsyncFunc = (...args: any) => Promise<any>
/**
* Infer the type of the parameter from function that takes a single argument
*/
export type FirstParam<F extends (...args: any) => Promise<any>> = Parameters<F>[0]
/**
* If type has a Promise, unwrap it. Otherwise return the original type
*/
export type Await<T> = T extends PromiseLike<infer U> ? U : T
/**
* Ensure the type is a promise
*/
export type EnsurePromise<T> = T extends PromiseLike<unknown> ? T : Promise<T>
/**
* Get the return type of a function which returns a Promise.
*/
export type PromiseReturnType<T extends (...args: any) => Promise<any>> = Await<ReturnType<T>>
export interface CancellablePromise<T> extends Promise<T> {
cancel?: Function
}
export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
k: infer I,
) => void
? I
: never
export type Simplify<T> = {[P in keyof T]: T[P]}
export type AddParameters<
TFunction extends (...args: any) => any,
TParameters extends [...args: any],
> = (...args: [...Parameters<TFunction>, ...TParameters]) => ReturnType<TFunction>

Some files were not shown because too many files have changed in this diff Show More