Skip to content
Merged

Next #321

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Nullstack

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ Get to know the [Nullstack Contributors](https://nullstack.app/contributors)

## License

Nullstack is released under the [MIT License](https://opensource.org/licenses/MIT).
Nullstack is released under the [MIT License](LICENSE).
24 changes: 21 additions & 3 deletions client/instanceProxyHandler.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import client from './client'
import { generateContext } from './context'
import context, { generateContext } from './context'
import { generateObjectProxy } from './objectProxyHandler'

export const instanceProxies = new WeakMap()
Expand All @@ -15,8 +15,26 @@ const instanceProxyHandler = {
}
const { [name]: named } = {
[name]: (args) => {
const context = generateContext({ ...target._attributes, ...args })
return target[name].call(proxy, context)
const scopedContext = generateContext({ ...target._attributes, ...args })
let result
try {
result = target[name].call(proxy, scopedContext)
} catch (error) {
if (context.catch) {
context.catch(error)
} else {
throw error
}
return null
}
if (result instanceof Promise) {
return new Promise((resolve, reject) => {
result.then(resolve).catch((error) => {
context.catch ? context.catch(error) : reject(error)
})
})
}
return result
},
}
return named
Expand Down
4 changes: 3 additions & 1 deletion loaders/add-source-to-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ module.exports = function (source) {
if (path.parent.type === 'JSXAttribute') {
if (path.node.name.startsWith('on')) {
const element = path.findParent((p) => p.type === 'JSXOpeningElement' && p.node.attributes)
const hasSource = element.node.attributes.find((a) => a.name.name === 'source')
const hasSource = element.node.attributes.find((a) => {
return a.type === 'JSXAttribute' && a.name.name === 'source'
})
if (!hasSource) {
const start = element.node.attributes[0].start
uniquePositions.add(start)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nullstack",
"version": "0.17.4",
"version": "0.17.5",
"description": "Full Stack Javascript Components for one-dev armies",
"main": "nullstack.js",
"author": "Mortaro",
Expand Down
2 changes: 1 addition & 1 deletion plugins/bindable.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function transform({ node, environment }) {
const object = node.attributes.bind.object ?? {}
const property = node.attributes.bind.property
if (node.type === 'textarea') {
node.children = [object[property]]
node.children = [object[property] ?? '']
} else if (node.type === 'input' && node.attributes.type === 'checkbox') {
node.attributes.checked = object[property]
} else {
Expand Down
5 changes: 5 additions & 0 deletions server/printError.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import context from './context'

export default function (error) {
if (context.catch) {
context.catch(error)
}
const lines = error.stack.split(`\n`)
let initiator = lines.find((line) => line.indexOf('Proxy') > -1)
if (initiator) {
Expand Down
20 changes: 19 additions & 1 deletion server/reqres.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,20 @@
const reqres = {}
class ReqRes {

request = null
response = null

set(request, response) {
this.request = request
this.response = response
}

clear() {
this.request = null
this.response = null
}

}

const reqres = new ReqRes()

export default reqres
24 changes: 17 additions & 7 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ for (const method of ['get', 'post', 'put', 'patch', 'delete', 'all']) {
server[method] = function (...args) {
if (typeof args[1] === 'function' && args[1].name === '_invoke') {
return original(args[0], bodyParser.text({ limit: server.maximumPayloadSize }), async (request, response) => {
reqres.set(request, response)
const params = {}
for (const key of Object.keys(request.params)) {
params[key] = extractParamValue(request.params[key])
Expand All @@ -48,14 +49,17 @@ for (const method of ['get', 'post', 'put', 'patch', 'delete', 'all']) {
params[key] = extractParamValue(request.query[key])
}
if (request.method !== 'GET') {
Object.assign(params, deserialize(request.body))
const payload = typeof request.body === 'object' ? JSON.stringify(request.body) : request.body
Object.assign(params, deserialize(payload))
}
try {
const subcontext = generateContext({ request, response, ...params })
const result = await args[1](subcontext)
reqres.clear()
response.json(result)
} catch (error) {
printError(error)
reqres.clear()
response.status(500).json({})
}
})
Expand Down Expand Up @@ -224,6 +228,7 @@ server.start = function () {

server.all(`/${prefix}/:hash/:methodName.json`, async (request, response) => {
const payload = request.method === 'GET' ? request.query.payload : request.body
reqres.set(request, response)
const args = deserialize(payload)
const { hash, methodName } = request.params
const [invokerHash, boundHash] = hash.split('-')
Expand All @@ -241,12 +246,15 @@ server.start = function () {
try {
const subcontext = generateContext({ request, response, ...args })
const result = await method.call(boundKlass, subcontext)
reqres.clear()
response.json({ result })
} catch (error) {
printError(error)
reqres.clear()
response.status(500).json({})
}
} else {
reqres.clear()
response.status(404).json({})
}
})
Expand All @@ -255,21 +263,23 @@ server.start = function () {
if (request.originalUrl.split('?')[0].indexOf('.') > -1) {
return next()
}
reqres.request = request
reqres.response = response
reqres.set(request, response)
const scope = await prerender(request, response)
if (!response.headersSent) {
const status = scope.context.page.status
const html = template(scope)
reqres.request = null
reqres.response = null
reqres.clear()
response.status(status).send(html)
} else {
reqres.request = null
reqres.response = null
reqres.clear()
}
})

server.use((error, _request, response, _next) => {
printError(error)
response.status(500).json({})
})

if (!server.less) {
if (!server.port) {
console.info('\x1b[31mServer port is not defined!\x1b[0m')
Expand Down
8 changes: 8 additions & 0 deletions tests/client.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Nullstack from 'nullstack'

import Application from './src/Application'
import CatchError from './src/CatchError.njs'
import vueable from './src/plugins/vueable'

Nullstack.use(vueable)
Expand All @@ -12,4 +13,11 @@ context.start = function () {
setTimeout(() => (context.startTimedValue = true), 1000)
}

context.catch = async function (error) {
CatchError.logError({ message: error.message })
if (context.environment.development) {
console.error(error)
}
}

export default context
18 changes: 18 additions & 0 deletions tests/server.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import Nullstack from 'nullstack'

import cors from 'cors'
import express from 'express'

import Application from './src/Application'
import CatchError from './src/CatchError'
import ContextProject from './src/ContextProject'
import ContextSecrets from './src/ContextSecrets'
import ContextSettings from './src/ContextSettings'
import ContextWorker from './src/ContextWorker'
import ExposedServerFunctions from './src/ExposedServerFunctions'
import vueable from './src/plugins/vueable'
import ReqRes from './src/ReqRes'

Nullstack.use(vueable)

Expand All @@ -22,6 +25,7 @@ context.server.use(
optionsSuccessStatus: 200,
}),
)
context.server.use(express.json())

context.worker.staleWhileRevalidate = [/[0-9]/]
context.worker.cacheFirst = [/[0-9]/]
Expand All @@ -40,6 +44,9 @@ context.server.put('/data/put/:param', ExposedServerFunctions.getData)
context.server.patch('/data/patch/:param', ExposedServerFunctions.getData)
context.server.delete('/data/delete/:param', ExposedServerFunctions.getData)

context.server.get('/exposed-server-function-url.json', ReqRes.exposedServerFunction)
context.server.get('/nested-exposed-server-function-url.json', ReqRes.nestedExposedServerFunction)

context.server.get('/custom-api-before-start', (request, response) => {
response.json({ startValue: context.startValue })
})
Expand All @@ -57,6 +64,10 @@ for (const method of methods) {
})
}

context.server.get('/vaidamerdanaapi.json', (_request, response) => {
response.vaidamerdanaapi()
})

context.startIncrementalValue = 0

context.start = async function () {
Expand All @@ -68,4 +79,11 @@ context.start = async function () {
context.startIncrementalValue++
}

context.catch = async function (error) {
CatchError.logError({ message: error.message })
if (context.environment.development) {
console.error(error)
}
}

export default context
4 changes: 4 additions & 0 deletions tests/src/Application.njs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import AnchorModifiers from './AnchorModifiers'
import './Application.css'
import ArrayAttributes from './ArrayAttributes'
import BodyFragment from './BodyFragment'
import CatchError from './CatchError'
import ChildComponent from './ChildComponent'
import ComponentTernary from './ComponentTernary'
import Context from './Context'
Expand Down Expand Up @@ -40,6 +41,7 @@ import PublicServerFunctions from './PublicServerFunctions.njs'
import PureComponents from './PureComponents'
import Refs from './Refs'
import RenderableComponent from './RenderableComponent'
import ReqRes from './ReqRes'
import RoutesAndParams from './RoutesAndParams'
import RouteScroll from './RouteScroll'
import ServerFunctions from './ServerFunctions'
Expand Down Expand Up @@ -137,6 +139,8 @@ class Application extends Nullstack {
<RouteScroll route="/route-scroll/*" key="routeScroll" />
<IsomorphicImport route="/isomorphic-import" />
<ExposedServerFunctions route="/exposed-server-functions" />
<CatchError route="/catch-error" />
<ReqRes route="/reqres" />
<ErrorPage route="*" />
</body>
)
Expand Down
47 changes: 47 additions & 0 deletions tests/src/CatchError.njs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Nullstack from 'nullstack'

import { appendFileSync } from 'fs'

const error = new Error('Panic in the system, someone missconfigured me!')

class CatchError extends Nullstack {

static async logError({ message, environment }) {
const folder = environment.production ? '.production' : '.development'
appendFileSync(`${folder}/exceptions.txt`, `${message}\n`)
}

static async getServerFunction() {
throw error
}

async oneErrorPls() {
throw error
}

async hydrate({ params }) {
setTimeout(() => (this.hydrated = true), 0)
if (params.error === 'hydrate') {
await this.vaidamerdanoclient()
}
}

async initiate({ params, page }) {
if (params.error === 'initiate' && page.status === 200) {
this.vaidamerdanoserver()
} else if (params.error === 'initiateServerFunction') {
await this.getServerFunction()
}
}

render() {
return (
<div data-hydrated={this.hydrated}>
<button onclick={this.oneErrorPls}> Error </button>
</div>
)
}

}

export default CatchError
34 changes: 34 additions & 0 deletions tests/src/CatchError.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const { readFileSync } = require('fs')

describe('CatchError initiate', () => {
test('errors caused by instances can be caught on the server', async () => {
await page.goto('http://localhost:6969/catch-error?error=initiate')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('this.vaidamerdanoserver is not a function')).toBeTruthy()
})
})

describe('CatchError initiateServerFunction', () => {
test('errors caused by server functions can be caught on the server', async () => {
await page.goto('http://localhost:6969/catch-error?error=initiateServerFunction')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('Panic in the system, someone missconfigured me!')).toBeTruthy()
})
})

describe('CatchError hydrate', () => {
test('errors caused by instances can be caught on the client', async () => {
await page.goto('http://localhost:6969/catch-error?error=hydrate')
await page.waitForSelector('[data-hydrated]')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('this.vaidamerdanoclient is not a function')).toBeTruthy()
})
})

describe('CatchError api', () => {
test('errors caused by api routes can be caught on the server', async () => {
await page.goto('http://localhost:6969/vaidamerdanaapi.json')
const logs = readFileSync('.production/exceptions.txt', 'utf-8')
expect(logs.includes('response.vaidamerdanaapi is not a function')).toBeTruthy()
})
})
Loading