Skip to content

Commit

Permalink
feat: config.shield.dev (#111)
Browse files Browse the repository at this point in the history
Co-authored-by: Romuald Brillout <git@brillout.com>
  • Loading branch information
samuba and brillout committed Jun 28, 2024
1 parent 213e0d0 commit 2830461
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 6 deletions.
2 changes: 1 addition & 1 deletion docs/components/Example.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function Timestamp({ children }: { children: TimestampType }) {
fontSize: '1.13em',
fontWeight: 'bold',
fontFamily: 'monospace',
marginRight: 2
marginRight: 2,
}}
>
{children}
Expand Down
5 changes: 5 additions & 0 deletions docs/headings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,11 @@ export const headings: HeadingDefinition[] = [
title: '`root`',
url: '/root',
},
{
level: 2,
title: '`shield`',
url: '/shield-config',
},
{
level: 4,
title: 'Plugins',
Expand Down
19 changes: 19 additions & 0 deletions docs/pages/shield-config/+Page.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Link, Warning } from '@brillout/docpress'
import { ConfigWhereServer } from '../../components'

**Environment**: server.
**Default**: `false`.

Whether to generate <Link href="/shield">`shield()`</Link> in development.

```js
// Environment: server

import { config } from 'telefunc'

config.shield.dev = true
```

<Warning>This can slow down development speed. Depending on your app and how fast your computer is, the decreased development speed can range from unnoticeable to significant.</Warning>

<ConfigWhereServer />
4 changes: 4 additions & 0 deletions docs/pages/shield/+Page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ export async function hello({ name }: { name: string }) {

With Telefunc, not only can we seamlessly re-use types across our frontend and backend code, but we also get automatic type-safety at runtime. If we use a TypeScript ORM (e.g. [Prisma](https://www.prisma.io/)) or SQL builder (e.g. [Kysely](https://github.com/koskimas/kysely) and [others](https://github.com/stars/brillout/lists/sql)), then we get end-to-end type safety all the way from database to frontend.

> For a faster development, Telefunc doesn't generate `shield()` and your telefunction arguments aren't validated during development.
> Telefunc only generates `shield()` upon building your app for production.
> You can enable the generation of `shield()` for development by setting <Link href="/shield-config">`config.shield.dev`</Link> to `true`.
> Telefunc's automatic `shield()` generation only works for stacks that transpile server-side code (Next.js, Vite, Vike, SvelteKit, Nuxt, etc.).
>
> For stacks that don't transpile server-side code (e.g. React Native, CRA, Parcel), we need to define `shield()` manually ourselves: see <Link href="#typescript-manual" />.
Expand Down
18 changes: 15 additions & 3 deletions telefunc/node/server/serverConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,20 @@ type ConfigUser = {
telefuncFiles?: string[]
/** Your project root directory, e.g. `/home/alice/code/my-app/` */
root?: string
/** Wether to disable ETag cache headers */
/** Whether to disable ETag cache headers */
disableEtag?: boolean
shield?: {
/** Whether to generate shield during development */
dev?: boolean
}
}
type ConfigResolved = {
telefuncUrl: string
root: string | null
disableEtag: boolean
telefuncFiles: string[] | null
disableNamingConvention: boolean
shield: { dev: boolean }
}

const configUser: ConfigUser = new Proxy({}, { set: validateUserConfig })
Expand All @@ -38,6 +43,7 @@ function getServerConfig(): ConfigResolved {
return {
disableEtag: configUser.disableEtag ?? false,
disableNamingConvention: configUser.disableNamingConvention ?? false,
shield: { dev: configUser.shield?.dev ?? false },
telefuncUrl: configUser.telefuncUrl || '/_telefunc',
telefuncFiles: (() => {
if (configUser.telefuncFiles) {
Expand Down Expand Up @@ -68,7 +74,7 @@ function validateUserConfig(configUserUnwrapped: ConfigUser, prop: string, val:
)
configUserUnwrapped[prop] = val
} else if (prop === 'telefuncFiles') {
const wrongType = '`config.telefuncFiles` should be a list of paths'
const wrongType = 'config.telefuncFiles should be a list of paths'
assertUsage(Array.isArray(val), wrongType)
val.forEach((val: unknown) => {
assertUsage(typeof val === 'string', wrongType)
Expand All @@ -80,7 +86,13 @@ function validateUserConfig(configUserUnwrapped: ConfigUser, prop: string, val:
assertUsage(typeof val === 'boolean', 'config.disableEtag should be a boolean')
configUserUnwrapped[prop] = val
} else if (prop === 'disableNamingConvention') {
assertUsage(typeof val === 'boolean', '`config.disableNamingConvention` should be a boolean')
assertUsage(typeof val === 'boolean', 'config.disableNamingConvention should be a boolean')
configUserUnwrapped[prop] = val
} else if (prop === 'shield') {
assertUsage(typeof val === 'object' && val !== null, 'config.shield should be a object')
if ('dev' in val) {
assertUsage(typeof (val as { dev: unknown }).dev === 'boolean', 'config.shield.dev should be a boolean')
}
configUserUnwrapped[prop] = val
} else {
assertUsage(false, `Unknown config.${prop}`)
Expand Down
2 changes: 1 addition & 1 deletion telefunc/node/server/shield/codegen/generateShield.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function getProject(telefuncFilePath: string, telefuncFileCode: string, appRootD
path.dirname(telefuncFilePath),
`__telefunc_shieldGen_${path.basename(telefuncFilePath)}`,
)
const shieldGenSource = project.createSourceFile(shieldGenFilePath)
const shieldGenSource = project.createSourceFile(shieldGenFilePath, undefined, { overwrite: true })
shieldGenSource.addImportDeclaration({
moduleSpecifier: getImportPath(shieldGenFilePath, typeToShieldFilePath),
namedImports: ['ShieldArrStr'],
Expand Down
4 changes: 3 additions & 1 deletion telefunc/node/transformer/transformTelefuncFileServerSide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export { transformTelefuncFileServerSide }
import { getExportNames } from './getExportNames'
import { assertPosixPath } from './utils'
import { generateShield } from '../server/shield/codegen/generateShield'
import { getServerConfig } from '../server/serverConfig'

async function transformTelefuncFileServerSide(
src: string,
Expand All @@ -17,7 +18,8 @@ async function transformTelefuncFileServerSide(
const exportNames = await getExportNames(src)
let code = decorateTelefunctions(exportNames, src, id.replace(appRootDir, ''), appRootDir, skipRegistration)

if (id.endsWith('.ts') && !isDev) {
const config = getServerConfig()
if (id.endsWith('.ts') && (!isDev || config.shield.dev)) {
code = generateShield(code, id, appRootDir)
}

Expand Down

0 comments on commit 2830461

Please sign in to comment.