...
 
Commits (5)
......@@ -111,4 +111,4 @@ $RECYCLE.BIN/
lib/
data/
!/src/lib/
!/server/lib/
import Vue from 'vue'
import NuxtLoading from './components/nuxt-loading.vue'
let layouts = {
"_default": () => import('./layouts/default.vue' /* webpackChunkName: "layouts/default" */).then(m => m.default || m)
}
let resolvedLayouts = {}
export default {
head: {"meta":[],"link":[],"style":[],"script":[]},
render(h, props) {
const loadingEl = h('nuxt-loading', { ref: 'loading' })
const layoutEl = h(this.layout || 'nuxt')
const templateEl = h('div', {
domProps: {
id: '__layout'
},
key: this.layoutName
}, [ layoutEl ])
const transitionEl = h('transition', {
props: {
name: 'layout',
mode: 'out-in'
}
}, [ templateEl ])
return h('div',{
domProps: {
id: '__nuxt'
}
}, [
loadingEl,
transitionEl
])
},
data: () => ({
layout: null,
layoutName: ''
}),
beforeCreate () {
Vue.util.defineReactive(this, 'nuxt', this.$options.nuxt)
},
created () {
// Add this.$nuxt in child instances
Vue.prototype.$nuxt = this
// add to window so we can listen when ready
if (typeof window !== 'undefined') {
window.$nuxt = this
}
// Add $nuxt.error()
this.error = this.nuxt.error
},
mounted () {
this.$loading = this.$refs.loading
},
watch: {
'nuxt.err': 'errorChanged'
},
methods: {
errorChanged () {
if (this.nuxt.err && this.$loading) {
if (this.$loading.fail) this.$loading.fail()
if (this.$loading.finish) this.$loading.finish()
}
},
setLayout (layout) {
if (!layout || !resolvedLayouts['_' + layout]) layout = 'default'
this.layoutName = layout
let _layout = '_' + layout
this.layout = resolvedLayouts[_layout]
return this.layout
},
loadLayout (layout) {
if (!layout || !(layouts['_' + layout] || resolvedLayouts['_' + layout])) layout = 'default'
let _layout = '_' + layout
if (resolvedLayouts[_layout]) {
return Promise.resolve(resolvedLayouts[_layout])
}
return layouts[_layout]()
.then((Component) => {
resolvedLayouts[_layout] = Component
delete layouts[_layout]
return resolvedLayouts[_layout]
})
.catch((e) => {
if (this.$nuxt) {
return this.$nuxt.error({ statusCode: 500, message: e.message })
}
})
}
},
components: {
NuxtLoading
}
}
This diff is collapsed.
/*
** From https://github.com/egoist/vue-no-ssr
** With the authorization of @egoist
*/
export default {
name: 'no-ssr',
props: ['placeholder'],
data () {
return {
canRender: false
}
},
mounted () {
this.canRender = true
},
render (h) {
if (this.canRender) {
if (
process.env.NODE_ENV === 'development' &&
this.$slots.default &&
this.$slots.default.length > 1
) {
throw new Error('<no-ssr> You cannot use multiple child components')
}
return this.$slots.default && this.$slots.default[0]
}
return h(
'div',
{
class: ['no-ssr-placeholder']
},
this.$slots.placeholder || this.placeholder
)
}
}
export default {
name: 'nuxt-child',
functional: true,
props: ['keepAlive'],
render (h, { parent, data, props }) {
data.nuxtChild = true
const _parent = parent
const transitions = parent.$nuxt.nuxt.transitions
const defaultTransition = parent.$nuxt.nuxt.defaultTransition
let depth = 0
while (parent) {
if (parent.$vnode && parent.$vnode.data.nuxtChild) {
depth++
}
parent = parent.$parent
}
data.nuxtChildDepth = depth
const transition = transitions[depth] || defaultTransition
let transitionProps = {}
transitionsKeys.forEach((key) => {
if (typeof transition[key] !== 'undefined') {
transitionProps[key] = transition[key]
}
})
let listeners = {}
listenersKeys.forEach((key) => {
if (typeof transition[key] === 'function') {
listeners[key] = transition[key].bind(_parent)
}
})
// Add triggerScroll event on beforeEnter (fix #1376)
let beforeEnter = listeners.beforeEnter
listeners.beforeEnter = (el) => {
window.$nuxt.$emit('triggerScroll')
if (beforeEnter) return beforeEnter.call(_parent, el)
}
let routerView = [
h('router-view', data)
]
if (typeof props.keepAlive !== 'undefined') {
routerView = [
h('keep-alive', routerView)
]
}
return h('transition', {
props: transitionProps,
on: listeners
}, routerView)
}
}
const transitionsKeys = [
'name',
'mode',
'appear',
'css',
'type',
'duration',
'enterClass',
'leaveClass',
'appearClass',
'enterActiveClass',
'enterActiveClass',
'leaveActiveClass',
'appearActiveClass',
'enterToClass',
'leaveToClass',
'appearToClass'
]
const listenersKeys = [
'beforeEnter',
'enter',
'afterEnter',
'enterCancelled',
'beforeLeave',
'leave',
'afterLeave',
'leaveCancelled',
'beforeAppear',
'appear',
'afterAppear',
'appearCancelled'
]
<template>
<div class="__nuxt-error-page">
<div class="error">
<svg xmlns="http://www.w3.org/2000/svg" width="90" height="90" fill="#DBE1EC" viewBox="0 0 48 48"><path d="M22 30h4v4h-4zm0-16h4v12h-4zm1.99-10C12.94 4 4 12.95 4 24s8.94 20 19.99 20S44 35.05 44 24 35.04 4 23.99 4zM24 40c-8.84 0-16-7.16-16-16S15.16 8 24 8s16 7.16 16 16-7.16 16-16 16z"/></svg>
<div class="title">{{ message }}</div>
<p class="description" v-if="statusCode === 404">
<nuxt-link class="error-link" to="/">Back to the home page</nuxt-link>
</p>
<p class="description" v-else>An error occurred while rendering the page. Check developer tools console for details.</p>
<div class="logo">
<a href="https://nuxtjs.org" target="_blank" rel="noopener">Nuxt.js</a>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'nuxt-error',
props: ['error'],
head () {
return {
title: this.message,
meta: [
{
name: 'viewport',
content: 'width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no'
}
]
}
},
// Only on debug mode
data () {
return {
mounted: false
}
},
mounted () {
this.mounted = true
},
created () {
console.error(this.error)
},
watch: {
error(newErr) {
if(newErr) {
console.error(newErr)
}
}
},
computed: {
statusCode () {
return (this.error && this.error.statusCode) || 500
},
message () {
return this.error.message || 'Error'
}
}
}
</script>
<style>
.__nuxt-error-page {
padding: 1rem;
background: #F7F8FB;
color: #47494E;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: sans-serif;
font-weight: 100 !important;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
-webkit-font-smoothing: antialiased;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.__nuxt-error-page .error {
max-width: 450px;
}
.__nuxt-error-page .title {
font-size: 1.5rem;
margin-top: 15px;
color: #47494E;
margin-bottom: 8px;
}
.__nuxt-error-page .description {
color: #7F828B;
line-height: 21px;
margin-bottom: 10px;
}
.__nuxt-error-page a {
color: #7F828B !important;
text-decoration: none;
}
.__nuxt-error-page .logo {
position: fixed;
left: 12px;
bottom: 12px;
}
</style>
export default {
name: 'nuxt-link',
functional: true,
render (h, { data, children }) {
return h('router-link', data, children)
}
}
<template>
<div class="nuxt-progress" :style="{
'width': percent+'%',
'height': height,
'background-color': canSuccess? color : failedColor,
'opacity': show ? 1 : 0
}"></div>
</template>
<script>
import Vue from 'vue'
export default {
name: 'nuxt-loading',
data () {
return {
percent: 0,
show: false,
canSuccess: true,
duration: 5000,
height: '2px',
color: '#92D3CE',
failedColor: 'red',
}
},
methods: {
start () {
this.show = true
this.canSuccess = true
if (this._timer) {
clearInterval(this._timer)
this.percent = 0
}
this._cut = 10000 / Math.floor(this.duration)
this._timer = setInterval(() => {
this.increase(this._cut * Math.random())
if (this.percent > 95) {
this.finish()
}
}, 100)
return this
},
set (num) {
this.show = true
this.canSuccess = true
this.percent = Math.floor(num)
return this
},
get () {
return Math.floor(this.percent)
},
increase (num) {
this.percent = this.percent + Math.floor(num)
return this
},
decrease (num) {
this.percent = this.percent - Math.floor(num)
return this
},
finish () {
this.percent = 100
this.hide()
return this
},
pause () {
clearInterval(this._timer)
return this
},
hide () {
clearInterval(this._timer)
this._timer = null
setTimeout(() => {
this.show = false
Vue.nextTick(() => {
setTimeout(() => {
this.percent = 0
}, 200)
})
}, 500)
return this
},
fail () {
this.canSuccess = false
return this
}
}
}
</script>
<style>
.nuxt-progress {
position: fixed;
top: 0px;
left: 0px;
right: 0px;
height: 2px;
width: 0%;
transition: width 0.2s, opacity 0.4s;
opacity: 1;
background-color: #efc14e;
z-index: 999999;
}
</style>
import Vue from 'vue'
import NuxtChild from './nuxt-child'
import NuxtError from './nuxt-error.vue'
import { compile } from '../utils'
export default {
name: 'nuxt',
props: ['nuxtChildKey', 'keepAlive'],
render(h) {
// If there is some error
if (this.nuxt.err) {
return h('nuxt-error', {
props: {
error: this.nuxt.err
}
})
}
// Directly return nuxt child
return h('nuxt-child', {
key: this.routerViewKey,
props: this.$props
})
},
beforeCreate () {
Vue.util.defineReactive(this, 'nuxt', this.$root.$options.nuxt)
},
computed: {
routerViewKey () {
// If nuxtChildKey prop is given or current route has children
if (typeof this.nuxtChildKey !== 'undefined' || this.$route.matched.length > 1) {
return this.nuxtChildKey || compile(this.$route.matched[0].path)(this.$route.params)
}
const Component = this.$route.matched[0] && this.$route.matched[0].components.default
if (Component && Component.options && Component.options.key) {
return (typeof Component.options.key === 'function' ? Component.options.key(this.$route) : Component.options.key)
}
return this.$route.path
}
},
components: {
NuxtChild,
NuxtError
}
}
// This file is intentionally left empty for noop aliases
import 'es6-promise/auto'
import Vue from 'vue'
import Meta from 'vue-meta'
import { createRouter } from './router.js'
import NoSSR from './components/no-ssr.js'
import NuxtChild from './components/nuxt-child.js'
import NuxtLink from './components/nuxt-link.js'
import NuxtError from './components/nuxt-error.vue'
import Nuxt from './components/nuxt.js'
import App from './App.js'
import { setContext, getLocation, getRouteData } from './utils'
/* Plugins */
// Component: <no-ssr>
Vue.component(NoSSR.name, NoSSR)
// Component: <nuxt-child>
Vue.component(NuxtChild.name, NuxtChild)
// Component: <nuxt-link>
Vue.component(NuxtLink.name, NuxtLink)
// Component: <nuxt>`
Vue.component(Nuxt.name, Nuxt)
// vue-meta configuration
Vue.use(Meta, {
keyName: 'head', // the component option name that vue-meta looks for meta info on.
attribute: 'data-n-head', // the attribute name vue-meta adds to the tags it observes
ssrAttribute: 'data-n-head-ssr', // the attribute name that lets vue-meta know that meta info has already been server-rendered
tagIDKeyName: 'hid' // the property name that vue-meta uses to determine whether to overwrite or append a tag
})
const defaultTransition = {"name":"page","mode":"out-in","appear":false,"appearClass":"appear","appearActiveClass":"appear-active","appearToClass":"appear-to"}
async function createApp (ssrContext) {
const router = createRouter()
// Create Root instance
// here we inject the router and store to all child components,
// making them available everywhere as `this.$router` and `this.$store`.
const app = {
router,
nuxt: {
defaultTransition,
transitions: [ defaultTransition ],
setTransitions (transitions) {
if (!Array.isArray(transitions)) {
transitions = [ transitions ]
}
transitions = transitions.map((transition) => {
if (!transition) {
transition = defaultTransition
} else if (typeof transition === 'string') {
transition = Object.assign({}, defaultTransition, { name: transition })
} else {
transition = Object.assign({}, defaultTransition, transition)
}
return transition
})
this.$options.nuxt.transitions = transitions
return transitions
},
err: null,
dateErr: null,
error (err) {
err = err || null
app.context._errored = !!err
if (typeof err === 'string') err = { statusCode: 500, message: err }
const nuxt = this.nuxt || this.$options.nuxt
nuxt.dateErr = Date.now()
nuxt.err = err
// Used in lib/server.js
if (ssrContext) ssrContext.nuxt.error = err
return err
}
},
...App
}
const next = ssrContext ? ssrContext.next : location => app.router.push(location)
// Resolve route
let route
if (ssrContext) {
route = router.resolve(ssrContext.url).route
} else {
const path = getLocation(router.options.base)
route = router.resolve(path).route
}
// Set context to app.context
await setContext(app, {
route,
next,
error: app.nuxt.error.bind(app),
payload: ssrContext ? ssrContext.payload : undefined,
req: ssrContext ? ssrContext.req : undefined,
res: ssrContext ? ssrContext.res : undefined,
beforeRenderFns: ssrContext ? ssrContext.beforeRenderFns : undefined
})
const inject = function (key, value) {
if (!key) throw new Error('inject(key, value) has no key provided')
if (!value) throw new Error('inject(key, value) has no value provided')
key = '$' + key
// Add into app
app[key] = value
// Check if plugin not already installed
const installKey = '__nuxt_' + key + '_installed__'
if (Vue[installKey]) return
Vue[installKey] = true
// Call Vue.use() to install the plugin into vm
Vue.use(() => {
if (!Vue.prototype.hasOwnProperty(key)) {
Object.defineProperty(Vue.prototype, key, {
get () {
return this.$root.$options[key]
}
})
}
})
}
// Plugin execution
// If server-side, wait for async component to be resolved first
if (process.server && ssrContext && ssrContext.url) {
await new Promise((resolve, reject) => {
router.push(ssrContext.url, resolve, () => {
// navigated to a different route in router guard
const unregister = router.afterEach(async (to, from, next) => {
ssrContext.url = to.fullPath
app.context.route = await getRouteData(to)
app.context.params = to.params || {}
app.context.query = to.query || {}
unregister()
resolve()
})
})
})
}
return {
app,
router,
}
}
export { createApp, NuxtError }
<template>
<nuxt/>
</template>
<style>
body, html, #__nuxt {
background-color: white;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
padding: 0;
}
.spinner {
width: 40px;
height: 40px;
margin: 100px auto;
background-color: #dbe1ec;
border-radius: 100%;
-webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
animation: sk-scaleout 1.0s infinite ease-in-out;
}
@-webkit-keyframes sk-scaleout {
0% { -webkit-transform: scale(0) }
100% {
-webkit-transform: scale(1.0);
opacity: 0;
}
}
@keyframes sk-scaleout {
0% {
-webkit-transform: scale(0);
transform: scale(0);
} 100% {
-webkit-transform: scale(1.0);
transform: scale(1.0);
opacity: 0;
}
}
</style>
<div class="spinner">
<div class="double-bounce1"></div>
<div class="double-bounce2"></div>
</div>
<!-- http://tobiasahlin.com/spinkit -->
export default {}
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const _ac9093f6 = () => import('../pages/index.vue' /* webpackChunkName: "pages/index" */).then(m => m.default || m)
if (process.client) {
window.history.scrollRestoration = 'manual'
}
const scrollBehavior = function (to, from, savedPosition) {
// if the returned position is falsy or an empty object,
// will retain current scroll position.
let position = false
// if no children detected
if (to.matched.length < 2) {
// scroll to the top of the page
position = { x: 0, y: 0 }
} else if (to.matched.some((r) => r.components.default.options.scrollToTop)) {
// if one of the children has scrollToTop option set to true
position = { x: 0, y: 0 }
}
// savedPosition is only available for popstate navigations (back button)
if (savedPosition) {
position = savedPosition
}
return new Promise(resolve => {
// wait for the out transition to complete (if necessary)
window.$nuxt.$once('triggerScroll', () => {
// coords will be used if no selector is provided,
// or if the selector didn't match any element.
if (to.hash && document.querySelector(to.hash)) {
// scroll to anchor by returning the selector
position = { selector: to.hash }
}
resolve(position)
})
})
}
export function createRouter () {
return new Router({
mode: 'history',
base: '/',
linkActiveClass: 'nuxt-link-active',
linkExactActiveClass: 'nuxt-link-exact-active',
scrollBehavior,
routes: [
{
path: "/",
component: _ac9093f6,
name: "index"
}
],
fallback: false
})
}
import Vue from 'vue'
import clone from 'clone'
import { stringify } from 'querystring'
import { omit } from 'lodash'
import middleware from './middleware'
import { createApp, NuxtError } from './index'
import { applyAsyncData, sanitizeComponent, getMatchedComponents, getContext, middlewareSeries, promisify, urlJoin } from './utils'
const debug = require('debug')('nuxt:render')
debug.color = 4 // force blue color
const isDev = true
const noopApp = () => new Vue({ render: (h) => h('div') })
const createNext = ssrContext => opts => {
ssrContext.redirected = opts
// If nuxt generate
if (!ssrContext.res) {
ssrContext.nuxt.serverRendered = false
return
}
opts.query = stringify(opts.query)
opts.path = opts.path + (opts.query ? '?' + opts.query : '')
if (opts.path.indexOf('http') !== 0 && ('/' !== '/' && opts.path.indexOf('/') !== 0)) {
opts.path = urlJoin('/', opts.path)
}
// Avoid loop redirect
if (opts.path === ssrContext.url) {
ssrContext.redirected = false
return
}
ssrContext.res.writeHead(opts.status, {
'Location': opts.path
})
ssrContext.res.end()
}
// This exported function will be called by `bundleRenderer`.
// This is where we perform data-prefetching to determine the
// state of our application before actually rendering it.
// Since data fetching is async, this function is expected to
// return a Promise that resolves to the app instance.
export default async ssrContext => {
// Create ssrContext.next for simulate next() of beforeEach() when wanted to redirect
ssrContext.redirected = false
ssrContext.next = createNext(ssrContext)
// Used for beforeNuxtRender({ Components, nuxtState })
ssrContext.beforeRenderFns = []
// Nuxt object (window.__NUXT__)
ssrContext.nuxt = { layout: 'default', data: [], error: null, serverRendered: true }
// Create the app definition and the instance (created for each request)
const { app, router } = await createApp(ssrContext)
const _app = new Vue(app)
// Add meta infos (used in renderer.js)
ssrContext.meta = _app.$meta()
// Keep asyncData for each matched component in ssrContext (used in app/utils.js via this.$ssrContext)
ssrContext.asyncData = {}
const beforeRender = async () => {
// Call beforeNuxtRender() methods
await Promise.all(ssrContext.beforeRenderFns.map((fn) => promisify(fn, { Components, nuxtState: ssrContext.nuxt })))
}
const renderErrorPage = async () => {
// Load layout for error page
let errLayout = (typeof NuxtError.layout === 'function' ? NuxtError.layout(app.context) : NuxtError.layout)
ssrContext.nuxt.layout = errLayout || 'default'
await _app.loadLayout(errLayout)
_app.setLayout(errLayout)
await beforeRender()
return _app
}
const render404Page = () => {
app.context.error({ statusCode: 404, path: ssrContext.url, message: 'This page could not be found' })
return renderErrorPage()
}
const s = isDev && Date.now()
// Components are already resolved by setContext -> getRouteData (app/utils.js)
const Components = getMatchedComponents(router.match(ssrContext.url))
/*
** Call global middleware (nuxt.config.js)
*/
let midd = []
midd = midd.map((name) => {
if (typeof name === 'function') return name
if (typeof middleware[name] !== 'function') {
app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
}
return middleware[name]
})
await middlewareSeries(midd, app.context)
// ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp()
if (ssrContext.nuxt.error) return renderErrorPage()
/*
** Set layout
*/
let layout = Components.length ? Components[0].options.layout : NuxtError.layout
if (typeof layout === 'function') layout = layout(app.context)
await _app.loadLayout(layout)
layout = _app.setLayout(layout)
// ...Set layout to __NUXT__
ssrContext.nuxt.layout = _app.layoutName
/*
** Call middleware (layout + pages)
*/
midd = []
if (layout.middleware) midd = midd.concat(layout.middleware)
Components.forEach((Component) => {
if (Component.options.middleware) {
midd = midd.concat(Component.options.middleware)
}
})
midd = midd.map((name) => {
if (typeof name === 'function') return name
if (typeof middleware[name] !== 'function') {
app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
}
return middleware[name]
})
await middlewareSeries(midd, app.context)
// ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp()
if (ssrContext.nuxt.error) return renderErrorPage()
/*
** Call .validate()
*/
let isValid = true
Components.forEach((Component) => {
if (!isValid) return
if (typeof Component.options.validate !== 'function') return
isValid = Component.options.validate({
params: app.context.route.params || {},
query: app.context.route.query || {},
})
})
// ...If .validate() returned false
if (!isValid) {
// Don't server-render the page in generate mode
if (ssrContext._generate) ssrContext.nuxt.serverRendered = false
// Render a 404 error page
return render404Page()
}
// If no Components found, returns 404
if (!Components.length) return render404Page()
// Call asyncData & fetch hooks on components matched by the route.
let asyncDatas = await Promise.all(Components.map(Component => {
let promises = []
// Call asyncData(context)
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
let promise = promisify(Component.options.asyncData, app.context)
promise.then(asyncDataResult => {
ssrContext.asyncData[Component.cid] = asyncDataResult
applyAsyncData(Component)
return asyncDataResult
})
promises.push(promise)
} else {
promises.push(null)
}
// Call fetch(context)
if (Component.options.fetch) {
promises.push(Component.options.fetch(app.context))
}
else {
promises.push(null)
}
return Promise.all(promises)
}))
if (asyncDatas.length) debug('Data fetching ' + ssrContext.url + ': ' + (Date.now() - s) + 'ms')
// datas are the first row of each
ssrContext.nuxt.data = asyncDatas.map(r => r[0] || {})
// ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp()
if (ssrContext.nuxt.error) return renderErrorPage()
// Call beforeNuxtRender methods & add store state
await beforeRender()
return _app
}
This diff is collapsed.
<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
<head>
{{ HEAD }}
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Server error</title>
<meta charset="utf-8">
<meta content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name=viewport>
<style>
.__nuxt-error-page{padding: 1rem;background:#f7f8fb;color:#47494e;text-align:center;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;font-family:sans-serif;font-weight:100!important;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;-webkit-font-smoothing:antialiased;position:absolute;top:0;left:0;right:0;bottom:0}.__nuxt-error-page .error{max-width:450px}.__nuxt-error-page .title{font-size:24px;font-size:1.5rem;margin-top:15px;color:#47494e;margin-bottom:8px}.__nuxt-error-page .description{color:#7f828b;line-height:21px;margin-bottom:10px}.__nuxt-error-page a{color:#7f828b!important;text-decoration:none}.__nuxt-error-page .logo{position:fixed;left:12px;bottom:12px}
</style>
</head>
<body>
<div class="__nuxt-error-page">
<div class="error">
<svg xmlns="http://www.w3.org/2000/svg" width="90" height="90" fill="#DBE1EC" viewBox="0 0 48 48"><path d="M22 30h4v4h-4zm0-16h4v12h-4zm1.99-10C12.94 4 4 12.95 4 24s8.94 20 19.99 20S44 35.05 44 24 35.04 4 23.99 4zM24 40c-8.84 0-16-7.16-16-16S15.16 8 24 8s16 7.16 16 16-7.16 16-16 16z"/></svg>
<div class="title">Server error</div>
<div class="description">{{ message }}</div>
</div>
<div class="logo">
<a href="https://nuxtjs.org" target="_blank" rel="noopener">Nuxt.js</a>
</div>
</div>
</body>
</html>
const path = require('path')
module.exports = {
loading: {
color: '#92D3CE'
},
rootDir: path.resolve(__dirname),
dev: process.env.NODE_ENV !== 'production'
}
This diff is collapsed.
......@@ -3,7 +3,7 @@
"description": "ActivityPub implementation for federated personal web sites.",
"version": "0.0.0",
"homepage": "https://indienet.info",
"main": "src",
"main": "server",
"keywords": [
"feathers"
],
......@@ -14,7 +14,7 @@
"contributors": [],
"bugs": {},
"directories": {
"lib": "src",
"lib": "server",
"test": "test/"
},
"engines": {
......@@ -22,9 +22,11 @@
"npm": ">= 3.0.0"
},
"scripts": {
"build": "nuxt build",
"dev": "DEBUG=nuxt:* nodemon --watch server/ --watch config/ server/index.js",
"prestart": "npm run build",
"start": "NODE_ENV=production node server/",
"test": "npm run -s mocha",
"eslint": "eslint src/. test/. --config .eslintrc.json",
"start": "nodemon src/",
"mocha": "mocha test/ --recursive --exit"
},
"dependencies": {
......@@ -36,6 +38,7 @@
"compression": "^1.7.1",
"cors": "^2.8.4",
"helmet": "^3.9.0",
"nuxt": "^1.3.0",
"serve-favicon": "^2.4.5",
"winston": "^2.4.0",
"ws": "^4.0.0"
......@@ -44,6 +47,7 @@
"eslint": "^4.16.0",
"log-suppress": "^1.0.3",
"mocha": "^4.0.1",
"nodemon": "^1.14.12",
"request": "^2.83.0",
"request-promise": "^4.2.2",
"standard": "^10.0.3"
......
<template>
<div>
<h1>Indie Site</h1>
<p>Welcome.</p>
</div>
</template>
......@@ -28,7 +28,7 @@ app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(favicon(path.join(app.get('public'), 'favicon.ico')))
// Host the public folder
app.use('/', express.static(app.get('public')))
// app.use('/', express.static(app.get('public')))
// Set up Plugins and providers
app.configure(express.rest())
......
......@@ -2,12 +2,19 @@
const logger = require('winston')
const app = require('./app')
const port = app.get('port')
const server = app.listen(port)
process.on('unhandledRejection', (reason, p) =>
logger.error('Unhandled Rejection at: Promise ', p, reason)
)
server.on('listening', () =>
logger.info('Feathers application started on http://%s:%d', app.get('host'), port)
)
// Once Nuxt is done rendering the clinet, start the FeathersJS Server.
process.on('nuxt:build:done', (err) => {
if (err) {
logger.error(err)
}
const server = app.listen(port)
server.on('listening', () => {
logger.info(`Feathers application started on ${app.get('host')}:${port}`)
})
})
// @ts-check
// Nuxt
const { render } = require('./nuxt')
// ActivityPub
const activity = require('../lib/activity.js')
// Setup logger.
......@@ -8,12 +13,13 @@ if (process.env.NODE_ENV === 'test') {
winston.remove(winston.transports.Console)
}
module.exports = function (app) { // eslint-disable-line no-unused-vars
module.exports = function (app) {
// Custom Express middleware. The order matters
// Content types enumeration.
const ContentType = Object.freeze({
HTML: 'text/html',
JSON: 'application/json',
ActivityPub: 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
AlternateActivityPub: 'application/activity+json'
})
......@@ -25,13 +31,35 @@ module.exports = function (app) { // eslint-disable-line no-unused-vars
InternalServerError: 500
})
//
// Nuxt
//
// Use Nuxt's render middleware
app.use((request, response, next) => {
// Nuxt is greedy and will try to render all types of routes, not just HTML.
// Prevent it from rendering the ones that Express and Feathers should be handling.
switch (request.accepts(ContentType.HTML, ContentType.JSON, ContentType.ActivityPub, ContentType.AlternateActivityPub)) {
case ContentType.JSON:
case ContentType.ActivityPub:
case ContentType.AlternateActivityPub: {
next()
break
}
default: {
render(request, response, next)
}
}
})
//
// ActivityPub
//
// Feathers does not support unnamed services so that currently precludes
// having a service serve the root GET to return the Actor object for.
// having a service to serve the root GET to return the Actor object for.
// (See https://github.com/feathersjs/feathers/issues/728#issuecomment-355295764)
app.get('/', function (request, response, next) {
//
// Content negotiation
//
// ActivityPub response (return Actor object for the site owner).
const activityPub = () => {
......@@ -45,30 +73,11 @@ module.exports = function (app) { // eslint-disable-line no-unused-vars
response.end(ownerActorJSON)
}
// HTML response (return placeholder client page).
const html = () => {
response.status(HTTPStatusCode.OK)
// TODO: Serve the client.
response.end(`
<!doctype html>
<meta charset='utf-8'>
<title>Your site</title>
<style>html { font-family: sans-serif; }</style>
<h1>Welcome to your federated personal web site</h1>
<p>TODO: Create client.</p>
`)
}
response.format({
// Web client index.
[ContentType.HTML]: html,
// ActivityPub has two valid content types. (§7, w3.org/TR/activitypub).
[ContentType.ActivityPub]: activityPub,
[ContentType.AlternateActivityPub]: activityPub
})
})
}
const { Nuxt, Builder } = require('nuxt')
const logger = require('winston')
const config = require('../../nuxt.config')
const nuxt = new Nuxt(config)
if (config.dev) {
new Builder(nuxt).build()
.then(() => process.emit('nuxt:build:done'))
.catch((error) => {
logger.error(error)
process.exit(1)
})
} else {
process.nextTick(() => process.emit('nuxt:build:done'))
}
module.exports = nuxt
......@@ -6,7 +6,7 @@ process.env.NODE_ENV = 'test'
const assert = require('assert')
const request = require('request-promise')
const url = require('url')
const app = require('../src/app')
const app = require('../server/app')
//
// Helpers
......