From 6930e69b551b2e8ec1c125ecbf386c4536da86c4 Mon Sep 17 00:00:00 2001 From: advplyr Date: Tue, 17 Aug 2021 17:01:11 -0500 Subject: [PATCH 001/140] Init --- .dockerignore | 9 + .gitignore | 6 + Dockerfile | 26 + client/.nuxt/App.js | 213 + client/.nuxt/axios.js | 193 + client/.nuxt/client.js | 817 + client/.nuxt/components/index.js | 49 + .../.nuxt/components/nuxt-build-indicator.vue | 143 + client/.nuxt/components/nuxt-child.js | 122 + client/.nuxt/components/nuxt-error.vue | 98 + client/.nuxt/components/nuxt-link.client.js | 98 + client/.nuxt/components/nuxt-link.server.js | 16 + client/.nuxt/components/nuxt-loading.vue | 177 + client/.nuxt/components/nuxt.js | 101 + client/.nuxt/components/plugin.js | 33 + client/.nuxt/components/readme.md | 31 + client/.nuxt/components/utils.js | 30 + client/.nuxt/empty.js | 1 + client/.nuxt/index.js | 279 + client/.nuxt/jsonp.js | 82 + client/.nuxt/loading.html | 110 + client/.nuxt/middleware.js | 3 + client/.nuxt/mixins/fetch.client.js | 90 + client/.nuxt/mixins/fetch.server.js | 69 + client/.nuxt/nuxt-socket-io.js | 1083 ++ client/.nuxt/router.js | 68 + client/.nuxt/router.scrollBehavior.js | 76 + client/.nuxt/routes.json | 37 + client/.nuxt/server.js | 312 + client/.nuxt/store.js | 146 + client/.nuxt/utils.js | 630 + client/.nuxt/vetur/tags.json | 71 + client/.nuxt/views/app.template.html | 9 + client/.nuxt/views/error.html | 23 + client/assets/app.css | 52 + client/assets/transitions.css | 47 + client/components/AudioPlayer.vue | 435 + client/components/app/Appbar.vue | 88 + client/components/app/BookShelf.vue | 102 + client/components/app/StreamContainer.vue | 142 + client/components/app/TracksTable.vue | 67 + client/components/cards/BookCard.vue | 110 + client/components/cards/BookCover.vue | 72 + client/components/controls/VolumeControl.vue | 89 + client/components/modals/EditModal.vue | 86 + client/components/modals/Modal.vue | 100 + client/components/modals/edit-tabs/Cover.vue | 42 + .../components/modals/edit-tabs/Details.vue | 135 + client/components/modals/edit-tabs/Match.vue | 100 + client/components/modals/edit-tabs/Tracks.vue | 66 + client/components/ui/Btn.vue | 67 + client/components/ui/LoadingIndicator.vue | 70 + client/components/ui/Menu.vue | 54 + client/components/ui/TextInput.vue | 47 + client/components/ui/TextInputWithLabel.vue | 31 + client/components/ui/TextareaInput.vue | 47 + client/components/ui/TextareaWithLabel.vue | 34 + client/components/ui/Tooltip.vue | 55 + client/components/widgets/ScanAlert.vue | 37 + client/layouts/blank.vue | 9 + client/layouts/default.vue | 150 + client/nuxt.config.js | 103 + client/package-lock.json | 14255 ++++++++++++++++ client/package.json | 28 + client/pages/audiobook/_id/edit.vue | 222 + client/pages/audiobook/_id/index.vue | 220 + client/pages/config/index.vue | 32 + client/pages/index.vue | 21 + client/pages/login.vue | 108 + client/plugins/axios.js | 19 + client/plugins/init.client.js | 120 + client/plugins/toast.js | 11 + client/static/Logo.png | Bin 0 -> 70893 bytes client/static/LogoTransparent.png | Bin 0 -> 75634 bytes client/static/book_placeholder.jpg | Bin 0 -> 107910 bytes client/static/favicon.ico | Bin 0 -> 3227 bytes client/static/wood_panels.jpg | Bin 0 -> 116707 bytes client/store/audiobooks.js | 67 + client/store/index.js | 63 + client/tailwind.config.js | 41 + index.js | 24 + package-lock.json | 1106 ++ package.json | 26 + server/ApiController.js | 143 + server/AudioTrack.js | 96 + server/Audiobook.js | 212 + server/Auth.js | 192 + server/Book.js | 72 + server/BookFinder.js | 33 + server/Db.js | 158 + server/HlsController.js | 90 + server/Logger.js | 50 + server/Scanner.js | 90 + server/Server.js | 241 + server/Stream.js | 497 + server/StreamManager.js | 118 + server/User.js | 75 + server/Watcher.js | 71 + server/providers/LibGen.js | 44 + server/providers/OpenLibrary.js | 72 + server/streamTest.js | 112 + server/utils/audioFileScanner.js | 180 + server/utils/fileUtils.js | 58 + server/utils/hlsPlaylistGenerator.js | 30 + server/utils/prober.js | 168 + server/utils/scandir.js | 72 + 106 files changed, 26925 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 client/.nuxt/App.js create mode 100644 client/.nuxt/axios.js create mode 100644 client/.nuxt/client.js create mode 100644 client/.nuxt/components/index.js create mode 100644 client/.nuxt/components/nuxt-build-indicator.vue create mode 100644 client/.nuxt/components/nuxt-child.js create mode 100644 client/.nuxt/components/nuxt-error.vue create mode 100644 client/.nuxt/components/nuxt-link.client.js create mode 100644 client/.nuxt/components/nuxt-link.server.js create mode 100644 client/.nuxt/components/nuxt-loading.vue create mode 100644 client/.nuxt/components/nuxt.js create mode 100644 client/.nuxt/components/plugin.js create mode 100644 client/.nuxt/components/readme.md create mode 100644 client/.nuxt/components/utils.js create mode 100644 client/.nuxt/empty.js create mode 100644 client/.nuxt/index.js create mode 100644 client/.nuxt/jsonp.js create mode 100644 client/.nuxt/loading.html create mode 100644 client/.nuxt/middleware.js create mode 100644 client/.nuxt/mixins/fetch.client.js create mode 100644 client/.nuxt/mixins/fetch.server.js create mode 100644 client/.nuxt/nuxt-socket-io.js create mode 100644 client/.nuxt/router.js create mode 100644 client/.nuxt/router.scrollBehavior.js create mode 100644 client/.nuxt/routes.json create mode 100644 client/.nuxt/server.js create mode 100644 client/.nuxt/store.js create mode 100644 client/.nuxt/utils.js create mode 100644 client/.nuxt/vetur/tags.json create mode 100644 client/.nuxt/views/app.template.html create mode 100644 client/.nuxt/views/error.html create mode 100644 client/assets/app.css create mode 100644 client/assets/transitions.css create mode 100644 client/components/AudioPlayer.vue create mode 100644 client/components/app/Appbar.vue create mode 100644 client/components/app/BookShelf.vue create mode 100644 client/components/app/StreamContainer.vue create mode 100644 client/components/app/TracksTable.vue create mode 100644 client/components/cards/BookCard.vue create mode 100644 client/components/cards/BookCover.vue create mode 100644 client/components/controls/VolumeControl.vue create mode 100644 client/components/modals/EditModal.vue create mode 100644 client/components/modals/Modal.vue create mode 100644 client/components/modals/edit-tabs/Cover.vue create mode 100644 client/components/modals/edit-tabs/Details.vue create mode 100644 client/components/modals/edit-tabs/Match.vue create mode 100644 client/components/modals/edit-tabs/Tracks.vue create mode 100644 client/components/ui/Btn.vue create mode 100644 client/components/ui/LoadingIndicator.vue create mode 100644 client/components/ui/Menu.vue create mode 100644 client/components/ui/TextInput.vue create mode 100644 client/components/ui/TextInputWithLabel.vue create mode 100644 client/components/ui/TextareaInput.vue create mode 100644 client/components/ui/TextareaWithLabel.vue create mode 100644 client/components/ui/Tooltip.vue create mode 100644 client/components/widgets/ScanAlert.vue create mode 100644 client/layouts/blank.vue create mode 100644 client/layouts/default.vue create mode 100644 client/nuxt.config.js create mode 100644 client/package-lock.json create mode 100644 client/package.json create mode 100644 client/pages/audiobook/_id/edit.vue create mode 100644 client/pages/audiobook/_id/index.vue create mode 100644 client/pages/config/index.vue create mode 100644 client/pages/index.vue create mode 100644 client/pages/login.vue create mode 100644 client/plugins/axios.js create mode 100644 client/plugins/init.client.js create mode 100644 client/plugins/toast.js create mode 100644 client/static/Logo.png create mode 100644 client/static/LogoTransparent.png create mode 100644 client/static/book_placeholder.jpg create mode 100644 client/static/favicon.ico create mode 100644 client/static/wood_panels.jpg create mode 100644 client/store/audiobooks.js create mode 100644 client/store/index.js create mode 100644 client/tailwind.config.js create mode 100644 index.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 server/ApiController.js create mode 100644 server/AudioTrack.js create mode 100644 server/Audiobook.js create mode 100644 server/Auth.js create mode 100644 server/Book.js create mode 100644 server/BookFinder.js create mode 100644 server/Db.js create mode 100644 server/HlsController.js create mode 100644 server/Logger.js create mode 100644 server/Scanner.js create mode 100644 server/Server.js create mode 100644 server/Stream.js create mode 100644 server/StreamManager.js create mode 100644 server/User.js create mode 100644 server/Watcher.js create mode 100644 server/providers/LibGen.js create mode 100644 server/providers/OpenLibrary.js create mode 100644 server/streamTest.js create mode 100644 server/utils/audioFileScanner.js create mode 100644 server/utils/fileUtils.js create mode 100644 server/utils/hlsPlaylistGenerator.js create mode 100644 server/utils/prober.js create mode 100644 server/utils/scandir.js diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..2483224c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +node_modules +npm-debug.log +.git +.gitignore +/config +/audiobooks +/metadata +dev.js +/test/ \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..0e030fac --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +dev.js +node_modules/ +/config/ +/audiobooks/ +/metadata/ +/test/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..84d2d0e5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +### STAGE 0: FFMPEG ### +FROM jrottenberg/ffmpeg:4.1-alpine AS ffmpeg +# FROM alfg/ffmpeg AS ffmpeg + +### STAGE 1: Build client ### +FROM node:12-alpine AS build +WORKDIR /client +COPY /client /client +RUN npm install +RUN npm run generate + +### STAGE 2: Build server ### +FROM node:12-alpine +# RUN apk add --no-cache ffmpeg +# RUN apt-get install -y ffmpeg +ENV NODE_ENV=production +ENV LOG_LEVEL=INFO +COPY --from=build /client/dist /client/dist +COPY --from=ffmpeg / / +COPY index.js index.js +COPY package.json package.json +COPY server server +RUN npm install --production +EXPOSE 80 +# CMD ["node", "index.js"] +CMD ["npm", "start"] diff --git a/client/.nuxt/App.js b/client/.nuxt/App.js new file mode 100644 index 00000000..d5c7ff12 --- /dev/null +++ b/client/.nuxt/App.js @@ -0,0 +1,213 @@ +import Vue from 'vue' +import { decode, parsePath, withoutBase, withoutTrailingSlash, normalizeURL } from 'ufo' + +import { getMatchedComponentsInstances, getChildrenComponentInstancesUsingFetch, promisify, globalHandleError, urlJoin, sanitizeComponent } from './utils' +import NuxtError from './components/nuxt-error.vue' +import NuxtLoading from './components/nuxt-loading.vue' +import NuxtBuildIndicator from './components/nuxt-build-indicator' + +import '..\\node_modules\\@nuxtjs\\tailwindcss\\dist\\runtime\\tailwind.css' + +import '..\\assets\\app.css' + +import _77180f1e from '..\\layouts\\blank.vue' +import _6f6c098b from '..\\layouts\\default.vue' + +const layouts = { "_blank": sanitizeComponent(_77180f1e),"_default": sanitizeComponent(_6f6c098b) } + +export default { + render (h, props) { + const loadingEl = h('NuxtLoading', { 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' + }, + on: { + beforeEnter (el) { + // Ensure to trigger scroll event after calling scrollBehavior + window.$nuxt.$nextTick(() => { + window.$nuxt.$emit('triggerScroll') + }) + } + } + }, [templateEl]) + + return h('div', { + domProps: { + id: '__nuxt' + } + }, [ + loadingEl, + h(NuxtBuildIndicator), + transitionEl + ]) + }, + + data: () => ({ + isOnline: true, + + layout: null, + layoutName: '', + + nbFetching: 0 + }), + + beforeCreate () { + Vue.util.defineReactive(this, 'nuxt', this.$options.nuxt) + }, + created () { + // Add this.$nuxt in child instances + this.$root.$options.$nuxt = this + + if (process.client) { + // add to window so we can listen when ready + window.$nuxt = this + + this.refreshOnlineStatus() + // Setup the listeners + window.addEventListener('online', this.refreshOnlineStatus) + window.addEventListener('offline', this.refreshOnlineStatus) + } + // Add $nuxt.error() + this.error = this.nuxt.error + // Add $nuxt.context + this.context = this.$options.context + }, + + async mounted () { + this.$loading = this.$refs.loading + }, + + watch: { + 'nuxt.err': 'errorChanged' + }, + + computed: { + isOffline () { + return !this.isOnline + }, + + isFetching () { + return this.nbFetching > 0 + }, + + isPreview () { + return Boolean(this.$options.previewData) + }, + }, + + methods: { + refreshOnlineStatus () { + if (process.client) { + if (typeof window.navigator.onLine === 'undefined') { + // If the browser doesn't support connection status reports + // assume that we are online because most apps' only react + // when they now that the connection has been interrupted + this.isOnline = true + } else { + this.isOnline = window.navigator.onLine + } + } + }, + + async refresh () { + const pages = getMatchedComponentsInstances(this.$route) + + if (!pages.length) { + return + } + this.$loading.start() + + const promises = pages.map((page) => { + const p = [] + + // Old fetch + if (page.$options.fetch && page.$options.fetch.length) { + p.push(promisify(page.$options.fetch, this.context)) + } + if (page.$fetch) { + p.push(page.$fetch()) + } else { + // Get all component instance to call $fetch + for (const component of getChildrenComponentInstancesUsingFetch(page.$vnode.componentInstance)) { + p.push(component.$fetch()) + } + } + + if (page.$options.asyncData) { + p.push( + promisify(page.$options.asyncData, this.context) + .then((newData) => { + for (const key in newData) { + Vue.set(page.$data, key, newData[key]) + } + }) + ) + } + + return Promise.all(p) + }) + try { + await Promise.all(promises) + } catch (error) { + this.$loading.fail(error) + globalHandleError(error) + this.error(error) + } + this.$loading.finish() + }, + errorChanged () { + if (this.nuxt.err) { + if (this.$loading) { + if (this.$loading.fail) { + this.$loading.fail(this.nuxt.err) + } + if (this.$loading.finish) { + this.$loading.finish() + } + } + + let errorLayout = (NuxtError.options || NuxtError).layout; + + if (typeof errorLayout === 'function') { + errorLayout = errorLayout(this.context) + } + + this.setLayout(errorLayout) + } + }, + + setLayout (layout) { + if(layout && typeof layout !== 'string') { + throw new Error('[nuxt] Avoid using non-string value as layout property.') + } + + if (!layout || !layouts['_' + layout]) { + layout = 'default' + } + this.layoutName = layout + this.layout = layouts['_' + layout] + return this.layout + }, + loadLayout (layout) { + if (!layout || !layouts['_' + layout]) { + layout = 'default' + } + return Promise.resolve(layouts['_' + layout]) + }, + }, + + components: { + NuxtLoading + } +} diff --git a/client/.nuxt/axios.js b/client/.nuxt/axios.js new file mode 100644 index 00000000..abae59c1 --- /dev/null +++ b/client/.nuxt/axios.js @@ -0,0 +1,193 @@ +import Axios from 'axios' +import defu from 'defu' + +// Axios.prototype cannot be modified +const axiosExtra = { + setBaseURL (baseURL) { + this.defaults.baseURL = baseURL + }, + setHeader (name, value, scopes = 'common') { + for (const scope of Array.isArray(scopes) ? scopes : [ scopes ]) { + if (!value) { + delete this.defaults.headers[scope][name]; + continue + } + this.defaults.headers[scope][name] = value + } + }, + setToken (token, type, scopes = 'common') { + const value = !token ? null : (type ? type + ' ' : '') + token + this.setHeader('Authorization', value, scopes) + }, + onRequest(fn) { + this.interceptors.request.use(config => fn(config) || config) + }, + onResponse(fn) { + this.interceptors.response.use(response => fn(response) || response) + }, + onRequestError(fn) { + this.interceptors.request.use(undefined, error => fn(error) || Promise.reject(error)) + }, + onResponseError(fn) { + this.interceptors.response.use(undefined, error => fn(error) || Promise.reject(error)) + }, + onError(fn) { + this.onRequestError(fn) + this.onResponseError(fn) + }, + create(options) { + return createAxiosInstance(defu(options, this.defaults)) + } +} + +// Request helpers ($get, $post, ...) +for (const method of ['request', 'delete', 'get', 'head', 'options', 'post', 'put', 'patch']) { + axiosExtra['$' + method] = function () { return this[method].apply(this, arguments).then(res => res && res.data) } +} + +const extendAxiosInstance = axios => { + for (const key in axiosExtra) { + axios[key] = axiosExtra[key].bind(axios) + } +} + +const createAxiosInstance = axiosOptions => { + // Create new axios instance + const axios = Axios.create(axiosOptions) + axios.CancelToken = Axios.CancelToken + axios.isCancel = Axios.isCancel + + // Extend axios proto + extendAxiosInstance(axios) + + // Intercept to apply default headers + axios.onRequest((config) => { + config.headers = { ...axios.defaults.headers.common, ...config.headers } + }) + + // Setup interceptors + + setupProgress(axios) + + return axios +} + +const setupProgress = (axios) => { + if (process.server) { + return + } + + // A noop loading inteterface for when $nuxt is not yet ready + const noopLoading = { + finish: () => { }, + start: () => { }, + fail: () => { }, + set: () => { } + } + + const $loading = () => { + const $nuxt = typeof window !== 'undefined' && window['$nuxt'] + return ($nuxt && $nuxt.$loading && $nuxt.$loading.set) ? $nuxt.$loading : noopLoading + } + + let currentRequests = 0 + + axios.onRequest(config => { + if (config && config.progress === false) { + return + } + + currentRequests++ + }) + + axios.onResponse(response => { + if (response && response.config && response.config.progress === false) { + return + } + + currentRequests-- + if (currentRequests <= 0) { + currentRequests = 0 + $loading().finish() + } + }) + + axios.onError(error => { + if (error && error.config && error.config.progress === false) { + return + } + + currentRequests-- + + if (Axios.isCancel(error)) { + if (currentRequests <= 0) { + currentRequests = 0 + $loading().finish() + } + return + } + + $loading().fail() + $loading().finish() + }) + + const onProgress = e => { + if (!currentRequests || !e.total) { + return + } + const progress = ((e.loaded * 100) / (e.total * currentRequests)) + $loading().set(Math.min(100, progress)) + } + + axios.defaults.onUploadProgress = onProgress + axios.defaults.onDownloadProgress = onProgress +} + +export default (ctx, inject) => { + // runtimeConfig + const runtimeConfig = ctx.$config && ctx.$config.axios || {} + // baseURL + const baseURL = process.browser + ? (runtimeConfig.browserBaseURL || runtimeConfig.browserBaseUrl || runtimeConfig.baseURL || runtimeConfig.baseUrl || '') + : (runtimeConfig.baseURL || runtimeConfig.baseUrl || process.env._AXIOS_BASE_URL_ || '') + + // Create fresh objects for all default header scopes + // Axios creates only one which is shared across SSR requests! + // https://github.com/mzabriskie/axios/blob/master/lib/defaults.js + const headers = { + "common": { + "Accept": "application/json, text/plain, */*" + }, + "delete": {}, + "get": {}, + "head": {}, + "post": {}, + "put": {}, + "patch": {} +} + + const axiosOptions = { + baseURL, + headers + } + + // Proxy SSR request headers headers + if (process.server && ctx.req && ctx.req.headers) { + const reqHeaders = { ...ctx.req.headers } + for (const h of ["accept","cf-connecting-ip","cf-ray","content-length","content-md5","content-type","host","x-forwarded-host","x-forwarded-port","x-forwarded-proto"]) { + delete reqHeaders[h] + } + axiosOptions.headers.common = { ...reqHeaders, ...axiosOptions.headers.common } + } + + if (process.server) { + // Don't accept brotli encoding because Node can't parse it + axiosOptions.headers.common['accept-encoding'] = 'gzip, deflate' + } + + const axios = createAxiosInstance(axiosOptions) + + // Inject axios to the context as $axios + ctx.$axios = axios + inject('axios', axios) +} diff --git a/client/.nuxt/client.js b/client/.nuxt/client.js new file mode 100644 index 00000000..7b5440c1 --- /dev/null +++ b/client/.nuxt/client.js @@ -0,0 +1,817 @@ +import Vue from 'vue' +import fetch from 'unfetch' +import middleware from './middleware.js' +import { + applyAsyncData, + promisify, + middlewareSeries, + sanitizeComponent, + resolveRouteComponents, + getMatchedComponents, + getMatchedComponentsInstances, + flatMapComponents, + setContext, + getLocation, + compile, + getQueryDiff, + globalHandleError, + isSamePath, + urlJoin +} from './utils.js' +import { createApp, NuxtError } from './index.js' +import fetchMixin from './mixins/fetch.client' +import NuxtLink from './components/nuxt-link.client.js' // should be included after ./index.js + +// Fetch mixin +if (!Vue.__nuxt__fetch__mixin__) { + Vue.mixin(fetchMixin) + Vue.__nuxt__fetch__mixin__ = true +} + +// Component: +Vue.component(NuxtLink.name, NuxtLink) +Vue.component('NLink', NuxtLink) + +if (!global.fetch) { global.fetch = fetch } + +// Global shared references +let _lastPaths = [] +let app +let router +let store + +// Try to rehydrate SSR data from window +const NUXT = window.__NUXT__ || {} + +const $config = NUXT.config || {} +if ($config._app) { + __webpack_public_path__ = urlJoin($config._app.cdnURL, $config._app.assetsPath) +} + +Object.assign(Vue.config, {"silent":false,"performance":true}) + +const logs = NUXT.logs || [] + if (logs.length > 0) { + const ssrLogStyle = 'background: #2E495E;border-radius: 0.5em;color: white;font-weight: bold;padding: 2px 0.5em;' + console.group && console.group ('%cNuxt SSR', ssrLogStyle) + logs.forEach(logObj => (console[logObj.type] || console.log)(...logObj.args)) + delete NUXT.logs + console.groupEnd && console.groupEnd() +} + +// Setup global Vue error handler +if (!Vue.config.$nuxt) { + const defaultErrorHandler = Vue.config.errorHandler + Vue.config.errorHandler = async (err, vm, info, ...rest) => { + // Call other handler if exist + let handled = null + if (typeof defaultErrorHandler === 'function') { + handled = defaultErrorHandler(err, vm, info, ...rest) + } + if (handled === true) { + return handled + } + + if (vm && vm.$root) { + const nuxtApp = Object.keys(Vue.config.$nuxt) + .find(nuxtInstance => vm.$root[nuxtInstance]) + + // Show Nuxt Error Page + if (nuxtApp && vm.$root[nuxtApp].error && info !== 'render function') { + const currentApp = vm.$root[nuxtApp] + + // Load error layout + let layout = (NuxtError.options || NuxtError).layout + if (typeof layout === 'function') { + layout = layout(currentApp.context) + } + if (layout) { + await currentApp.loadLayout(layout).catch(() => {}) + } + currentApp.setLayout(layout) + + currentApp.error(err) + } + } + + if (typeof defaultErrorHandler === 'function') { + return handled + } + + // Log to console + if (process.env.NODE_ENV !== 'production') { + console.error(err) + } else { + console.error(err.message || err) + } + } + Vue.config.$nuxt = {} +} +Vue.config.$nuxt.$nuxt = true + +const errorHandler = Vue.config.errorHandler || console.error + +// Create and mount App +createApp(null, NUXT.config).then(mountApp).catch(errorHandler) + +function componentOption (component, key, ...args) { + if (!component || !component.options || !component.options[key]) { + return {} + } + const option = component.options[key] + if (typeof option === 'function') { + return option(...args) + } + return option +} + +function mapTransitions (toComponents, to, from) { + const componentTransitions = (component) => { + const transition = componentOption(component, 'transition', to, from) || {} + return (typeof transition === 'string' ? { name: transition } : transition) + } + + const fromComponents = from ? getMatchedComponents(from) : [] + const maxDepth = Math.max(toComponents.length, fromComponents.length) + + const mergedTransitions = [] + for (let i=0; i typeof toTransitions[key] !== 'undefined' && !key.toLowerCase().includes('leave')) + .forEach((key) => { transitions[key] = toTransitions[key] }) + + mergedTransitions.push(transitions) + } + return mergedTransitions +} + +async function loadAsyncComponents (to, from, next) { + // Check if route changed (this._routeChanged), only if the page is not an error (for validate()) + this._routeChanged = Boolean(app.nuxt.err) || from.name !== to.name + this._paramChanged = !this._routeChanged && from.path !== to.path + this._queryChanged = !this._paramChanged && from.fullPath !== to.fullPath + this._diffQuery = (this._queryChanged ? getQueryDiff(to.query, from.query) : []) + + if ((this._routeChanged || this._paramChanged) && this.$loading.start && !this.$loading.manual) { + this.$loading.start() + } + + try { + if (this._queryChanged) { + const Components = await resolveRouteComponents( + to, + (Component, instance) => ({ Component, instance }) + ) + // Add a marker on each component that it needs to refresh or not + const startLoader = Components.some(({ Component, instance }) => { + const watchQuery = Component.options.watchQuery + if (watchQuery === true) { + return true + } + if (Array.isArray(watchQuery)) { + return watchQuery.some(key => this._diffQuery[key]) + } + if (typeof watchQuery === 'function') { + return watchQuery.apply(instance, [to.query, from.query]) + } + return false + }) + + if (startLoader && this.$loading.start && !this.$loading.manual) { + this.$loading.start() + } + } + // Call next() + next() + } catch (error) { + const err = error || {} + const statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500 + const message = err.message || '' + + // Handle chunk loading errors + // This may be due to a new deployment or a network problem + if (/^Loading( CSS)? chunk (\d)+ failed\./.test(message)) { + window.location.reload(true /* skip cache */) + return // prevent error page blinking for user + } + + this.error({ statusCode, message }) + this.$nuxt.$emit('routeChanged', to, from, err) + next() + } +} + +function applySSRData (Component, ssrData) { + if (NUXT.serverRendered && ssrData) { + applyAsyncData(Component, ssrData) + } + + Component._Ctor = Component + return Component +} + +// Get matched components +function resolveComponents (route) { + return flatMapComponents(route, async (Component, _, match, key, index) => { + // If component is not resolved yet, resolve it + if (typeof Component === 'function' && !Component.options) { + Component = await Component() + } + // Sanitize it and save it + const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null) + match.components[key] = _Component + return _Component + }) +} + +function callMiddleware (Components, context, layout) { + let midd = [] + let unknownMiddleware = false + + // If layout is undefined, only call global middleware + if (typeof layout !== 'undefined') { + midd = [] // Exclude global middleware if layout defined (already called before) + layout = sanitizeComponent(layout) + if (layout.options.middleware) { + midd = midd.concat(layout.options.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') { + unknownMiddleware = true + this.error({ statusCode: 500, message: 'Unknown middleware ' + name }) + } + return middleware[name] + }) + + if (unknownMiddleware) { + return + } + return middlewareSeries(midd, context) +} + +async function render (to, from, next) { + if (this._routeChanged === false && this._paramChanged === false && this._queryChanged === false) { + return next() + } + // Handle first render on SPA mode + let spaFallback = false + if (to === from) { + _lastPaths = [] + spaFallback = true + } else { + const fromMatches = [] + _lastPaths = getMatchedComponents(from, fromMatches).map((Component, i) => { + return compile(from.matched[fromMatches[i]].path)(from.params) + }) + } + + // nextCalled is true when redirected + let nextCalled = false + const _next = (path) => { + if (from.path === path.path && this.$loading.finish) { + this.$loading.finish() + } + + if (from.path !== path.path && this.$loading.pause) { + this.$loading.pause() + } + + if (nextCalled) { + return + } + + nextCalled = true + next(path) + } + + // Update context + await setContext(app, { + route: to, + from, + next: _next.bind(this) + }) + this._dateLastError = app.nuxt.dateErr + this._hadError = Boolean(app.nuxt.err) + + // Get route's matched components + const matches = [] + const Components = getMatchedComponents(to, matches) + + // If no Components matched, generate 404 + if (!Components.length) { + // Default layout + await callMiddleware.call(this, Components, app.context) + if (nextCalled) { + return + } + + // Load layout for error page + const errorLayout = (NuxtError.options || NuxtError).layout + const layout = await this.loadLayout( + typeof errorLayout === 'function' + ? errorLayout.call(NuxtError, app.context) + : errorLayout + ) + + await callMiddleware.call(this, Components, app.context, layout) + if (nextCalled) { + return + } + + // Show error page + app.context.error({ statusCode: 404, message: 'This page could not be found' }) + return next() + } + + // Update ._data and other properties if hot reloaded + Components.forEach((Component) => { + if (Component._Ctor && Component._Ctor.options) { + Component.options.asyncData = Component._Ctor.options.asyncData + Component.options.fetch = Component._Ctor.options.fetch + } + }) + + // Apply transitions + this.setTransitions(mapTransitions(Components, to, from)) + + try { + // Call middleware + await callMiddleware.call(this, Components, app.context) + if (nextCalled) { + return + } + if (app.context._errored) { + return next() + } + + // Set layout + let layout = Components[0].options.layout + if (typeof layout === 'function') { + layout = layout(app.context) + } + layout = await this.loadLayout(layout) + + // Call middleware for layout + await callMiddleware.call(this, Components, app.context, layout) + if (nextCalled) { + return + } + if (app.context._errored) { + return next() + } + + // Call .validate() + let isValid = true + try { + for (const Component of Components) { + if (typeof Component.options.validate !== 'function') { + continue + } + + isValid = await Component.options.validate(app.context) + + if (!isValid) { + break + } + } + } catch (validationError) { + // ...If .validate() threw an error + this.error({ + statusCode: validationError.statusCode || '500', + message: validationError.message + }) + return next() + } + + // ...If .validate() returned false + if (!isValid) { + this.error({ statusCode: 404, message: 'This page could not be found' }) + return next() + } + + let instances + // Call asyncData & fetch hooks on components matched by the route. + await Promise.all(Components.map(async (Component, i) => { + // Check if only children route changed + Component._path = compile(to.matched[matches[i]].path)(to.params) + Component._dataRefresh = false + const childPathChanged = Component._path !== _lastPaths[i] + // Refresh component (call asyncData & fetch) when: + // Route path changed part includes current component + // Or route param changed part includes current component and watchParam is not `false` + // Or route query is changed and watchQuery returns `true` + if (this._routeChanged && childPathChanged) { + Component._dataRefresh = true + } else if (this._paramChanged && childPathChanged) { + const watchParam = Component.options.watchParam + Component._dataRefresh = watchParam !== false + } else if (this._queryChanged) { + const watchQuery = Component.options.watchQuery + if (watchQuery === true) { + Component._dataRefresh = true + } else if (Array.isArray(watchQuery)) { + Component._dataRefresh = watchQuery.some(key => this._diffQuery[key]) + } else if (typeof watchQuery === 'function') { + if (!instances) { + instances = getMatchedComponentsInstances(to) + } + Component._dataRefresh = watchQuery.apply(instances[i], [to.query, from.query]) + } + } + if (!this._hadError && this._isMounted && !Component._dataRefresh) { + return + } + + const promises = [] + + const hasAsyncData = ( + Component.options.asyncData && + typeof Component.options.asyncData === 'function' + ) + + const hasFetch = Boolean(Component.options.fetch) && Component.options.fetch.length + + const loadingIncrease = (hasAsyncData && hasFetch) ? 30 : 45 + + // Call asyncData(context) + if (hasAsyncData) { + const promise = promisify(Component.options.asyncData, app.context) + + promise.then((asyncDataResult) => { + applyAsyncData(Component, asyncDataResult) + + if (this.$loading.increase) { + this.$loading.increase(loadingIncrease) + } + }) + promises.push(promise) + } + + // Check disabled page loading + this.$loading.manual = Component.options.loading === false + + // Call fetch(context) + if (hasFetch) { + let p = Component.options.fetch(app.context) + if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) { + p = Promise.resolve(p) + } + p.then((fetchResult) => { + if (this.$loading.increase) { + this.$loading.increase(loadingIncrease) + } + }) + promises.push(p) + } + + return Promise.all(promises) + })) + + // If not redirected + if (!nextCalled) { + if (this.$loading.finish && !this.$loading.manual) { + this.$loading.finish() + } + + next() + } + } catch (err) { + const error = err || {} + if (error.message === 'ERR_REDIRECT') { + return this.$nuxt.$emit('routeChanged', to, from, error) + } + _lastPaths = [] + + globalHandleError(error) + + // Load error layout + let layout = (NuxtError.options || NuxtError).layout + if (typeof layout === 'function') { + layout = layout(app.context) + } + await this.loadLayout(layout) + + this.error(error) + this.$nuxt.$emit('routeChanged', to, from, error) + next() + } +} + +// Fix components format in matched, it's due to code-splitting of vue-router +function normalizeComponents (to, ___) { + flatMapComponents(to, (Component, _, match, key) => { + if (typeof Component === 'object' && !Component.options) { + // Updated via vue-router resolveAsyncComponents() + Component = Vue.extend(Component) + Component._Ctor = Component + match.components[key] = Component + } + return Component + }) +} + +function setLayoutForNextPage (to) { + // Set layout + let hasError = Boolean(this.$options.nuxt.err) + if (this._hadError && this._dateLastError === this.$options.nuxt.dateErr) { + hasError = false + } + let layout = hasError + ? (NuxtError.options || NuxtError).layout + : to.matched[0].components.default.options.layout + + if (typeof layout === 'function') { + layout = layout(app.context) + } + + this.setLayout(layout) +} + +function checkForErrors (app) { + // Hide error component if no error + if (app._hadError && app._dateLastError === app.$options.nuxt.dateErr) { + app.error() + } +} + +// When navigating on a different route but the same component is used, Vue.js +// Will not update the instance data, so we have to update $data ourselves +function fixPrepatch (to, ___) { + if (this._routeChanged === false && this._paramChanged === false && this._queryChanged === false) { + return + } + + const instances = getMatchedComponentsInstances(to) + const Components = getMatchedComponents(to) + + let triggerScroll = false + + Vue.nextTick(() => { + instances.forEach((instance, i) => { + if (!instance || instance._isDestroyed) { + return + } + + if ( + instance.constructor._dataRefresh && + Components[i] === instance.constructor && + instance.$vnode.data.keepAlive !== true && + typeof instance.constructor.options.data === 'function' + ) { + const newData = instance.constructor.options.data.call(instance) + for (const key in newData) { + Vue.set(instance.$data, key, newData[key]) + } + + triggerScroll = true + } + }) + + if (triggerScroll) { + // Ensure to trigger scroll event after calling scrollBehavior + window.$nuxt.$nextTick(() => { + window.$nuxt.$emit('triggerScroll') + }) + } + + checkForErrors(this) + + // Hot reloading + setTimeout(() => hotReloadAPI(this), 100) + }) +} + +function nuxtReady (_app) { + window.onNuxtReadyCbs.forEach((cb) => { + if (typeof cb === 'function') { + cb(_app) + } + }) + // Special JSDOM + if (typeof window._onNuxtLoaded === 'function') { + window._onNuxtLoaded(_app) + } + // Add router hooks + router.afterEach((to, from) => { + // Wait for fixPrepatch + $data updates + Vue.nextTick(() => _app.$nuxt.$emit('routeChanged', to, from)) + }) +} + +const noopData = () => { return {} } +const noopFetch = () => {} + +// Special hot reload with asyncData(context) +function getNuxtChildComponents ($parent, $components = []) { + $parent.$children.forEach(($child) => { + if ($child.$vnode && $child.$vnode.data.nuxtChild && !$components.find(c =>(c.$options.__file === $child.$options.__file))) { + $components.push($child) + } + if ($child.$children && $child.$children.length) { + getNuxtChildComponents($child, $components) + } + }) + + return $components +} + +function hotReloadAPI(_app) { + if (!module.hot) return + + let $components = getNuxtChildComponents(_app.$nuxt, []) + + $components.forEach(addHotReload.bind(_app)) +} + +function addHotReload ($component, depth) { + if ($component.$vnode.data._hasHotReload) return + $component.$vnode.data._hasHotReload = true + + var _forceUpdate = $component.$forceUpdate.bind($component.$parent) + + $component.$vnode.context.$forceUpdate = async () => { + let Components = getMatchedComponents(router.currentRoute) + let Component = Components[depth] + if (!Component) { + return _forceUpdate() + } + if (typeof Component === 'object' && !Component.options) { + // Updated via vue-router resolveAsyncComponents() + Component = Vue.extend(Component) + Component._Ctor = Component + } + this.error() + let promises = [] + const next = function (path) { + this.$loading.finish && this.$loading.finish() + router.push(path) + } + await setContext(app, { + route: router.currentRoute, + isHMR: true, + next: next.bind(this) + }) + const context = app.context + + if (this.$loading.start && !this.$loading.manual) { + this.$loading.start() + } + + callMiddleware.call(this, Components, context) + .then(() => { + // If layout changed + if (depth !== 0) { + return + } + + let layout = Component.options.layout || 'default' + if (typeof layout === 'function') { + layout = layout(context) + } + if (this.layoutName === layout) { + return + } + let promise = this.loadLayout(layout) + promise.then(() => { + this.setLayout(layout) + Vue.nextTick(() => hotReloadAPI(this)) + }) + return promise + }) + + .then(() => { + return callMiddleware.call(this, Components, context, this.layout) + }) + + .then(() => { + // Call asyncData(context) + let pAsyncData = promisify(Component.options.asyncData || noopData, context) + pAsyncData.then((asyncDataResult) => { + applyAsyncData(Component, asyncDataResult) + this.$loading.increase && this.$loading.increase(30) + }) + promises.push(pAsyncData) + + // Call fetch() + Component.options.fetch = Component.options.fetch || noopFetch + let pFetch = Component.options.fetch.length && Component.options.fetch(context) + if (!pFetch || (!(pFetch instanceof Promise) && (typeof pFetch.then !== 'function'))) { pFetch = Promise.resolve(pFetch) } + pFetch.then(() => this.$loading.increase && this.$loading.increase(30)) + promises.push(pFetch) + + return Promise.all(promises) + }) + .then(() => { + this.$loading.finish && this.$loading.finish() + _forceUpdate() + setTimeout(() => hotReloadAPI(this), 100) + }) + } +} + +async function mountApp (__app) { + // Set global variables + app = __app.app + router = __app.router + store = __app.store + + // Create Vue instance + const _app = new Vue(app) + + // Mounts Vue app to DOM element + const mount = () => { + _app.$mount('#__nuxt') + + // Add afterEach router hooks + router.afterEach(normalizeComponents) + + router.afterEach(setLayoutForNextPage.bind(_app)) + + router.afterEach(fixPrepatch.bind(_app)) + + // Listen for first Vue update + Vue.nextTick(() => { + // Call window.{{globals.readyCallback}} callbacks + nuxtReady(_app) + + // Enable hot reloading + hotReloadAPI(_app) + }) + } + + // Resolve route components + const Components = await Promise.all(resolveComponents(app.context.route)) + + // Enable transitions + _app.setTransitions = _app.$options.nuxt.setTransitions.bind(_app) + if (Components.length) { + _app.setTransitions(mapTransitions(Components, router.currentRoute)) + _lastPaths = router.currentRoute.matched.map(route => compile(route.path)(router.currentRoute.params)) + } + + // Initialize error handler + _app.$loading = {} // To avoid error while _app.$nuxt does not exist + if (NUXT.error) { + _app.error(NUXT.error) + } + + // Add beforeEach router hooks + router.beforeEach(loadAsyncComponents.bind(_app)) + router.beforeEach(render.bind(_app)) + + // Fix in static: remove trailing slash to force hydration + // Full static, if server-rendered: hydrate, to allow custom redirect to generated page + + // Fix in static: remove trailing slash to force hydration + if (NUXT.serverRendered && isSamePath(NUXT.routePath, _app.context.route.path)) { + return mount() + } + + // First render on client-side + const clientFirstMount = () => { + normalizeComponents(router.currentRoute, router.currentRoute) + setLayoutForNextPage.call(_app, router.currentRoute) + checkForErrors(_app) + // Don't call fixPrepatch.call(_app, router.currentRoute, router.currentRoute) since it's first render + mount() + } + + // fix: force next tick to avoid having same timestamp when an error happen on spa fallback + await new Promise(resolve => setTimeout(resolve, 0)) + render.call(_app, router.currentRoute, router.currentRoute, (path) => { + // If not redirected + if (!path) { + clientFirstMount() + return + } + + // Add a one-time afterEach hook to + // mount the app wait for redirect and route gets resolved + const unregisterHook = router.afterEach((to, from) => { + unregisterHook() + clientFirstMount() + }) + + // Push the path and let route to be resolved + router.push(path, undefined, (err) => { + if (err) { + errorHandler(err) + } + }) + }) +} diff --git a/client/.nuxt/components/index.js b/client/.nuxt/components/index.js new file mode 100644 index 00000000..84236346 --- /dev/null +++ b/client/.nuxt/components/index.js @@ -0,0 +1,49 @@ +import { wrapFunctional } from './utils' + +export { default as AudioPlayer } from '../..\\components\\AudioPlayer.vue' +export { default as AppAppbar } from '../..\\components\\app\\Appbar.vue' +export { default as AppBookShelf } from '../..\\components\\app\\BookShelf.vue' +export { default as AppStreamContainer } from '../..\\components\\app\\StreamContainer.vue' +export { default as AppTracksTable } from '../..\\components\\app\\TracksTable.vue' +export { default as CardsBookCard } from '../..\\components\\cards\\BookCard.vue' +export { default as CardsBookCover } from '../..\\components\\cards\\BookCover.vue' +export { default as ControlsVolumeControl } from '../..\\components\\controls\\VolumeControl.vue' +export { default as ModalsEditModal } from '../..\\components\\modals\\EditModal.vue' +export { default as ModalsModal } from '../..\\components\\modals\\Modal.vue' +export { default as UiBtn } from '../..\\components\\ui\\Btn.vue' +export { default as UiLoadingIndicator } from '../..\\components\\ui\\LoadingIndicator.vue' +export { default as UiMenu } from '../..\\components\\ui\\Menu.vue' +export { default as UiTextareaInput } from '../..\\components\\ui\\TextareaInput.vue' +export { default as UiTextareaWithLabel } from '../..\\components\\ui\\TextareaWithLabel.vue' +export { default as UiTextInput } from '../..\\components\\ui\\TextInput.vue' +export { default as UiTextInputWithLabel } from '../..\\components\\ui\\TextInputWithLabel.vue' +export { default as UiTooltip } from '../..\\components\\ui\\Tooltip.vue' +export { default as WidgetsScanAlert } from '../..\\components\\widgets\\ScanAlert.vue' +export { default as ModalsEditTabsCover } from '../..\\components\\modals\\edit-tabs\\Cover.vue' +export { default as ModalsEditTabsDetails } from '../..\\components\\modals\\edit-tabs\\Details.vue' +export { default as ModalsEditTabsMatch } from '../..\\components\\modals\\edit-tabs\\Match.vue' +export { default as ModalsEditTabsTracks } from '../..\\components\\modals\\edit-tabs\\Tracks.vue' + +export const LazyAudioPlayer = import('../..\\components\\AudioPlayer.vue' /* webpackChunkName: "components/audio-player" */).then(c => wrapFunctional(c.default || c)) +export const LazyAppAppbar = import('../..\\components\\app\\Appbar.vue' /* webpackChunkName: "components/app-appbar" */).then(c => wrapFunctional(c.default || c)) +export const LazyAppBookShelf = import('../..\\components\\app\\BookShelf.vue' /* webpackChunkName: "components/app-book-shelf" */).then(c => wrapFunctional(c.default || c)) +export const LazyAppStreamContainer = import('../..\\components\\app\\StreamContainer.vue' /* webpackChunkName: "components/app-stream-container" */).then(c => wrapFunctional(c.default || c)) +export const LazyAppTracksTable = import('../..\\components\\app\\TracksTable.vue' /* webpackChunkName: "components/app-tracks-table" */).then(c => wrapFunctional(c.default || c)) +export const LazyCardsBookCard = import('../..\\components\\cards\\BookCard.vue' /* webpackChunkName: "components/cards-book-card" */).then(c => wrapFunctional(c.default || c)) +export const LazyCardsBookCover = import('../..\\components\\cards\\BookCover.vue' /* webpackChunkName: "components/cards-book-cover" */).then(c => wrapFunctional(c.default || c)) +export const LazyControlsVolumeControl = import('../..\\components\\controls\\VolumeControl.vue' /* webpackChunkName: "components/controls-volume-control" */).then(c => wrapFunctional(c.default || c)) +export const LazyModalsEditModal = import('../..\\components\\modals\\EditModal.vue' /* webpackChunkName: "components/modals-edit-modal" */).then(c => wrapFunctional(c.default || c)) +export const LazyModalsModal = import('../..\\components\\modals\\Modal.vue' /* webpackChunkName: "components/modals-modal" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiBtn = import('../..\\components\\ui\\Btn.vue' /* webpackChunkName: "components/ui-btn" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiLoadingIndicator = import('../..\\components\\ui\\LoadingIndicator.vue' /* webpackChunkName: "components/ui-loading-indicator" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiMenu = import('../..\\components\\ui\\Menu.vue' /* webpackChunkName: "components/ui-menu" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiTextareaInput = import('../..\\components\\ui\\TextareaInput.vue' /* webpackChunkName: "components/ui-textarea-input" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiTextareaWithLabel = import('../..\\components\\ui\\TextareaWithLabel.vue' /* webpackChunkName: "components/ui-textarea-with-label" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiTextInput = import('../..\\components\\ui\\TextInput.vue' /* webpackChunkName: "components/ui-text-input" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiTextInputWithLabel = import('../..\\components\\ui\\TextInputWithLabel.vue' /* webpackChunkName: "components/ui-text-input-with-label" */).then(c => wrapFunctional(c.default || c)) +export const LazyUiTooltip = import('../..\\components\\ui\\Tooltip.vue' /* webpackChunkName: "components/ui-tooltip" */).then(c => wrapFunctional(c.default || c)) +export const LazyWidgetsScanAlert = import('../..\\components\\widgets\\ScanAlert.vue' /* webpackChunkName: "components/widgets-scan-alert" */).then(c => wrapFunctional(c.default || c)) +export const LazyModalsEditTabsCover = import('../..\\components\\modals\\edit-tabs\\Cover.vue' /* webpackChunkName: "components/modals-edit-tabs-cover" */).then(c => wrapFunctional(c.default || c)) +export const LazyModalsEditTabsDetails = import('../..\\components\\modals\\edit-tabs\\Details.vue' /* webpackChunkName: "components/modals-edit-tabs-details" */).then(c => wrapFunctional(c.default || c)) +export const LazyModalsEditTabsMatch = import('../..\\components\\modals\\edit-tabs\\Match.vue' /* webpackChunkName: "components/modals-edit-tabs-match" */).then(c => wrapFunctional(c.default || c)) +export const LazyModalsEditTabsTracks = import('../..\\components\\modals\\edit-tabs\\Tracks.vue' /* webpackChunkName: "components/modals-edit-tabs-tracks" */).then(c => wrapFunctional(c.default || c)) diff --git a/client/.nuxt/components/nuxt-build-indicator.vue b/client/.nuxt/components/nuxt-build-indicator.vue new file mode 100644 index 00000000..913f5448 --- /dev/null +++ b/client/.nuxt/components/nuxt-build-indicator.vue @@ -0,0 +1,143 @@ + + + + + diff --git a/client/.nuxt/components/nuxt-child.js b/client/.nuxt/components/nuxt-child.js new file mode 100644 index 00000000..af27a4d3 --- /dev/null +++ b/client/.nuxt/components/nuxt-child.js @@ -0,0 +1,122 @@ + +export default { + name: 'NuxtChild', + functional: true, + props: { + nuxtChildKey: { + type: String, + default: '' + }, + keepAlive: Boolean, + keepAliveProps: { + type: Object, + default: undefined + } + }, + render (_, { parent, data, props }) { + const h = parent.$createElement + + 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 + const transitionProps = {} + transitionsKeys.forEach((key) => { + if (typeof transition[key] !== 'undefined') { + transitionProps[key] = transition[key] + } + }) + + const listeners = {} + listenersKeys.forEach((key) => { + if (typeof transition[key] === 'function') { + listeners[key] = transition[key].bind(_parent) + } + }) + if (process.client) { + // Add triggerScroll event on beforeEnter (fix #1376) + const beforeEnter = listeners.beforeEnter + listeners.beforeEnter = (el) => { + // Ensure to trigger scroll event after calling scrollBehavior + window.$nuxt.$nextTick(() => { + window.$nuxt.$emit('triggerScroll') + }) + if (beforeEnter) { + return beforeEnter.call(_parent, el) + } + } + } + + // make sure that leave is called asynchronous (fix #5703) + if (transition.css === false) { + const leave = listeners.leave + + // only add leave listener when user didnt provide one + // or when it misses the done argument + if (!leave || leave.length < 2) { + listeners.leave = (el, done) => { + if (leave) { + leave.call(_parent, el) + } + + _parent.$nextTick(done) + } + } + } + + let routerView = h('routerView', data) + + if (props.keepAlive) { + routerView = h('keep-alive', { props: props.keepAliveProps }, [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' +] diff --git a/client/.nuxt/components/nuxt-error.vue b/client/.nuxt/components/nuxt-error.vue new file mode 100644 index 00000000..e71f7d01 --- /dev/null +++ b/client/.nuxt/components/nuxt-error.vue @@ -0,0 +1,98 @@ + + + + + diff --git a/client/.nuxt/components/nuxt-link.client.js b/client/.nuxt/components/nuxt-link.client.js new file mode 100644 index 00000000..1477cfd0 --- /dev/null +++ b/client/.nuxt/components/nuxt-link.client.js @@ -0,0 +1,98 @@ +import Vue from 'vue' + +const requestIdleCallback = window.requestIdleCallback || + function (cb) { + const start = Date.now() + return setTimeout(function () { + cb({ + didTimeout: false, + timeRemaining: () => Math.max(0, 50 - (Date.now() - start)) + }) + }, 1) + } + +const cancelIdleCallback = window.cancelIdleCallback || function (id) { + clearTimeout(id) +} + +const observer = window.IntersectionObserver && new window.IntersectionObserver((entries) => { + entries.forEach(({ intersectionRatio, target: link }) => { + if (intersectionRatio <= 0 || !link.__prefetch) { + return + } + link.__prefetch() + }) +}) + +export default { + name: 'NuxtLink', + extends: Vue.component('RouterLink'), + props: { + prefetch: { + type: Boolean, + default: true + }, + noPrefetch: { + type: Boolean, + default: false + } + }, + mounted () { + if (this.prefetch && !this.noPrefetch) { + this.handleId = requestIdleCallback(this.observe, { timeout: 2e3 }) + } + }, + beforeDestroy () { + cancelIdleCallback(this.handleId) + + if (this.__observed) { + observer.unobserve(this.$el) + delete this.$el.__prefetch + } + }, + methods: { + observe () { + // If no IntersectionObserver, avoid prefetching + if (!observer) { + return + } + // Add to observer + if (this.shouldPrefetch()) { + this.$el.__prefetch = this.prefetchLink.bind(this) + observer.observe(this.$el) + this.__observed = true + } + }, + shouldPrefetch () { + return this.getPrefetchComponents().length > 0 + }, + canPrefetch () { + const conn = navigator.connection + const hasBadConnection = this.$nuxt.isOffline || (conn && ((conn.effectiveType || '').includes('2g') || conn.saveData)) + + return !hasBadConnection + }, + getPrefetchComponents () { + const ref = this.$router.resolve(this.to, this.$route, this.append) + const Components = ref.resolved.matched.map(r => r.components.default) + + return Components.filter(Component => typeof Component === 'function' && !Component.options && !Component.__prefetched) + }, + prefetchLink () { + if (!this.canPrefetch()) { + return + } + // Stop observing this link (in case of internet connection changes) + observer.unobserve(this.$el) + const Components = this.getPrefetchComponents() + + for (const Component of Components) { + const componentOrPromise = Component() + if (componentOrPromise instanceof Promise) { + componentOrPromise.catch(() => {}) + } + Component.__prefetched = true + } + } + } +} diff --git a/client/.nuxt/components/nuxt-link.server.js b/client/.nuxt/components/nuxt-link.server.js new file mode 100644 index 00000000..f1230908 --- /dev/null +++ b/client/.nuxt/components/nuxt-link.server.js @@ -0,0 +1,16 @@ +import Vue from 'vue' + +export default { + name: 'NuxtLink', + extends: Vue.component('RouterLink'), + props: { + prefetch: { + type: Boolean, + default: true + }, + noPrefetch: { + type: Boolean, + default: false + } + } +} diff --git a/client/.nuxt/components/nuxt-loading.vue b/client/.nuxt/components/nuxt-loading.vue new file mode 100644 index 00000000..8743f117 --- /dev/null +++ b/client/.nuxt/components/nuxt-loading.vue @@ -0,0 +1,177 @@ + + + diff --git a/client/.nuxt/components/nuxt.js b/client/.nuxt/components/nuxt.js new file mode 100644 index 00000000..dc79c20c --- /dev/null +++ b/client/.nuxt/components/nuxt.js @@ -0,0 +1,101 @@ +import Vue from 'vue' +import { compile } from '../utils' + +import NuxtError from './nuxt-error.vue' + +import NuxtChild from './nuxt-child' + +export default { + name: 'Nuxt', + components: { + NuxtChild, + NuxtError + }, + props: { + nuxtChildKey: { + type: String, + default: undefined + }, + keepAlive: Boolean, + keepAliveProps: { + type: Object, + default: undefined + }, + name: { + type: String, + default: 'default' + } + }, + errorCaptured (error) { + // if we receive and error while showing the NuxtError component + // capture the error and force an immediate update so we re-render + // without the NuxtError component + if (this.displayingNuxtError) { + this.errorFromNuxtError = error + this.$forceUpdate() + } + }, + 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 [matchedRoute] = this.$route.matched + + if (!matchedRoute) { + return this.$route.path + } + + const Component = matchedRoute.components.default + + if (Component && Component.options) { + const { options } = Component + + if (options.key) { + return (typeof options.key === 'function' ? options.key(this.$route) : options.key) + } + } + + const strict = /\/$/.test(matchedRoute.path) + return strict ? this.$route.path : this.$route.path.replace(/\/$/, '') + } + }, + beforeCreate () { + Vue.util.defineReactive(this, 'nuxt', this.$root.$options.nuxt) + }, + render (h) { + // if there is no error + if (!this.nuxt.err) { + // Directly return nuxt child + return h('NuxtChild', { + key: this.routerViewKey, + props: this.$props + }) + } + + // if an error occurred within NuxtError show a simple + // error message instead to prevent looping + if (this.errorFromNuxtError) { + this.$nextTick(() => (this.errorFromNuxtError = false)) + + return h('div', {}, [ + h('h2', 'An error occurred while showing the error page'), + h('p', 'Unfortunately an error occurred and while showing the error page another error occurred'), + h('p', `Error details: ${this.errorFromNuxtError.toString()}`), + h('nuxt-link', { props: { to: '/' } }, 'Go back to home') + ]) + } + + // track if we are showing the NuxtError component + this.displayingNuxtError = true + this.$nextTick(() => (this.displayingNuxtError = false)) + + return h(NuxtError, { + props: { + error: this.nuxt.err + } + }) + } +} diff --git a/client/.nuxt/components/plugin.js b/client/.nuxt/components/plugin.js new file mode 100644 index 00000000..978b5c83 --- /dev/null +++ b/client/.nuxt/components/plugin.js @@ -0,0 +1,33 @@ +import Vue from 'vue' +import { wrapFunctional } from './utils' + +const components = { + AudioPlayer: () => import('../..\\components\\AudioPlayer.vue' /* webpackChunkName: "components/audio-player" */).then(c => wrapFunctional(c.default || c)), + AppAppbar: () => import('../..\\components\\app\\Appbar.vue' /* webpackChunkName: "components/app-appbar" */).then(c => wrapFunctional(c.default || c)), + AppBookShelf: () => import('../..\\components\\app\\BookShelf.vue' /* webpackChunkName: "components/app-book-shelf" */).then(c => wrapFunctional(c.default || c)), + AppStreamContainer: () => import('../..\\components\\app\\StreamContainer.vue' /* webpackChunkName: "components/app-stream-container" */).then(c => wrapFunctional(c.default || c)), + AppTracksTable: () => import('../..\\components\\app\\TracksTable.vue' /* webpackChunkName: "components/app-tracks-table" */).then(c => wrapFunctional(c.default || c)), + CardsBookCard: () => import('../..\\components\\cards\\BookCard.vue' /* webpackChunkName: "components/cards-book-card" */).then(c => wrapFunctional(c.default || c)), + CardsBookCover: () => import('../..\\components\\cards\\BookCover.vue' /* webpackChunkName: "components/cards-book-cover" */).then(c => wrapFunctional(c.default || c)), + ControlsVolumeControl: () => import('../..\\components\\controls\\VolumeControl.vue' /* webpackChunkName: "components/controls-volume-control" */).then(c => wrapFunctional(c.default || c)), + ModalsEditModal: () => import('../..\\components\\modals\\EditModal.vue' /* webpackChunkName: "components/modals-edit-modal" */).then(c => wrapFunctional(c.default || c)), + ModalsModal: () => import('../..\\components\\modals\\Modal.vue' /* webpackChunkName: "components/modals-modal" */).then(c => wrapFunctional(c.default || c)), + UiBtn: () => import('../..\\components\\ui\\Btn.vue' /* webpackChunkName: "components/ui-btn" */).then(c => wrapFunctional(c.default || c)), + UiLoadingIndicator: () => import('../..\\components\\ui\\LoadingIndicator.vue' /* webpackChunkName: "components/ui-loading-indicator" */).then(c => wrapFunctional(c.default || c)), + UiMenu: () => import('../..\\components\\ui\\Menu.vue' /* webpackChunkName: "components/ui-menu" */).then(c => wrapFunctional(c.default || c)), + UiTextareaInput: () => import('../..\\components\\ui\\TextareaInput.vue' /* webpackChunkName: "components/ui-textarea-input" */).then(c => wrapFunctional(c.default || c)), + UiTextareaWithLabel: () => import('../..\\components\\ui\\TextareaWithLabel.vue' /* webpackChunkName: "components/ui-textarea-with-label" */).then(c => wrapFunctional(c.default || c)), + UiTextInput: () => import('../..\\components\\ui\\TextInput.vue' /* webpackChunkName: "components/ui-text-input" */).then(c => wrapFunctional(c.default || c)), + UiTextInputWithLabel: () => import('../..\\components\\ui\\TextInputWithLabel.vue' /* webpackChunkName: "components/ui-text-input-with-label" */).then(c => wrapFunctional(c.default || c)), + UiTooltip: () => import('../..\\components\\ui\\Tooltip.vue' /* webpackChunkName: "components/ui-tooltip" */).then(c => wrapFunctional(c.default || c)), + WidgetsScanAlert: () => import('../..\\components\\widgets\\ScanAlert.vue' /* webpackChunkName: "components/widgets-scan-alert" */).then(c => wrapFunctional(c.default || c)), + ModalsEditTabsCover: () => import('../..\\components\\modals\\edit-tabs\\Cover.vue' /* webpackChunkName: "components/modals-edit-tabs-cover" */).then(c => wrapFunctional(c.default || c)), + ModalsEditTabsDetails: () => import('../..\\components\\modals\\edit-tabs\\Details.vue' /* webpackChunkName: "components/modals-edit-tabs-details" */).then(c => wrapFunctional(c.default || c)), + ModalsEditTabsMatch: () => import('../..\\components\\modals\\edit-tabs\\Match.vue' /* webpackChunkName: "components/modals-edit-tabs-match" */).then(c => wrapFunctional(c.default || c)), + ModalsEditTabsTracks: () => import('../..\\components\\modals\\edit-tabs\\Tracks.vue' /* webpackChunkName: "components/modals-edit-tabs-tracks" */).then(c => wrapFunctional(c.default || c)) +} + +for (const name in components) { + Vue.component(name, components[name]) + Vue.component('Lazy' + name, components[name]) +} diff --git a/client/.nuxt/components/readme.md b/client/.nuxt/components/readme.md new file mode 100644 index 00000000..3d00872c --- /dev/null +++ b/client/.nuxt/components/readme.md @@ -0,0 +1,31 @@ +# Discovered Components + +This is an auto-generated list of components discovered by [nuxt/components](https://github.com/nuxt/components). + +You can directly use them in pages and other components without the need to import them. + +**Tip:** If a component is conditionally rendered with `v-if` and is big, it is better to use `Lazy` or `lazy-` prefix to lazy load. + +- `` | `` (components/AudioPlayer.vue) +- `` | `` (components/app/Appbar.vue) +- `` | `` (components/app/BookShelf.vue) +- `` | `` (components/app/StreamContainer.vue) +- `` | `` (components/app/TracksTable.vue) +- `` | `` (components/cards/BookCard.vue) +- `` | `` (components/cards/BookCover.vue) +- `` | `` (components/controls/VolumeControl.vue) +- `` | `` (components/modals/EditModal.vue) +- `` | `` (components/modals/Modal.vue) +- `` | `` (components/ui/Btn.vue) +- `` | `` (components/ui/LoadingIndicator.vue) +- `` | `` (components/ui/Menu.vue) +- `` | `` (components/ui/TextareaInput.vue) +- `` | `` (components/ui/TextareaWithLabel.vue) +- `` | `` (components/ui/TextInput.vue) +- `` | `` (components/ui/TextInputWithLabel.vue) +- `` | `` (components/ui/Tooltip.vue) +- `` | `` (components/widgets/ScanAlert.vue) +- `` | `` (components/modals/edit-tabs/Cover.vue) +- `` | `` (components/modals/edit-tabs/Details.vue) +- `` | `` (components/modals/edit-tabs/Match.vue) +- `` | `` (components/modals/edit-tabs/Tracks.vue) diff --git a/client/.nuxt/components/utils.js b/client/.nuxt/components/utils.js new file mode 100644 index 00000000..b79efd5d --- /dev/null +++ b/client/.nuxt/components/utils.js @@ -0,0 +1,30 @@ +// nuxt/nuxt.js#8607 +export function wrapFunctional(options) { + if (!options || !options.functional) { + return options + } + + const propKeys = Array.isArray(options.props) ? options.props : Object.keys(options.props || {}) + + return { + render(h) { + const attrs = {} + const props = {} + + for (const key in this.$attrs) { + if (propKeys.includes(key)) { + props[key] = this.$attrs[key] + } else { + attrs[key] = this.$attrs[key] + } + } + + return h(options, { + on: this.$listeners, + attrs, + props, + scopedSlots: this.$scopedSlots, + }, this.$slots.default) + } + } +} diff --git a/client/.nuxt/empty.js b/client/.nuxt/empty.js new file mode 100644 index 00000000..a3ac0d84 --- /dev/null +++ b/client/.nuxt/empty.js @@ -0,0 +1 @@ +// This file is intentionally left empty for noop aliases diff --git a/client/.nuxt/index.js b/client/.nuxt/index.js new file mode 100644 index 00000000..c5f319d6 --- /dev/null +++ b/client/.nuxt/index.js @@ -0,0 +1,279 @@ +import Vue from 'vue' +import Vuex from 'vuex' +import Meta from 'vue-meta' +import ClientOnly from 'vue-client-only' +import NoSsr from 'vue-no-ssr' +import { createRouter } from './router.js' +import NuxtChild from './components/nuxt-child.js' +import NuxtError from './components/nuxt-error.vue' +import Nuxt from './components/nuxt.js' +import App from './App.js' +import { setContext, getLocation, getRouteData, normalizeError } from './utils' +import { createStore } from './store.js' + +/* Plugins */ + +import nuxt_plugin_plugin_30872e99 from 'nuxt_plugin_plugin_30872e99' // Source: .\\components\\plugin.js (mode: 'all') +import nuxt_plugin_axios_65e5003c from 'nuxt_plugin_axios_65e5003c' // Source: .\\axios.js (mode: 'all') +import nuxt_plugin_nuxtsocketio_e6f92ab4 from 'nuxt_plugin_nuxtsocketio_e6f92ab4' // Source: .\\nuxt-socket-io.js (mode: 'all') +import nuxt_plugin_initclient_bdf7e43c from 'nuxt_plugin_initclient_bdf7e43c' // Source: ..\\plugins\\init.client.js (mode: 'client') +import nuxt_plugin_axios_397e53b5 from 'nuxt_plugin_axios_397e53b5' // Source: ..\\plugins\\axios.js (mode: 'all') +import nuxt_plugin_toast_05aea064 from 'nuxt_plugin_toast_05aea064' // Source: ..\\plugins\\toast.js (mode: 'all') + +// Component: +Vue.component(ClientOnly.name, ClientOnly) + +// TODO: Remove in Nuxt 3: +Vue.component(NoSsr.name, { + ...NoSsr, + render (h, ctx) { + if (process.client && !NoSsr._warned) { + NoSsr._warned = true + + console.warn(' has been deprecated and will be removed in Nuxt 3, please use instead') + } + return NoSsr.render(h, ctx) + } +}) + +// Component: +Vue.component(NuxtChild.name, NuxtChild) +Vue.component('NChild', NuxtChild) + +// Component NuxtLink is imported in server.js or client.js + +// Component: +Vue.component(Nuxt.name, Nuxt) + +Object.defineProperty(Vue.prototype, '$nuxt', { + get() { + const globalNuxt = this.$root.$options.$nuxt + if (process.client && !globalNuxt && typeof window !== 'undefined') { + return window.$nuxt + } + return globalNuxt + }, + configurable: true +}) + +Vue.use(Meta, {"keyName":"head","attribute":"data-n-head","ssrAttribute":"data-n-head-ssr","tagIDKeyName":"hid"}) + +const defaultTransition = {"name":"page","mode":"out-in","appear":true,"appearClass":"appear","appearActiveClass":"appear-active","appearToClass":"appear-to"} + +const originalRegisterModule = Vuex.Store.prototype.registerModule + +function registerModule (path, rawModule, options = {}) { + const preserveState = process.client && ( + Array.isArray(path) + ? !!path.reduce((namespacedState, path) => namespacedState && namespacedState[path], this.state) + : path in this.state + ) + return originalRegisterModule.call(this, path, rawModule, { preserveState, ...options }) +} + +async function createApp(ssrContext, config = {}) { + const router = await createRouter(ssrContext, config) + + const store = createStore(ssrContext) + // Add this.$router into store actions/mutations + store.$router = router + + // 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 = { + head: {"title":"AudioBookshelf","htmlAttrs":{"lang":"en"},"meta":[{"charset":"utf-8"},{"name":"viewport","content":"width=device-width, initial-scale=1"},{"hid":"description","name":"description","content":""}],"script":[{"src":"\u002F\u002Fcdn.jsdelivr.net\u002Fnpm\u002Fsortablejs@1.8.4\u002FSortable.min.js"}],"link":[{"rel":"icon","type":"image\u002Fx-icon","href":"\u002Ffavicon.ico"},{"rel":"stylesheet","href":"https:\u002F\u002Ffonts.googleapis.com\u002Fcss2?family=Fira+Mono&family=Ubuntu+Mono&family=Open+Sans:wght@600&family=Gentium+Book+Basic"},{"rel":"stylesheet","href":"https:\u002F\u002Ffonts.googleapis.com\u002Ficon?family=Material+Icons"}],"style":[]}, + + store, + 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 = Boolean(err) + err = err ? normalizeError(err) : null + let nuxt = app.nuxt // to work with @vue/composition-api, see https://github.com/nuxt/nuxt.js/issues/6517#issuecomment-573280207 + if (this) { + nuxt = this.nuxt || this.$options.nuxt + } + nuxt.dateErr = Date.now() + nuxt.err = err + // Used in src/server.js + if (ssrContext) { + ssrContext.nuxt.error = err + } + return err + } + }, + ...App + } + + // Make app available into store via this.app + store.app = 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, router.options.mode) + route = router.resolve(path).route + } + + // Set context to app.context + await setContext(app, { + store, + 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, + ssrContext + }) + + function inject(key, value) { + if (!key) { + throw new Error('inject(key, value) has no key provided') + } + if (value === undefined) { + throw new Error(`inject('${key}', value) has no value provided`) + } + + key = '$' + key + // Add into app + app[key] = value + // Add into context + if (!app.context[key]) { + app.context[key] = value + } + + // Add into store + store[key] = app[key] + + // 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 (!Object.prototype.hasOwnProperty.call(Vue.prototype, key)) { + Object.defineProperty(Vue.prototype, key, { + get () { + return this.$root.$options[key] + } + }) + } + }) + } + + // Inject runtime config as $config + inject('config', config) + + if (process.client) { + // Replace store state before plugins execution + if (window.__NUXT__ && window.__NUXT__.state) { + store.replaceState(window.__NUXT__.state) + } + } + + // Add enablePreview(previewData = {}) in context for plugins + if (process.static && process.client) { + app.context.enablePreview = function (previewData = {}) { + app.previewData = Object.assign({}, previewData) + inject('preview', previewData) + } + } + // Plugin execution + + if (typeof nuxt_plugin_plugin_30872e99 === 'function') { + await nuxt_plugin_plugin_30872e99(app.context, inject) + } + + if (typeof nuxt_plugin_axios_65e5003c === 'function') { + await nuxt_plugin_axios_65e5003c(app.context, inject) + } + + if (typeof nuxt_plugin_nuxtsocketio_e6f92ab4 === 'function') { + await nuxt_plugin_nuxtsocketio_e6f92ab4(app.context, inject) + } + + if (process.client && typeof nuxt_plugin_initclient_bdf7e43c === 'function') { + await nuxt_plugin_initclient_bdf7e43c(app.context, inject) + } + + if (typeof nuxt_plugin_axios_397e53b5 === 'function') { + await nuxt_plugin_axios_397e53b5(app.context, inject) + } + + if (typeof nuxt_plugin_toast_05aea064 === 'function') { + await nuxt_plugin_toast_05aea064(app.context, inject) + } + + // Lock enablePreview in context + if (process.static && process.client) { + app.context.enablePreview = function () { + console.warn('You cannot call enablePreview() outside a plugin.') + } + } + + // Wait for async component to be resolved first + await new Promise((resolve, reject) => { + const { route } = router.resolve(app.context.route.fullPath) + // Ignore 404s rather than blindly replacing URL + if (!route.matched.length && process.client) { + return resolve() + } + router.replace(route, resolve, (err) => { + // https://github.com/vuejs/vue-router/blob/v3.4.3/src/util/errors.js + if (!err._isRouter) return reject(err) + if (err.type !== 2 /* NavigationFailureType.redirected */) return resolve() + + // navigated to a different route in router guard + const unregister = router.afterEach(async (to, from) => { + if (process.server && ssrContext && ssrContext.url) { + ssrContext.url = to.fullPath + } + app.context.route = await getRouteData(to) + app.context.params = to.params || {} + app.context.query = to.query || {} + unregister() + resolve() + }) + }) + }) + + return { + store, + app, + router + } +} + +export { createApp, NuxtError } diff --git a/client/.nuxt/jsonp.js b/client/.nuxt/jsonp.js new file mode 100644 index 00000000..702adf21 --- /dev/null +++ b/client/.nuxt/jsonp.js @@ -0,0 +1,82 @@ +const chunks = {} // chunkId => exports +const chunksInstalling = {} // chunkId => Promise +const failedChunks = {} + +function importChunk(chunkId, src) { + // Already installed + if (chunks[chunkId]) { + return Promise.resolve(chunks[chunkId]) + } + + // Failed loading + if (failedChunks[chunkId]) { + return Promise.reject(failedChunks[chunkId]) + } + + // Installing + if (chunksInstalling[chunkId]) { + return chunksInstalling[chunkId] + } + + // Set a promise in chunk cache + let resolve, reject + const promise = chunksInstalling[chunkId] = new Promise((_resolve, _reject) => { + resolve = _resolve + reject = _reject + }) + + // Clear chunk data from cache + delete chunks[chunkId] + + // Start chunk loading + const script = document.createElement('script') + script.charset = 'utf-8' + script.timeout = 120 + script.src = src + let timeout + + // Create error before stack unwound to get useful stacktrace later + const error = new Error() + + // Complete handlers + const onScriptComplete = script.onerror = script.onload = (event) => { + // Cleanups + clearTimeout(timeout) + delete chunksInstalling[chunkId] + + // Avoid mem leaks in IE + script.onerror = script.onload = null + + // Verify chunk is loaded + if (chunks[chunkId]) { + return resolve(chunks[chunkId]) + } + + // Something bad happened + const errorType = event && (event.type === 'load' ? 'missing' : event.type) + const realSrc = event && event.target && event.target.src + error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')' + error.name = 'ChunkLoadError' + error.type = errorType + error.request = realSrc + failedChunks[chunkId] = error + reject(error) + } + + // Timeout + timeout = setTimeout(() => { + onScriptComplete({ type: 'timeout', target: script }) + }, 120000) + + // Append script + document.head.appendChild(script) + + // Return promise + return promise +} + +export function installJsonp() { + window.__NUXT_JSONP__ = function (chunkId, exports) { chunks[chunkId] = exports } + window.__NUXT_JSONP_CACHE__ = chunks + window.__NUXT_IMPORT__ = importChunk +} diff --git a/client/.nuxt/loading.html b/client/.nuxt/loading.html new file mode 100644 index 00000000..a6dcd1b5 --- /dev/null +++ b/client/.nuxt/loading.html @@ -0,0 +1,110 @@ + + + + +
Loading...
+ + diff --git a/client/.nuxt/middleware.js b/client/.nuxt/middleware.js new file mode 100644 index 00000000..343ef954 --- /dev/null +++ b/client/.nuxt/middleware.js @@ -0,0 +1,3 @@ +const middleware = {} + +export default middleware diff --git a/client/.nuxt/mixins/fetch.client.js b/client/.nuxt/mixins/fetch.client.js new file mode 100644 index 00000000..017e559e --- /dev/null +++ b/client/.nuxt/mixins/fetch.client.js @@ -0,0 +1,90 @@ +import Vue from 'vue' +import { hasFetch, normalizeError, addLifecycleHook, createGetCounter } from '../utils' + +const isSsrHydration = (vm) => vm.$vnode && vm.$vnode.elm && vm.$vnode.elm.dataset && vm.$vnode.elm.dataset.fetchKey +const nuxtState = window.__NUXT__ + +export default { + beforeCreate () { + if (!hasFetch(this)) { + return + } + + this._fetchDelay = typeof this.$options.fetchDelay === 'number' ? this.$options.fetchDelay : 200 + + Vue.util.defineReactive(this, '$fetchState', { + pending: false, + error: null, + timestamp: Date.now() + }) + + this.$fetch = $fetch.bind(this) + addLifecycleHook(this, 'created', created) + addLifecycleHook(this, 'beforeMount', beforeMount) + } +} + +function beforeMount() { + if (!this._hydrated) { + return this.$fetch() + } +} + +function created() { + if (!isSsrHydration(this)) { + return + } + + // Hydrate component + this._hydrated = true + this._fetchKey = this.$vnode.elm.dataset.fetchKey + const data = nuxtState.fetch[this._fetchKey] + + // If fetch error + if (data && data._error) { + this.$fetchState.error = data._error + return + } + + // Merge data + for (const key in data) { + Vue.set(this.$data, key, data[key]) + } +} + +function $fetch() { + if (!this._fetchPromise) { + this._fetchPromise = $_fetch.call(this) + .then(() => { delete this._fetchPromise }) + } + return this._fetchPromise +} + +async function $_fetch() { + this.$nuxt.nbFetching++ + this.$fetchState.pending = true + this.$fetchState.error = null + this._hydrated = false + let error = null + const startTime = Date.now() + + try { + await this.$options.fetch.call(this) + } catch (err) { + if (process.dev) { + console.error('Error in fetch():', err) + } + error = normalizeError(err) + } + + const delayLeft = this._fetchDelay - (Date.now() - startTime) + if (delayLeft > 0) { + await new Promise(resolve => setTimeout(resolve, delayLeft)) + } + + this.$fetchState.error = error + this.$fetchState.pending = false + this.$fetchState.timestamp = Date.now() + + this.$nextTick(() => this.$nuxt.nbFetching--) +} diff --git a/client/.nuxt/mixins/fetch.server.js b/client/.nuxt/mixins/fetch.server.js new file mode 100644 index 00000000..24a00686 --- /dev/null +++ b/client/.nuxt/mixins/fetch.server.js @@ -0,0 +1,69 @@ +import Vue from 'vue' +import { hasFetch, normalizeError, addLifecycleHook, purifyData, createGetCounter } from '../utils' + +async function serverPrefetch() { + if (!this._fetchOnServer) { + return + } + + // Call and await on $fetch + try { + await this.$options.fetch.call(this) + } catch (err) { + if (process.dev) { + console.error('Error in fetch():', err) + } + this.$fetchState.error = normalizeError(err) + } + this.$fetchState.pending = false + + // Define an ssrKey for hydration + this._fetchKey = this._fetchKey || this.$ssrContext.fetchCounters['']++ + + // Add data-fetch-key on parent element of Component + const attrs = this.$vnode.data.attrs = this.$vnode.data.attrs || {} + attrs['data-fetch-key'] = this._fetchKey + + // Add to ssrContext for window.__NUXT__.fetch + + if (this.$ssrContext.nuxt.fetch[this._fetchKey] !== undefined) { + console.warn(`Duplicate fetch key detected (${this._fetchKey}). This may lead to unexpected results.`) + } + + this.$ssrContext.nuxt.fetch[this._fetchKey] = + this.$fetchState.error ? { _error: this.$fetchState.error } : purifyData(this._data) +} + +export default { + created() { + if (!hasFetch(this)) { + return + } + + if (typeof this.$options.fetchOnServer === 'function') { + this._fetchOnServer = this.$options.fetchOnServer.call(this) !== false + } else { + this._fetchOnServer = this.$options.fetchOnServer !== false + } + + const defaultKey = this.$options._scopeId || this.$options.name || '' + const getCounter = createGetCounter(this.$ssrContext.fetchCounters, defaultKey) + + if (typeof this.$options.fetchKey === 'function') { + this._fetchKey = this.$options.fetchKey.call(this, getCounter) + } else { + const key = 'string' === typeof this.$options.fetchKey ? this.$options.fetchKey : defaultKey + this._fetchKey = key ? key + ':' + getCounter(key) : String(getCounter(key)) + } + + // Added for remove vue undefined warning while ssr + this.$fetch = () => {} // issue #8043 + Vue.util.defineReactive(this, '$fetchState', { + pending: true, + error: null, + timestamp: Date.now() + }) + + addLifecycleHook(this, 'serverPrefetch', serverPrefetch) + } +} diff --git a/client/.nuxt/nuxt-socket-io.js b/client/.nuxt/nuxt-socket-io.js new file mode 100644 index 00000000..ea62f28e --- /dev/null +++ b/client/.nuxt/nuxt-socket-io.js @@ -0,0 +1,1083 @@ +/* eslint-disable no-console */ +/* + * Copyright 2021 Richard Schloss (https://github.com/richardeschloss/nuxt-socket-io) + */ + +import io from 'socket.io-client' +import Debug from 'debug' +import emitter from 'tiny-emitter/instance' +/* + TODO: + 1) will enable when '@nuxtjs/composition-api' reaches stable version: + 2) will bump from devDep to dep when stable +*/ + // import { watch as vueWatch } from '@nuxtjs/composition-api' + +const debug = Debug('nuxt-socket-io') + +function PluginOptions() { + let _pluginOptions + if (process.env.TEST === undefined) { + _pluginOptions = {"sockets":[{"name":"dev","url":"http://localhost:3333"},{"name":"prod"}]} + } + + return Object.freeze({ + get: () => _pluginOptions, + set: (opts) => (_pluginOptions = opts) + }) +} + +const isRefImpl = (any) => any && any.constructor.name === 'RefImpl' + +const _pOptions = PluginOptions() + +const _sockets = {} + +let warn, infoMsgs + +function camelCase(str) { + return str + .replace(/[_\-\s](.)/g, function($1) { + return $1.toUpperCase() + }) + .replace(/[-_\s]/g, '') + .replace(/^(.)/, function($1) { + return $1.toLowerCase() + }) + .replace(/[^\w\s]/gi, '') +} + +function propExists(obj, path) { + const exists = path.split('.').reduce((out, prop) => { + if (out !== undefined && out[prop] !== undefined) { + return out[prop] + } + }, obj) + + return exists !== undefined +} + +function parseEntry(entry, entryType) { + let evt, mapTo, pre, body, post, emitEvt, msgLabel + if (typeof entry === 'string') { + let subItems = [] + const items = entry.trim().split(/\s*\]\s*/) + if (items.length > 1) { + pre = items[0] + subItems = items[1].split(/\s*\[\s*/) + } else { + subItems = items[0].split(/\s*\[\s*/) + } + ;[body, post] = subItems + if (body.includes('-->')) { + ;[evt, mapTo] = body.split(/\s*-->\s*/) + } else if (body.includes('<--')) { + ;[evt, mapTo] = body.split(/\s*<--\s*/) + } else { + evt = body + } + + if (entryType === 'emitter') { + ;[emitEvt, msgLabel] = evt.split(/\s*\+\s*/) + } else if (mapTo === undefined) { + mapTo = evt + } + } else if (entryType === 'emitBack') { + ;[[mapTo, evt]] = Object.entries(entry) + } else { + ;[[evt, mapTo]] = Object.entries(entry) + } + return { pre, post, evt, mapTo, emitEvt, msgLabel } +} + +function assignMsg(ctx, prop) { + let msg + if (prop !== undefined) { + if (ctx[prop] !== undefined) { + if (typeof ctx[prop] === 'object') { + msg = ctx[prop].constructor.name === 'Array' ? [] : {} + Object.assign(msg, ctx[prop]) + } else { + msg = ctx[prop] + } + } else { + warn(`prop or data item "${prop}" not defined`) + } + debug(`assigned ${prop} to ${msg}`) + } + return msg +} + +function assignResp(ctx, prop, resp) { + if (prop !== undefined) { + if (ctx[prop] !== undefined) { + if (typeof ctx[prop] !== 'function') { + // In vue3, it's possible to create + // reactive refs on the fly with ref() + // so check for that here. + // (this would elimnate the need for v2's + // this.$set because we just set the value prop + // to trigger the UI changes) + if (isRefImpl(ctx[prop])) { + ctx[prop].value = resp + } else { + ctx[prop] = resp + } + debug(`assigned ${resp} to ${prop}`) + } + } else { + warn(`${prop} not defined on instance`) + } + } +} + +async function runHook(ctx, prop, data) { + if (prop !== undefined) { + if (ctx[prop]) return await ctx[prop](data) + else warn(`method ${prop} not defined`) + } +} + +function propByPath(obj, path) { + return path.split(/[/.]/).reduce((out, prop) => { + if (out !== undefined && out[prop] !== undefined) { + return out[prop] + } + }, obj) +} + +function validateSockets(sockets) { + return (sockets + && Array.isArray(sockets) + && sockets.length > 0) +} + +const register = { + clientApiEvents({ ctx, store, socket, api }) { + const { evts } = api + Object.entries(evts).forEach(([emitEvt, schema]) => { + const { data: dataT } = schema + const fn = emitEvt + 'Emit' + if (ctx[emitEvt] !== undefined) { + if (dataT !== undefined) { + Object.entries(dataT).forEach(([key, val]) => { + ctx.$set(ctx[emitEvt], key, val) + }) + debug('Initialized data for', emitEvt, dataT) + } + } + + if (ctx[fn] !== undefined) return + + ctx[fn] = (fnArgs) => { + const { label: apiLabel, ack, ...args } = fnArgs || {} + return new Promise(async (resolve, reject) => { + const label = apiLabel || api.label + const msg = Object.keys(args).length > 0 ? args : { ...ctx[emitEvt] } + msg.method = fn + if (ack) { + const ackd = await store.dispatch('$nuxtSocket/emit', { + label, + socket, + evt: emitEvt, + msg + }) + resolve(ackd) + } else { + store.dispatch('$nuxtSocket/emit', { + label, + socket, + evt: emitEvt, + msg, + noAck: true + }) + resolve() + } + }) + } + debug('Registered clientAPI method', fn) + }) + }, + clientApiMethods({ ctx, socket, api }) { + const { methods } = api + const evts = Object.assign({}, methods, { getAPI: {} }) + Object.entries(evts).forEach(([evt, schema]) => { + if (socket.hasListeners(evt)) { + warn(`evt ${evt} already has a listener registered`) + } + + socket.on(evt, async (msg, cb) => { + if (evt === 'getAPI') { + if (cb) cb(api) + } else if (ctx[evt] !== undefined) { + msg.method = evt + const resp = await ctx[evt](msg) + if (cb) cb(resp) + } else if (cb) { + cb({ + emitErr: 'notImplemented', + msg: `Client has not yet implemented method (${evt})` + }) + } + }) + + debug(`registered client api method ${evt}`) + if (evt !== 'getAPI' && ctx[evt] === undefined) { + warn( + `client api method ${evt} has not been defined. ` + + `Either update the client api or define the method so it can be used by callers` + ) + } + }) + }, + clientAPI({ ctx, store, socket, clientAPI }) { + if (clientAPI.methods) { + register.clientApiMethods({ ctx, socket, api: clientAPI }) + } + + if (clientAPI.evts) { + register.clientApiEvents({ ctx, store, socket, api: clientAPI }) + } + + store.commit('$nuxtSocket/SET_CLIENT_API', clientAPI) + debug('clientAPI registered', clientAPI) + }, + serverApiEvents({ ctx, socket, api, label, ioDataProp, apiIgnoreEvts }) { + const { evts } = api + Object.entries(evts).forEach(([evt, entry]) => { + const { methods = [], data: dataT } = entry + if (apiIgnoreEvts.includes(evt)) { + debug( + `Event ${evt} is in ignore list ("apiIgnoreEvts"), not registering.` + ) + return + } + + if (socket.hasListeners(evt)) { + warn(`evt ${evt} already has a listener registered`) + } + + if (methods.length === 0) { + let initVal = dataT + if (typeof initVal === 'object') { + initVal = dataT.constructor.name === 'Array' ? [] : {} + } + ctx.$set(ctx[ioDataProp], evt, initVal) + } else { + methods.forEach((method) => { + if (ctx[ioDataProp][method] === undefined) { + ctx.$set(ctx[ioDataProp], method, {}) + } + + ctx.$set( + ctx[ioDataProp][method], + evt, + dataT.constructor.name === 'Array' ? [] : {} + ) + }) + } + + socket.on(evt, (msg, cb) => { + debug(`serverAPI event ${evt} rxd with msg`, msg) + const { method, data } = msg + if (method !== undefined) { + if (ctx[ioDataProp][method] === undefined) { + ctx.$set(ctx[ioDataProp], method, {}) + } + + ctx.$set(ctx[ioDataProp][method], evt, data) + } else { + ctx.$set(ctx[ioDataProp], evt, data) + } + + if (cb) { + cb({ ack: 'ok' }) + } + }) + debug(`Registered listener for ${evt} on ${label}`) + }) + }, + serverApiMethods({ ctx, socket, store, api, label, ioApiProp, ioDataProp }) { + Object.entries(api.methods).forEach(([fn, schema]) => { + const { msg: msgT, resp: respT } = schema + if (ctx[ioDataProp][fn] === undefined) { + ctx.$set(ctx[ioDataProp], fn, {}) + if (msgT !== undefined) { + ctx.$set(ctx[ioDataProp][fn], 'msg', { ...msgT }) + } + + if (respT !== undefined) { + ctx.$set( + ctx[ioDataProp][fn], + 'resp', + respT.constructor.name === 'Array' ? [] : {} + ) + } + } + + ctx[ioApiProp][fn] = (args) => { + return new Promise(async (resolve, reject) => { + const emitEvt = fn + const msg = args !== undefined ? args : { ...ctx[ioDataProp][fn].msg } + debug(`${ioApiProp}:${label}: Emitting ${emitEvt} with ${msg}`) + const resp = await store.dispatch('$nuxtSocket/emit', { + label, + socket, + evt: emitEvt, + msg + }) + + ctx[ioDataProp][fn].resp = resp + resolve(resp) + }) + } + }) + }, + async serverAPI({ + ctx, + socket, + store, + label, + apiIgnoreEvts, + ioApiProp, + ioDataProp, + serverAPI, + clientAPI = {} + }) { + if (ctx[ioApiProp] === undefined) { + console.error( + `[nuxt-socket-io]: ${ioApiProp} needs to be defined in the current context for ` + + `serverAPI registration (vue requirement)` + ) + return + } + + const apiLabel = serverAPI.label || label + debug('register api for', apiLabel) + const api = store.state.$nuxtSocket.ioApis[apiLabel] || {} + const fetchedApi = await store.dispatch('$nuxtSocket/emit', { + label: apiLabel, + socket, + evt: serverAPI.evt || 'getAPI', + msg: serverAPI.data || {} + }) + + const isPeer = + clientAPI.label === fetchedApi.label && + parseFloat(clientAPI.version) === parseFloat(fetchedApi.version) + if (isPeer) { + Object.assign(api, clientAPI) + store.commit('$nuxtSocket/SET_API', { label: apiLabel, api }) + debug(`api for ${apiLabel} registered`, api) + } else if (parseFloat(api.version) !== parseFloat(fetchedApi.version)) { + Object.assign(api, fetchedApi) + store.commit('$nuxtSocket/SET_API', { label: apiLabel, api }) + debug(`api for ${apiLabel} registered`, api) + } + + ctx.$set(ctx, ioApiProp, api) + + if (api.methods !== undefined) { + register.serverApiMethods({ + ctx, + socket, + store, + api, + label, + ioApiProp, + ioDataProp + }) + debug( + `Attached methods for ${label} to ${ioApiProp}`, + Object.keys(api.methods) + ) + } + + if (api.evts !== undefined) { + register.serverApiEvents({ + ctx, + socket, + api, + label, + ioDataProp, + apiIgnoreEvts + }) + debug(`registered evts for ${label} to ${ioApiProp}`) + } + + ctx.$set(ctx[ioApiProp], 'ready', true) + debug('ioApi', ctx[ioApiProp]) + }, + emitErrors({ ctx, err, emitEvt, emitErrorsProp }) { + if (ctx[emitErrorsProp][emitEvt] === undefined) { + ctx[emitErrorsProp][emitEvt] = [] + } + ctx[emitErrorsProp][emitEvt].push(err) + }, + emitTimeout({ ctx, emitEvt, emitErrorsProp, emitTimeout, timerObj }) { + return new Promise((resolve, reject) => { + timerObj.timer = setTimeout(() => { + const err = { + message: 'emitTimeout', + emitEvt, + emitTimeout, + hint: [ + `1) Is ${emitEvt} supported on the backend?`, + `2) Is emitTimeout ${emitTimeout} ms too small?` + ].join('\r\n'), + timestamp: Date.now() + } + debug('emitEvt timed out', err) + if (typeof ctx[emitErrorsProp] === 'object') { + register.emitErrors({ ctx, err, emitEvt, emitErrorsProp }) + resolve() + } else { + reject(err) + } + }, emitTimeout) + }) + }, + emitBacks({ ctx, socket, entries }) { + entries.forEach((entry) => { + const { pre, post, evt, mapTo } = parseEntry(entry, 'emitBack') + if (propExists(ctx, mapTo)) { + debug('registered local emitBack', { mapTo }) + ctx.$watch(mapTo, async function(data, oldData) { + debug('local data changed', evt, data) + const preResult = await runHook(ctx, pre, { data, oldData }) + if (preResult === false) { + return Promise.resolve() + } + debug('Emitting back:', { evt, mapTo, data }) + return new Promise((resolve) => { + socket.emit(evt, { data }, (resp) => { + runHook(ctx, post, resp) + resolve(resp) + }) + if (post === undefined) resolve() + }) + }) + } else { + warn(`Specified emitback ${mapTo} is not defined in component`) + } + }) + }, + emitBacksVuex({ ctx, store, useSocket, socket, entries }) { + entries.forEach((entry) => { + const { pre, post, evt, mapTo } = parseEntry(entry, 'emitBack') + + if (useSocket.registeredWatchers.includes(mapTo)) { + return + } + + store.watch( + (state) => { + const watchProp = propByPath(state, mapTo) + if (watchProp === undefined) { + throw new Error( + [ + `[nuxt-socket-io]: Trying to register emitback ${mapTo} failed`, + `because it is not defined in Vuex.`, + 'Is state set up correctly in your stores folder?' + ].join('\n') + ) + } + useSocket.registeredWatchers.push(mapTo) + debug('emitBack registered', { mapTo }) + return watchProp + }, + async (data, oldData) => { + debug('vuex emitBack data changed', { emitBack: evt, data, oldData }) + const preResult = await runHook(ctx, pre, { data, oldData }) + if (preResult === false) { + return Promise.resolve() + } + debug('Emitting back:', { evt, mapTo, data }) + socket.emit(evt, { data }, (resp) => { + runHook(ctx, post, resp) + }) + } + ) + }) + }, + emitters({ ctx, socket, entries, emitTimeout, emitErrorsProp }) { + entries.forEach((entry) => { + const { pre, post, mapTo, emitEvt, msgLabel } = parseEntry( + entry, + 'emitter' + ) + ctx[emitEvt] = async function(args) { + const msg = args !== undefined ? args : assignMsg(ctx, msgLabel) + debug('Emit evt', { emitEvt, msg }) + const preResult = await runHook(ctx, pre, msg) + if (preResult === false) { + return Promise.resolve() + } + return new Promise((resolve, reject) => { + const timerObj = {} + socket.emit(emitEvt, msg, (resp) => { + debug('Emitter response rxd', { emitEvt, resp }) + clearTimeout(timerObj.timer) + const { emitError, ...errorDetails } = resp || {} + if (emitError !== undefined) { + const err = { + message: emitError, + emitEvt, + errorDetails, + timestamp: Date.now() + } + debug('Emit error occurred', err) + if (typeof ctx[emitErrorsProp] === 'object') { + register.emitErrors({ + ctx, + err, + emitEvt, + emitErrorsProp + }) + resolve() + } else { + reject(err) + } + } else { + assignResp(ctx.$data || ctx, mapTo, resp) + runHook(ctx, post, resp) + resolve(resp) + } + }) + if (emitTimeout) { + register + .emitTimeout({ + ctx, + emitEvt, + emitErrorsProp, + emitTimeout, + timerObj + }) + .then(resolve) + .catch(reject) + debug('Emit timeout registered for evt', { emitEvt, emitTimeout }) + } + }) + } + debug('Emitter created', { emitter: emitEvt }) + }) + }, + listeners({ ctx, socket, entries }) { + entries.forEach((entry) => { + const { pre, post, evt, mapTo } = parseEntry(entry) + debug('Registered local listener', evt) + socket.on(evt, async (resp) => { + debug('Local listener received data', { evt, resp }) + await runHook(ctx, pre) + assignResp(ctx.$data || ctx, mapTo, resp) + runHook(ctx, post, resp) + }) + }) + }, + listenersVuex({ ctx, socket, entries, storeFn, useSocket }) { + entries.forEach((entry) => { + const { pre, post, evt, mapTo } = parseEntry(entry) + async function vuexListenerEvt(resp) { + debug('Vuex listener received data', { evt, resp }) + await runHook(ctx, pre) + storeFn(mapTo, resp) + runHook(ctx, post, resp) + } + + if (useSocket.registeredVuexListeners.includes(evt)) return + + socket.on(evt, vuexListenerEvt) + debug('Registered vuex listener', evt) + useSocket.registeredVuexListeners.push(evt) + }) + }, + namespace({ ctx, namespaceCfg, socket, emitTimeout, emitErrorsProp }) { + const { emitters = [], listeners = [], emitBacks = [] } = namespaceCfg + const sets = { emitters, listeners, emitBacks } + Object.entries(sets).forEach(([setName, entries]) => { + if (entries.constructor.name === 'Array') { + register[setName]({ ctx, socket, entries, emitTimeout, emitErrorsProp }) + } else { + warn( + `[nuxt-socket-io]: ${setName} needs to be an array in namespace config` + ) + } + }) + }, + vuexModule({ store }) { + store.registerModule( + '$nuxtSocket', + { + namespaced: true, + state: { + clientApis: {}, + ioApis: {}, + emitErrors: {}, + emitTimeouts: {} + }, + mutations: { + SET_API(state, { label, api }) { + state.ioApis[label] = api + }, + + SET_CLIENT_API(state, { label = 'clientAPI', ...api }) { + state.clientApis[label] = api + }, + + SET_EMIT_ERRORS(state, { label, emitEvt, err }) { + if (state.emitErrors[label] === undefined) { + state.emitErrors[label] = {} + } + + if (state.emitErrors[label][emitEvt] === undefined) { + state.emitErrors[label][emitEvt] = [] + } + + state.emitErrors[label][emitEvt].push(err) + }, + + SET_EMIT_TIMEOUT(state, { label, emitTimeout }) { + state.emitTimeouts[label] = emitTimeout + } + }, + actions: { + emit( + { state, commit }, + { label, socket, evt, msg, emitTimeout, noAck } + ) { + debug('$nuxtSocket vuex action "emit" dispatched', label, evt) + return new Promise((resolve, reject) => { + const _socket = socket || _sockets[label] + const _emitTimeout = + emitTimeout !== undefined + ? emitTimeout + : state.emitTimeouts[label] + + if (_socket === undefined) { + reject( + new Error( + 'socket instance required. Please provide a valid socket label or socket instance' + ) + ) + } + debug(`Emitting ${evt} with msg`, msg) + let timer + _socket.emit(evt, msg, (resp) => { + debug('Emitter response rxd', { evt, resp }) + clearTimeout(timer) + const { emitError, ...errorDetails } = resp || {} + if (emitError !== undefined) { + const err = { + message: emitError, + emitEvt: evt, + errorDetails, + timestamp: Date.now() + } + debug('Emit error occurred', err) + if (label !== undefined && label !== '') { + debug( + `[nuxt-socket-io]: ${label} Emit error ${err.message} occurred and logged to vuex `, + err + ) + commit('SET_EMIT_ERRORS', { label, emitEvt: evt, err }) + resolve() + } else { + reject(new Error(JSON.stringify(err, null, '\t'))) + } + } else { + resolve(resp) + } + }) + + if (noAck) { + resolve() + } + + if (_emitTimeout) { + debug(`registering emitTimeout ${_emitTimeout} ms for ${evt}`) + timer = setTimeout(() => { + const err = { + message: 'emitTimeout', + emitEvt: evt, + emitTimeout, + hint: [ + `1) Is ${evt} supported on the backend?`, + `2) Is emitTimeout ${_emitTimeout} ms too small?` + ].join('\r\n'), + timestamp: Date.now() + } + if (label !== undefined && label !== '') { + commit('SET_EMIT_ERRORS', { label, emitEvt: evt, err }) + debug( + `[nuxt-socket-io]: ${label} Emit error occurred and logged to vuex `, + err + ) + resolve() + } else { + reject(new Error(JSON.stringify(err, null, '\t'))) + } + }, _emitTimeout) + } + }) + } + } + }, + { preserveState: false } + ) + }, + vuexOpts({ ctx, vuexOpts, useSocket, socket, store }) { + const { mutations = [], actions = [], emitBacks = [] } = vuexOpts + const sets = { mutations, actions, emitBacks } + const storeFns = { + mutations: 'commit', + actions: 'dispatch' + } + Object.entries(sets).forEach(([setName, entries]) => { + if (entries.constructor.name === 'Array') { + const fnName = storeFns[setName] + if (fnName) { + register.listenersVuex({ + ctx, + socket, + entries, + storeFn: store[fnName], + useSocket + }) + } else { + register.emitBacksVuex({ ctx, store, useSocket, socket, entries }) + } + } else { + warn(`[nuxt-socket-io]: vuexOption ${setName} needs to be an array`) + } + }) + }, + socketStatus({ ctx, socket, connectUrl, statusProp }) { + const socketStatus = { connectUrl } + // See also: + // https://socket.io/docs/v3/migrating-from-2-x-to-3-0/index.html#The-Socket-instance-will-no-longer-forward-the-events-emitted-by-its-Manager + const clientEvts = [ + 'connect_error', + 'connect_timeout', + 'reconnect', + 'reconnect_attempt', + 'reconnecting', // socket.io-client v2.x only + 'reconnect_error', + 'reconnect_failed', + 'ping', + 'pong' + ] + clientEvts.forEach((evt) => { + const prop = camelCase(evt) + socketStatus[prop] = '' + function handleEvt(resp) { + Object.assign(ctx[statusProp], { [prop]: resp }) + } + socket.on(evt, handleEvt) + socket.io.on(evt, handleEvt) + }) + Object.assign(ctx, { [statusProp]: socketStatus }) + }, + teardown({ ctx, socket, useSocket }) { + // Setup listener for "closeSockets" in case + // multiple instances of nuxtSocket exist in the same + // component (only one destroy/unmount event takes place). + // When we teardown, we want to remove the listeners of all + // the socket.io-client instances + ctx.$once('closeSockets', function() { + debug('closing socket id=' + socket.id) + socket.removeAllListeners() + socket.close() + }) + + if (!ctx.registeredTeardown) { + // ctx.$destroy is defined in vue2 + // but will go away in vue3 (in favor of onUnmounted) + // save user's destroy method and honor it after + // we run nuxt-socket-io's teardown + ctx.onComponentDestroy = ctx.$destroy + debug('teardown enabled for socket', { name: useSocket.name }) + // Our $destroy method + // Gets called automatically on the destroy lifecycle + // in v2. In v3, we have call it with the + // onUnmounted hook + ctx.$destroy = function() { + debug('component destroyed, closing socket(s)', { + name: useSocket.name, + url: useSocket.url + }) + useSocket.registeredVuexListeners = [] + ctx.$emit('closeSockets') + // Only run the user's destroy method + // if it exists + if (ctx.onComponentDestroy) { + ctx.onComponentDestroy() + } + } + + // onUnmounted will only exist in v3 + if (ctx.onUnmounted) { + ctx.onUnmounted(ctx.$destroy) + } + ctx.registeredTeardown = true + } + + socket.on('disconnect', () => { + debug('server disconnected', { name: useSocket.name, url: useSocket.url }) + socket.close() + }) + }, + stubs(ctx) { + // Use a tiny event bus now. Can probably + // be replaced by watch eventually. For now this works. + if (!ctx.$on || !ctx.$emit || !ctx.$once) { + ctx.$once = (...args) => emitter.once(...args) + ctx.$on = (...args) => emitter.on(...args) + ctx.$off = (...args) => emitter.off(...args) + ctx.$emit = (...args) => emitter.emit(...args) + } + + if (!ctx.$set) { + ctx.$set = (obj, key, val) => { + if (isRefImpl(obj[key])) { + obj[key].value = val + } else { + obj[key] = val + } + } + } + + if (!ctx.$watch) { + ctx.$watch = (label, cb) => { + // will enable when '@nuxtjs/composition-api' reaches stable version: + // vueWatch(ctx.$data[label], cb) + } + } + } +} + +function nuxtSocket(ioOpts) { + const { + name, + channel = '', + statusProp = 'socketStatus', + persist, + teardown = !persist, + emitTimeout, + emitErrorsProp = 'emitErrors', + ioApiProp = 'ioApi', + ioDataProp = 'ioData', + apiIgnoreEvts = [], + serverAPI, + clientAPI, + vuex, + namespaceCfg, + ...connectOpts + } = ioOpts + const pluginOptions = _pOptions.get() + const { $config, $store } = this + const store = this.$store || this.store + + const runtimeOptions = { ...pluginOptions } + if ($config && $config.io) { + Object.assign(runtimeOptions, $config.io) + runtimeOptions.sockets = validateSockets(pluginOptions.sockets) + ? pluginOptions.sockets + : [] + if (validateSockets($config.io.sockets)) { + $config.io.sockets.forEach((socket) => { + const fnd = runtimeOptions.sockets.find(({ name }) => name === socket.name) + if (fnd === undefined) { + runtimeOptions.sockets.push(socket) + } + }) + } + } + + const mergedOpts = Object.assign({}, runtimeOptions, ioOpts) + const { sockets, warnings = true, info = true } = mergedOpts + + warn = + warnings && process.env.NODE_ENV !== 'production' ? console.warn : () => {} + + infoMsgs = + info && process.env.NODE_ENV !== 'production' ? console.info : () => {} + + if (!validateSockets(sockets)) { + throw new Error( + "Please configure sockets if planning to use nuxt-socket-io: \r\n [{name: '', url: ''}]" + ) + } + + register.stubs(this) + + let useSocket = null + + if (!name) { + useSocket = sockets.find((s) => s.default === true) + } else { + useSocket = sockets.find((s) => s.name === name) + } + + if (!useSocket) { + useSocket = sockets[0] + } + + if (!useSocket.name) { + useSocket.name = 'dflt' + } + + if (!useSocket.url) { + warn( + `URL not defined for socket "${useSocket.name}". Defaulting to "window.location"` + ) + } + + if (!useSocket.registeredWatchers) { + useSocket.registeredWatchers = [] + } + + if (!useSocket.registeredVuexListeners) { + useSocket.registeredVuexListeners = [] + } + + let { url: connectUrl } = useSocket + if (connectUrl) { + connectUrl += channel + } + + const vuexOpts = vuex || useSocket.vuex + const { namespaces = {} } = useSocket + + let socket + const label = + persist && typeof persist === 'string' + ? persist + : `${useSocket.name}${channel}` + + if (!store.state.$nuxtSocket) { + debug('vuex store $nuxtSocket does not exist....registering it') + register.vuexModule({ store }) + } + + if (emitTimeout) { + store.commit('$nuxtSocket/SET_EMIT_TIMEOUT', { label, emitTimeout }) + } + + function connectSocket() { + if (connectUrl) { + socket = io(connectUrl, connectOpts) + infoMsgs('[nuxt-socket-io]: connect', useSocket.name, connectUrl, connectOpts) + } else { + socket = io(channel, connectOpts) + infoMsgs( + '[nuxt-socket-io]: connect', + useSocket.name, + window.location, + channel, + connectOpts + ) + } + } + + if (persist) { + if (_sockets[label]) { + debug(`resuing persisted socket ${label}`) + socket = _sockets[label] + if (socket.disconnected) { + debug('persisted socket disconnected, reconnecting...') + connectSocket() + } + } else { + debug(`socket ${label} does not exist, creating and connecting to it..`) + connectSocket() + _sockets[label] = socket + } + } else { + connectSocket() + } + + const _namespaceCfg = namespaceCfg || namespaces[channel] + if (_namespaceCfg) { + register.namespace({ + ctx: this, + namespace: channel, + namespaceCfg: _namespaceCfg, + socket, + useSocket, + emitTimeout, + emitErrorsProp + }) + debug('namespaces configured for socket', { + name: useSocket.name, + channel, + namespaceCfg + }) + } + + if (serverAPI) { + register.serverAPI({ + store, + label, + apiIgnoreEvts, + ioApiProp, + ioDataProp, + ctx: this, + socket, + emitTimeout, + emitErrorsProp, + serverAPI, + clientAPI + }) + } + + if (clientAPI) { + register.clientAPI({ + ctx: this, + store, + socket, + clientAPI + }) + } + + if (vuexOpts) { + register.vuexOpts({ + ctx: this, + vuexOpts, + useSocket, + socket, + store + }) + debug('vuexOpts configured for socket', { name: useSocket.name, vuexOpts }) + } + + if ( + this.socketStatus !== undefined && + typeof this.socketStatus === 'object' + ) { + register.socketStatus({ ctx: this, socket, connectUrl, statusProp }) + debug('socketStatus registered for socket', { + name: useSocket.name, + url: connectUrl + }) + } + + if (teardown) { + register.teardown({ + ctx: this, + socket, + useSocket + }) + } + _pOptions.set({ sockets }) + return socket +} + +export default function(context, inject) { + inject('nuxtSocket', nuxtSocket) +} + +export let pOptions +if (process.env.TEST) { + pOptions = {} + Object.assign(pOptions, _pOptions) +} diff --git a/client/.nuxt/router.js b/client/.nuxt/router.js new file mode 100644 index 00000000..4dfb9cc7 --- /dev/null +++ b/client/.nuxt/router.js @@ -0,0 +1,68 @@ +import Vue from 'vue' +import Router from 'vue-router' +import { normalizeURL, decode } from 'ufo' +import { interopDefault } from './utils' +import scrollBehavior from './router.scrollBehavior.js' + +const _e09ac034 = () => interopDefault(import('..\\pages\\config\\index.vue' /* webpackChunkName: "pages/config/index" */)) +const _4bf07cff = () => interopDefault(import('..\\pages\\login.vue' /* webpackChunkName: "pages/login" */)) +const _4885a1ad = () => interopDefault(import('..\\pages\\audiobook\\_id\\index.vue' /* webpackChunkName: "pages/audiobook/_id/index" */)) +const _73d517ff = () => interopDefault(import('..\\pages\\audiobook\\_id\\edit.vue' /* webpackChunkName: "pages/audiobook/_id/edit" */)) +const _fb6e4c30 = () => interopDefault(import('..\\pages\\index.vue' /* webpackChunkName: "pages/index" */)) + +const emptyFn = () => {} + +Vue.use(Router) + +export const routerOptions = { + mode: 'history', + base: '/', + linkActiveClass: 'nuxt-link-active', + linkExactActiveClass: 'nuxt-link-exact-active', + scrollBehavior, + + routes: [{ + path: "/config", + component: _e09ac034, + name: "config" + }, { + path: "/login", + component: _4bf07cff, + name: "login" + }, { + path: "/audiobook/:id", + component: _4885a1ad, + name: "audiobook-id" + }, { + path: "/audiobook/:id?/edit", + component: _73d517ff, + name: "audiobook-id-edit" + }, { + path: "/", + component: _fb6e4c30, + name: "index" + }], + + fallback: false +} + +export function createRouter (ssrContext, config) { + const base = (config._app && config._app.basePath) || routerOptions.base + const router = new Router({ ...routerOptions, base }) + + // TODO: remove in Nuxt 3 + const originalPush = router.push + router.push = function push (location, onComplete = emptyFn, onAbort) { + return originalPush.call(this, location, onComplete, onAbort) + } + + const resolve = router.resolve.bind(router) + router.resolve = (to, current, append) => { + if (typeof to === 'string') { + to = normalizeURL(to) + } + return resolve(to, current, append) + } + + return router +} diff --git a/client/.nuxt/router.scrollBehavior.js b/client/.nuxt/router.scrollBehavior.js new file mode 100644 index 00000000..4d42dcc7 --- /dev/null +++ b/client/.nuxt/router.scrollBehavior.js @@ -0,0 +1,76 @@ +import { getMatchedComponents, setScrollRestoration } from './utils' + +if (process.client) { + if ('scrollRestoration' in window.history) { + setScrollRestoration('manual') + + // reset scrollRestoration to auto when leaving page, allowing page reload + // and back-navigation from other pages to use the browser to restore the + // scrolling position. + window.addEventListener('beforeunload', () => { + setScrollRestoration('auto') + }) + + // Setting scrollRestoration to manual again when returning to this page. + window.addEventListener('load', () => { + setScrollRestoration('manual') + }) + } +} + +function shouldScrollToTop(route) { + const Pages = getMatchedComponents(route) + if (Pages.length === 1) { + const { options = {} } = Pages[0] + return options.scrollToTop !== false + } + return Pages.some(({ options }) => options && options.scrollToTop) +} + +export default function (to, from, savedPosition) { + // If the returned position is falsy or an empty object, will retain current scroll position + let position = false + const isRouteChanged = to !== from + + // savedPosition is only available for popstate navigations (back button) + if (savedPosition) { + position = savedPosition + } else if (isRouteChanged && shouldScrollToTop(to)) { + position = { x: 0, y: 0 } + } + + const nuxt = window.$nuxt + + if ( + // Initial load (vuejs/vue-router#3199) + !isRouteChanged || + // Route hash changes + (to.path === from.path && to.hash !== from.hash) + ) { + nuxt.$nextTick(() => nuxt.$emit('triggerScroll')) + } + + return new Promise((resolve) => { + // wait for the out transition to complete (if necessary) + nuxt.$once('triggerScroll', () => { + // coords will be used if no selector is provided, + // or if the selector didn't match any element. + if (to.hash) { + let hash = to.hash + // CSS.escape() is not supported with IE and Edge. + if (typeof window.CSS !== 'undefined' && typeof window.CSS.escape !== 'undefined') { + hash = '#' + window.CSS.escape(hash.substr(1)) + } + try { + if (document.querySelector(hash)) { + // scroll to anchor by returning the selector + position = { selector: hash } + } + } catch (e) { + console.warn('Failed to save scroll position. Please add CSS.escape() polyfill (https://github.com/mathiasbynens/CSS.escape).') + } + } + resolve(position) + }) + }) +} diff --git a/client/.nuxt/routes.json b/client/.nuxt/routes.json new file mode 100644 index 00000000..a48f0bbd --- /dev/null +++ b/client/.nuxt/routes.json @@ -0,0 +1,37 @@ +[ + { + "name": "config", + "path": "/config", + "component": "C:\\\\Users\\\\Coop\\\\Documents\\\\NodeProjects\\\\audiobookshelf\\\\client\\\\pages\\\\config\\\\index.vue", + "chunkName": "pages/config/index", + "_name": "_e09ac034" + }, + { + "name": "login", + "path": "/login", + "component": "C:\\\\Users\\\\Coop\\\\Documents\\\\NodeProjects\\\\audiobookshelf\\\\client\\\\pages\\\\login.vue", + "chunkName": "pages/login", + "_name": "_4bf07cff" + }, + { + "name": "audiobook-id", + "path": "/audiobook/:id", + "component": "C:\\\\Users\\\\Coop\\\\Documents\\\\NodeProjects\\\\audiobookshelf\\\\client\\\\pages\\\\audiobook\\\\_id\\\\index.vue", + "chunkName": "pages/audiobook/_id/index", + "_name": "_4885a1ad" + }, + { + "name": "audiobook-id-edit", + "path": "/audiobook/:id?/edit", + "component": "C:\\\\Users\\\\Coop\\\\Documents\\\\NodeProjects\\\\audiobookshelf\\\\client\\\\pages\\\\audiobook\\\\_id\\\\edit.vue", + "chunkName": "pages/audiobook/_id/edit", + "_name": "_73d517ff" + }, + { + "name": "index", + "path": "/", + "component": "C:\\\\Users\\\\Coop\\\\Documents\\\\NodeProjects\\\\audiobookshelf\\\\client\\\\pages\\\\index.vue", + "chunkName": "pages/index", + "_name": "_fb6e4c30" + } +] diff --git a/client/.nuxt/server.js b/client/.nuxt/server.js new file mode 100644 index 00000000..63f660b0 --- /dev/null +++ b/client/.nuxt/server.js @@ -0,0 +1,312 @@ +import Vue from 'vue' +import { joinURL, normalizeURL, withQuery } from 'ufo' +import fetch from 'node-fetch' +import middleware from './middleware.js' +import { + applyAsyncData, + middlewareSeries, + sanitizeComponent, + getMatchedComponents, + promisify +} from './utils.js' +import fetchMixin from './mixins/fetch.server' +import { createApp, NuxtError } from './index.js' +import NuxtLink from './components/nuxt-link.server.js' // should be included after ./index.js + +// Update serverPrefetch strategy +Vue.config.optionMergeStrategies.serverPrefetch = Vue.config.optionMergeStrategies.created + +// Fetch mixin +if (!Vue.__nuxt__fetch__mixin__) { + Vue.mixin(fetchMixin) + Vue.__nuxt__fetch__mixin__ = true +} + +if (!Vue.__original_use__) { + Vue.__original_use__ = Vue.use + Vue.__install_times__ = 0 + Vue.use = function (plugin, ...args) { + plugin.__nuxt_external_installed__ = Vue._installedPlugins.includes(plugin) + return Vue.__original_use__(plugin, ...args) + } +} +if (Vue.__install_times__ === 2) { + Vue.__install_times__ = 0 + Vue._installedPlugins = Vue._installedPlugins.filter(plugin => { + return plugin.__nuxt_external_installed__ === true + }) +} +Vue.__install_times__++ + +// Component: +Vue.component(NuxtLink.name, NuxtLink) +Vue.component('NLink', NuxtLink) + +if (!global.fetch) { global.fetch = fetch } + +const noopApp = () => new Vue({ render: h => h('div', { domProps: { id: '__nuxt' } }) }) + +const createNext = ssrContext => (opts) => { + // If static target, render on client-side + ssrContext.redirected = opts + if (ssrContext.target === 'static' || !ssrContext.res) { + ssrContext.nuxt.serverRendered = false + return + } + let fullPath = withQuery(opts.path, opts.query) + const $config = ssrContext.runtimeConfig || {} + const routerBase = ($config._app && $config._app.basePath) || '/' + if (!fullPath.startsWith('http') && (routerBase !== '/' && !fullPath.startsWith(routerBase))) { + fullPath = joinURL(routerBase, fullPath) + } + // Avoid loop redirect + if (decodeURI(fullPath) === decodeURI(ssrContext.url)) { + ssrContext.redirected = false + return + } + ssrContext.res.writeHead(opts.status, { + Location: normalizeURL(fullPath) + }) + 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.{{globals.context}}, defaults to window.__NUXT__) + ssrContext.nuxt = { layout: 'default', data: [], fetch: {}, error: null, state: null, serverRendered: true, routePath: '' } + + ssrContext.fetchCounters = {} + + // Remove query from url is static target + + // Public runtime config + ssrContext.nuxt.config = ssrContext.runtimeConfig.public + if (ssrContext.nuxt.config._app) { + __webpack_public_path__ = joinURL(ssrContext.nuxt.config._app.cdnURL, ssrContext.nuxt.config._app.assetsPath) + } + // Create the app definition and the instance (created for each request) + const { app, router, store } = await createApp(ssrContext, ssrContext.runtimeConfig.private) + const _app = new Vue(app) + // Add ssr route path to nuxt context so we can account for page navigation between ssr and csr + ssrContext.nuxt.routePath = app.context.route.path + + // 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 }))) + + ssrContext.rendered = () => { + // Add the state from the vuex store + ssrContext.nuxt.state = store.state + } + } + + const renderErrorPage = async () => { + // Don't server-render the page in static target + if (ssrContext.target === 'static') { + ssrContext.nuxt.serverRendered = false + } + + // Load layout for error page + const layout = (NuxtError.options || NuxtError).layout + const errLayout = typeof layout === 'function' ? layout.call(NuxtError, app.context) : 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 = Date.now() + + // Components are already resolved by setContext -> getRouteData (app/utils.js) + const Components = getMatchedComponents(app.context.route) + + /* + ** Dispatch store nuxtServerInit + */ + if (store._actions && store._actions.nuxtServerInit) { + try { + await store.dispatch('nuxtServerInit', app.context) + } catch (err) { + console.debug('Error occurred when calling nuxtServerInit: ', err.message) + throw err + } + } + // ...If there is a redirect or an error, stop the process + if (ssrContext.redirected) { + return noopApp() + } + if (ssrContext.nuxt.error) { + return renderErrorPage() + } + + /* + ** 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) + if (ssrContext.nuxt.error) { + return renderErrorPage() + } + layout = _app.setLayout(layout) + ssrContext.nuxt.layout = _app.layoutName + + /* + ** Call middleware (layout + pages) + */ + midd = [] + + layout = sanitizeComponent(layout) + if (layout.options.middleware) { + midd = midd.concat(layout.options.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 + try { + for (const Component of Components) { + if (typeof Component.options.validate !== 'function') { + continue + } + + isValid = await Component.options.validate(app.context) + + if (!isValid) { + break + } + } + } catch (validationError) { + // ...If .validate() threw an error + app.context.error({ + statusCode: validationError.statusCode || '500', + message: validationError.message + }) + return renderErrorPage() + } + + // ...If .validate() returned false + if (!isValid) { + // 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. + const asyncDatas = await Promise.all(Components.map((Component) => { + const promises = [] + + // Call asyncData(context) + if (Component.options.asyncData && typeof Component.options.asyncData === 'function') { + const 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 && Component.options.fetch.length) { + promises.push(Component.options.fetch(app.context)) + } else { + promises.push(null) + } + + return Promise.all(promises) + })) + + if (process.env.DEBUG && asyncDatas.length) console.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 +} diff --git a/client/.nuxt/store.js b/client/.nuxt/store.js new file mode 100644 index 00000000..ca03d15a --- /dev/null +++ b/client/.nuxt/store.js @@ -0,0 +1,146 @@ +import Vue from 'vue' +import Vuex from 'vuex' + +Vue.use(Vuex) + +const VUEX_PROPERTIES = ['state', 'getters', 'actions', 'mutations'] + +let store = {}; + +(function updateModules () { + store = normalizeRoot(require('..\\store\\index.js'), 'store/index.js') + + // If store is an exported method = classic mode (deprecated) + + if (typeof store === 'function') { + return console.warn('Classic mode for store/ is deprecated and will be removed in Nuxt 3.') + } + + // Enforce store modules + store.modules = store.modules || {} + + resolveStoreModules(require('..\\store\\audiobooks.js'), 'audiobooks.js') + + // If the environment supports hot reloading... + + if (process.client && module.hot) { + // Whenever any Vuex module is updated... + module.hot.accept([ + '..\\store\\audiobooks.js', + '..\\store\\index.js', + ], () => { + // Update `root.modules` with the latest definitions. + updateModules() + // Trigger a hot update in the store. + window.$nuxt.$store.hotUpdate(store) + }) + } +})() + +// createStore +export const createStore = store instanceof Function ? store : () => { + return new Vuex.Store(Object.assign({ + strict: (process.env.NODE_ENV !== 'production') + }, store)) +} + +function normalizeRoot (moduleData, filePath) { + moduleData = moduleData.default || moduleData + + if (moduleData.commit) { + throw new Error(`[nuxt] ${filePath} should export a method that returns a Vuex instance.`) + } + + if (typeof moduleData !== 'function') { + // Avoid TypeError: setting a property that has only a getter when overwriting top level keys + moduleData = Object.assign({}, moduleData) + } + return normalizeModule(moduleData, filePath) +} + +function normalizeModule (moduleData, filePath) { + if (moduleData.state && typeof moduleData.state !== 'function') { + console.warn(`'state' should be a method that returns an object in ${filePath}`) + + const state = Object.assign({}, moduleData.state) + // Avoid TypeError: setting a property that has only a getter when overwriting top level keys + moduleData = Object.assign({}, moduleData, { state: () => state }) + } + return moduleData +} + +function resolveStoreModules (moduleData, filename) { + moduleData = moduleData.default || moduleData + // Remove store src + extension (./foo/index.js -> foo/index) + const namespace = filename.replace(/\.(js|mjs)$/, '') + const namespaces = namespace.split('/') + let moduleName = namespaces[namespaces.length - 1] + const filePath = `store/${filename}` + + moduleData = moduleName === 'state' + ? normalizeState(moduleData, filePath) + : normalizeModule(moduleData, filePath) + + // If src is a known Vuex property + if (VUEX_PROPERTIES.includes(moduleName)) { + const property = moduleName + const propertyStoreModule = getStoreModule(store, namespaces, { isProperty: true }) + + // Replace state since it's a function + mergeProperty(propertyStoreModule, moduleData, property) + return + } + + // If file is foo/index.js, it should be saved as foo + const isIndexModule = (moduleName === 'index') + if (isIndexModule) { + namespaces.pop() + moduleName = namespaces[namespaces.length - 1] + } + + const storeModule = getStoreModule(store, namespaces) + + for (const property of VUEX_PROPERTIES) { + mergeProperty(storeModule, moduleData[property], property) + } + + if (moduleData.namespaced === false) { + delete storeModule.namespaced + } +} + +function normalizeState (moduleData, filePath) { + if (typeof moduleData !== 'function') { + console.warn(`${filePath} should export a method that returns an object`) + const state = Object.assign({}, moduleData) + return () => state + } + return normalizeModule(moduleData, filePath) +} + +function getStoreModule (storeModule, namespaces, { isProperty = false } = {}) { + // If ./mutations.js + if (!namespaces.length || (isProperty && namespaces.length === 1)) { + return storeModule + } + + const namespace = namespaces.shift() + + storeModule.modules[namespace] = storeModule.modules[namespace] || {} + storeModule.modules[namespace].namespaced = true + storeModule.modules[namespace].modules = storeModule.modules[namespace].modules || {} + + return getStoreModule(storeModule.modules[namespace], namespaces, { isProperty }) +} + +function mergeProperty (storeModule, moduleData, property) { + if (!moduleData) { + return + } + + if (property === 'state') { + storeModule.state = moduleData || storeModule.state + } else { + storeModule[property] = Object.assign({}, storeModule[property], moduleData) + } +} diff --git a/client/.nuxt/utils.js b/client/.nuxt/utils.js new file mode 100644 index 00000000..d7754788 --- /dev/null +++ b/client/.nuxt/utils.js @@ -0,0 +1,630 @@ +import Vue from 'vue' +import { isSamePath as _isSamePath, joinURL, normalizeURL, withQuery, withoutTrailingSlash } from 'ufo' + +// window.{{globals.loadedCallback}} hook +// Useful for jsdom testing or plugins (https://github.com/tmpvar/jsdom#dealing-with-asynchronous-script-loading) +if (process.client) { + window.onNuxtReadyCbs = [] + window.onNuxtReady = (cb) => { + window.onNuxtReadyCbs.push(cb) + } +} + +export function createGetCounter (counterObject, defaultKey = '') { + return function getCounter (id = defaultKey) { + if (counterObject[id] === undefined) { + counterObject[id] = 0 + } + return counterObject[id]++ + } +} + +export function empty () {} + +export function globalHandleError (error) { + if (Vue.config.errorHandler) { + Vue.config.errorHandler(error) + } +} + +export function interopDefault (promise) { + return promise.then(m => m.default || m) +} + +export function hasFetch(vm) { + return vm.$options && typeof vm.$options.fetch === 'function' && !vm.$options.fetch.length +} +export function purifyData(data) { + if (process.env.NODE_ENV === 'production') { + return data + } + + return Object.entries(data).filter( + ([key, value]) => { + const valid = !(value instanceof Function) && !(value instanceof Promise) + if (!valid) { + console.warn(`${key} is not able to be stringified. This will break in a production environment.`) + } + return valid + } + ).reduce((obj, [key, value]) => { + obj[key] = value + return obj + }, {}) +} +export function getChildrenComponentInstancesUsingFetch(vm, instances = []) { + const children = vm.$children || [] + for (const child of children) { + if (child.$fetch) { + instances.push(child) + continue; // Don't get the children since it will reload the template + } + if (child.$children) { + getChildrenComponentInstancesUsingFetch(child, instances) + } + } + return instances +} + +export function applyAsyncData (Component, asyncData) { + if ( + // For SSR, we once all this function without second param to just apply asyncData + // Prevent doing this for each SSR request + !asyncData && Component.options.__hasNuxtData + ) { + return + } + + const ComponentData = Component.options._originDataFn || Component.options.data || function () { return {} } + Component.options._originDataFn = ComponentData + + Component.options.data = function () { + const data = ComponentData.call(this, this) + if (this.$ssrContext) { + asyncData = this.$ssrContext.asyncData[Component.cid] + } + return { ...data, ...asyncData } + } + + Component.options.__hasNuxtData = true + + if (Component._Ctor && Component._Ctor.options) { + Component._Ctor.options.data = Component.options.data + } +} + +export function sanitizeComponent (Component) { + // If Component already sanitized + if (Component.options && Component._Ctor === Component) { + return Component + } + if (!Component.options) { + Component = Vue.extend(Component) // fix issue #6 + Component._Ctor = Component + } else { + Component._Ctor = Component + Component.extendOptions = Component.options + } + // If no component name defined, set file path as name, (also fixes #5703) + if (!Component.options.name && Component.options.__file) { + Component.options.name = Component.options.__file + } + return Component +} + +export function getMatchedComponents (route, matches = false, prop = 'components') { + return Array.prototype.concat.apply([], route.matched.map((m, index) => { + return Object.keys(m[prop]).map((key) => { + matches && matches.push(index) + return m[prop][key] + }) + })) +} + +export function getMatchedComponentsInstances (route, matches = false) { + return getMatchedComponents(route, matches, 'instances') +} + +export function flatMapComponents (route, fn) { + return Array.prototype.concat.apply([], route.matched.map((m, index) => { + return Object.keys(m.components).reduce((promises, key) => { + if (m.components[key]) { + promises.push(fn(m.components[key], m.instances[key], m, key, index)) + } else { + delete m.components[key] + } + return promises + }, []) + })) +} + +export function resolveRouteComponents (route, fn) { + return Promise.all( + flatMapComponents(route, async (Component, instance, match, key) => { + // If component is a function, resolve it + if (typeof Component === 'function' && !Component.options) { + try { + Component = await Component() + } catch (error) { + // Handle webpack chunk loading errors + // This may be due to a new deployment or a network problem + if ( + error && + error.name === 'ChunkLoadError' && + typeof window !== 'undefined' && + window.sessionStorage + ) { + const timeNow = Date.now() + const previousReloadTime = parseInt(window.sessionStorage.getItem('nuxt-reload')) + + // check for previous reload time not to reload infinitely + if (!previousReloadTime || previousReloadTime + 60000 < timeNow) { + window.sessionStorage.setItem('nuxt-reload', timeNow) + window.location.reload(true /* skip cache */) + } + } + + throw error + } + } + match.components[key] = Component = sanitizeComponent(Component) + return typeof fn === 'function' ? fn(Component, instance, match, key) : Component + }) + ) +} + +export async function getRouteData (route) { + if (!route) { + return + } + // Make sure the components are resolved (code-splitting) + await resolveRouteComponents(route) + // Send back a copy of route with meta based on Component definition + return { + ...route, + meta: getMatchedComponents(route).map((Component, index) => { + return { ...Component.options.meta, ...(route.matched[index] || {}).meta } + }) + } +} + +export async function setContext (app, context) { + // If context not defined, create it + if (!app.context) { + app.context = { + isStatic: process.static, + isDev: true, + isHMR: false, + app, + store: app.store, + payload: context.payload, + error: context.error, + base: app.router.options.base, + env: {"serverUrl":"http://localhost:3333","baseUrl":"http://0.0.0.0"} + } + // Only set once + + if (context.req) { + app.context.req = context.req + } + if (context.res) { + app.context.res = context.res + } + + if (context.ssrContext) { + app.context.ssrContext = context.ssrContext + } + app.context.redirect = (status, path, query) => { + if (!status) { + return + } + app.context._redirected = true + // if only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' }) + let pathType = typeof path + if (typeof status !== 'number' && (pathType === 'undefined' || pathType === 'object')) { + query = path || {} + path = status + pathType = typeof path + status = 302 + } + if (pathType === 'object') { + path = app.router.resolve(path).route.fullPath + } + // "/absolute/route", "./relative/route" or "../relative/route" + if (/(^[.]{1,2}\/)|(^\/(?!\/))/.test(path)) { + app.context.next({ + path, + query, + status + }) + } else { + path = withQuery(path, query) + if (process.server) { + app.context.next({ + path, + status + }) + } + if (process.client) { + // https://developer.mozilla.org/en-US/docs/Web/API/Location/replace + window.location.replace(path) + + // Throw a redirect error + throw new Error('ERR_REDIRECT') + } + } + } + if (process.server) { + app.context.beforeNuxtRender = fn => context.beforeRenderFns.push(fn) + } + if (process.client) { + app.context.nuxtState = window.__NUXT__ + } + } + + // Dynamic keys + const [currentRouteData, fromRouteData] = await Promise.all([ + getRouteData(context.route), + getRouteData(context.from) + ]) + + if (context.route) { + app.context.route = currentRouteData + } + + if (context.from) { + app.context.from = fromRouteData + } + + app.context.next = context.next + app.context._redirected = false + app.context._errored = false + app.context.isHMR = Boolean(context.isHMR) + app.context.params = app.context.route.params || {} + app.context.query = app.context.route.query || {} +} + +export function middlewareSeries (promises, appContext) { + if (!promises.length || appContext._redirected || appContext._errored) { + return Promise.resolve() + } + return promisify(promises[0], appContext) + .then(() => { + return middlewareSeries(promises.slice(1), appContext) + }) +} + +export function promisify (fn, context) { + let promise + if (fn.length === 2) { + console.warn('Callback-based asyncData, fetch or middleware calls are deprecated. ' + + 'Please switch to promises or async/await syntax') + + // fn(context, callback) + promise = new Promise((resolve) => { + fn(context, function (err, data) { + if (err) { + context.error(err) + } + data = data || {} + resolve(data) + }) + }) + } else { + promise = fn(context) + } + + if (promise && promise instanceof Promise && typeof promise.then === 'function') { + return promise + } + return Promise.resolve(promise) +} + +// Imported from vue-router +export function getLocation (base, mode) { + if (mode === 'hash') { + return window.location.hash.replace(/^#\//, '') + } + + base = decodeURI(base).slice(0, -1) // consideration is base is normalized with trailing slash + let path = decodeURI(window.location.pathname) + + if (base && path.startsWith(base)) { + path = path.slice(base.length) + } + + const fullPath = (path || '/') + window.location.search + window.location.hash + + return normalizeURL(fullPath) +} + +// Imported from path-to-regexp + +/** + * Compile a string to a template function for the path. + * + * @param {string} str + * @param {Object=} options + * @return {!function(Object=, Object=)} + */ +export function compile (str, options) { + return tokensToFunction(parse(str, options), options) +} + +export function getQueryDiff (toQuery, fromQuery) { + const diff = {} + const queries = { ...toQuery, ...fromQuery } + for (const k in queries) { + if (String(toQuery[k]) !== String(fromQuery[k])) { + diff[k] = true + } + } + return diff +} + +export function normalizeError (err) { + let message + if (!(err.message || typeof err === 'string')) { + try { + message = JSON.stringify(err, null, 2) + } catch (e) { + message = `[${err.constructor.name}]` + } + } else { + message = err.message || err + } + return { + ...err, + message, + statusCode: (err.statusCode || err.status || (err.response && err.response.status) || 500) + } +} + +/** + * The main path matching regexp utility. + * + * @type {RegExp} + */ +const PATH_REGEXP = new RegExp([ + // Match escaped characters that would otherwise appear in future matches. + // This allows the user to escape special characters that won't transform. + '(\\\\.)', + // Match Express-style parameters and un-named parameters with a prefix + // and optional suffixes. Matches appear as: + // + // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined] + // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined] + // "/*" => ["/", undefined, undefined, undefined, undefined, "*"] + '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))' +].join('|'), 'g') + +/** + * Parse a string for the raw tokens. + * + * @param {string} str + * @param {Object=} options + * @return {!Array} + */ +function parse (str, options) { + const tokens = [] + let key = 0 + let index = 0 + let path = '' + const defaultDelimiter = (options && options.delimiter) || '/' + let res + + while ((res = PATH_REGEXP.exec(str)) != null) { + const m = res[0] + const escaped = res[1] + const offset = res.index + path += str.slice(index, offset) + index = offset + m.length + + // Ignore already escaped sequences. + if (escaped) { + path += escaped[1] + continue + } + + const next = str[index] + const prefix = res[2] + const name = res[3] + const capture = res[4] + const group = res[5] + const modifier = res[6] + const asterisk = res[7] + + // Push the current path onto the tokens. + if (path) { + tokens.push(path) + path = '' + } + + const partial = prefix != null && next != null && next !== prefix + const repeat = modifier === '+' || modifier === '*' + const optional = modifier === '?' || modifier === '*' + const delimiter = res[2] || defaultDelimiter + const pattern = capture || group + + tokens.push({ + name: name || key++, + prefix: prefix || '', + delimiter, + optional, + repeat, + partial, + asterisk: Boolean(asterisk), + pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?') + }) + } + + // Match any characters still remaining. + if (index < str.length) { + path += str.substr(index) + } + + // If the path exists, push it onto the end. + if (path) { + tokens.push(path) + } + + return tokens +} + +/** + * Prettier encoding of URI path segments. + * + * @param {string} + * @return {string} + */ +function encodeURIComponentPretty (str, slashAllowed) { + const re = slashAllowed ? /[?#]/g : /[/?#]/g + return encodeURI(str).replace(re, (c) => { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} + +/** + * Encode the asterisk parameter. Similar to `pretty`, but allows slashes. + * + * @param {string} + * @return {string} + */ +function encodeAsterisk (str) { + return encodeURIComponentPretty(str, true) +} + +/** + * Escape a regular expression string. + * + * @param {string} str + * @return {string} + */ +function escapeString (str) { + return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1') +} + +/** + * Escape the capturing group by escaping special characters and meaning. + * + * @param {string} group + * @return {string} + */ +function escapeGroup (group) { + return group.replace(/([=!:$/()])/g, '\\$1') +} + +/** + * Expose a method for transforming tokens into the path function. + */ +function tokensToFunction (tokens, options) { + // Compile all the tokens into regexps. + const matches = new Array(tokens.length) + + // Compile all the patterns before compilation. + for (let i = 0; i < tokens.length; i++) { + if (typeof tokens[i] === 'object') { + matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options)) + } + } + + return function (obj, opts) { + let path = '' + const data = obj || {} + const options = opts || {} + const encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i] + + if (typeof token === 'string') { + path += token + + continue + } + + const value = data[token.name || 'pathMatch'] + let segment + + if (value == null) { + if (token.optional) { + // Prepend partial segment prefixes. + if (token.partial) { + path += token.prefix + } + + continue + } else { + throw new TypeError('Expected "' + token.name + '" to be defined') + } + } + + if (Array.isArray(value)) { + if (!token.repeat) { + throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`') + } + + if (value.length === 0) { + if (token.optional) { + continue + } else { + throw new TypeError('Expected "' + token.name + '" to not be empty') + } + } + + for (let j = 0; j < value.length; j++) { + segment = encode(value[j]) + + if (!matches[i].test(segment)) { + throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`') + } + + path += (j === 0 ? token.prefix : token.delimiter) + segment + } + + continue + } + + segment = token.asterisk ? encodeAsterisk(value) : encode(value) + + if (!matches[i].test(segment)) { + throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"') + } + + path += token.prefix + segment + } + + return path + } +} + +/** + * Get the flags for a regexp from the options. + * + * @param {Object} options + * @return {string} + */ +function flags (options) { + return options && options.sensitive ? '' : 'i' +} + +export function addLifecycleHook(vm, hook, fn) { + if (!vm.$options[hook]) { + vm.$options[hook] = [] + } + if (!vm.$options[hook].includes(fn)) { + vm.$options[hook].push(fn) + } +} + +export const urlJoin = joinURL + +export const stripTrailingSlash = withoutTrailingSlash + +export const isSamePath = _isSamePath + +export function setScrollRestoration (newVal) { + try { + window.history.scrollRestoration = newVal; + } catch(e) {} +} diff --git a/client/.nuxt/vetur/tags.json b/client/.nuxt/vetur/tags.json new file mode 100644 index 00000000..a0578d25 --- /dev/null +++ b/client/.nuxt/vetur/tags.json @@ -0,0 +1,71 @@ +{ + "AudioPlayer": { + "description": "Auto imported from components/AudioPlayer.vue" + }, + "AppAppbar": { + "description": "Auto imported from components/app/Appbar.vue" + }, + "AppBookShelf": { + "description": "Auto imported from components/app/BookShelf.vue" + }, + "AppStreamContainer": { + "description": "Auto imported from components/app/StreamContainer.vue" + }, + "AppTracksTable": { + "description": "Auto imported from components/app/TracksTable.vue" + }, + "CardsBookCard": { + "description": "Auto imported from components/cards/BookCard.vue" + }, + "CardsBookCover": { + "description": "Auto imported from components/cards/BookCover.vue" + }, + "ControlsVolumeControl": { + "description": "Auto imported from components/controls/VolumeControl.vue" + }, + "ModalsEditModal": { + "description": "Auto imported from components/modals/EditModal.vue" + }, + "ModalsModal": { + "description": "Auto imported from components/modals/Modal.vue" + }, + "UiBtn": { + "description": "Auto imported from components/ui/Btn.vue" + }, + "UiLoadingIndicator": { + "description": "Auto imported from components/ui/LoadingIndicator.vue" + }, + "UiMenu": { + "description": "Auto imported from components/ui/Menu.vue" + }, + "UiTextareaInput": { + "description": "Auto imported from components/ui/TextareaInput.vue" + }, + "UiTextareaWithLabel": { + "description": "Auto imported from components/ui/TextareaWithLabel.vue" + }, + "UiTextInput": { + "description": "Auto imported from components/ui/TextInput.vue" + }, + "UiTextInputWithLabel": { + "description": "Auto imported from components/ui/TextInputWithLabel.vue" + }, + "UiTooltip": { + "description": "Auto imported from components/ui/Tooltip.vue" + }, + "WidgetsScanAlert": { + "description": "Auto imported from components/widgets/ScanAlert.vue" + }, + "ModalsEditTabsCover": { + "description": "Auto imported from components/modals/edit-tabs/Cover.vue" + }, + "ModalsEditTabsDetails": { + "description": "Auto imported from components/modals/edit-tabs/Details.vue" + }, + "ModalsEditTabsMatch": { + "description": "Auto imported from components/modals/edit-tabs/Match.vue" + }, + "ModalsEditTabsTracks": { + "description": "Auto imported from components/modals/edit-tabs/Tracks.vue" + } +} diff --git a/client/.nuxt/views/app.template.html b/client/.nuxt/views/app.template.html new file mode 100644 index 00000000..3427d3ea --- /dev/null +++ b/client/.nuxt/views/app.template.html @@ -0,0 +1,9 @@ + + + + {{ HEAD }} + + + {{ APP }} + + diff --git a/client/.nuxt/views/error.html b/client/.nuxt/views/error.html new file mode 100644 index 00000000..082a41fc --- /dev/null +++ b/client/.nuxt/views/error.html @@ -0,0 +1,23 @@ + + + +Server error + + + + + +
+
+ +
Server error
+
{{ message }}
+
+ +
+ + diff --git a/client/assets/app.css b/client/assets/app.css new file mode 100644 index 00000000..e6ab6a4d --- /dev/null +++ b/client/assets/app.css @@ -0,0 +1,52 @@ +@import url('./transitions.css'); + +.page { + width: 100%; + height: calc(100% - 64px); + max-height: calc(100% - 64px); +} +.page.streaming { + height: calc(100% - 64px - 165px); + max-height: calc(100% - 64px - 165px); +} + +/* width */ +::-webkit-scrollbar { + width: 8px; +} +/* Track */ +::-webkit-scrollbar-track { + background-color: rgba(0,0,0,0); +} +/* Handle */ +::-webkit-scrollbar-thumb { + background: #855620; + border-radius: 4px; +} +/* Handle on hover */ +::-webkit-scrollbar-thumb:hover { + background: #704922; +} + + +.tracksTable { + border-collapse: collapse; + width: 100%; + border: 1px solid #474747; +} +.tracksTable tr:nth-child(even) { + background-color: #2e2e2e; +} +.tracksTable tr { + background-color: #373838; +} +.tracksTable tr:hover { + background-color: #474747; +} +.tracksTable td { + padding: 4px; +} +.tracksTable th { + padding: 4px; + font-size: 0.75rem; +} \ No newline at end of file diff --git a/client/assets/transitions.css b/client/assets/transitions.css new file mode 100644 index 00000000..e8075c02 --- /dev/null +++ b/client/assets/transitions.css @@ -0,0 +1,47 @@ +.slide-enter-active { + -moz-transition-duration: 0.1s; + -webkit-transition-duration: 0.1s; + -o-transition-duration: 0.1s; + transition-duration: 0.1s; + -moz-transition-timing-function: ease-in; + -webkit-transition-timing-function: ease-in; + -o-transition-timing-function: ease-in; + transition-timing-function: ease-in; +} + +.slide-leave-active { + -moz-transition-duration: 0.2s; + -webkit-transition-duration: 0.2s; + -o-transition-duration: 0.2s; + transition-duration: 0.2s; + -moz-transition-timing-function: cubic-bezier(0, 1, 0.5, 1); + -webkit-transition-timing-function: cubic-bezier(0, 1, 0.5, 1); + -o-transition-timing-function: cubic-bezier(0, 1, 0.5, 1); + transition-timing-function: cubic-bezier(0, 1, 0.5, 1); +} + +.slide-enter-to, .slide-leave { + max-height: 600px; + overflow: hidden; +} + +.slide-enter, .slide-leave-to { + overflow: hidden; + max-height: 0; +} + + + +.menu-enter, .menu-leave-active { + transform: translateY(-15px); +} +.menu-enter-active { + transition: all 0.2s; +} +.menu-leave-active { + transition: all 0.1s; +} +.menu-enter, +.menu-leave-active { + opacity: 0; +} \ No newline at end of file diff --git a/client/components/AudioPlayer.vue b/client/components/AudioPlayer.vue new file mode 100644 index 00000000..67108fcf --- /dev/null +++ b/client/components/AudioPlayer.vue @@ -0,0 +1,435 @@ + + + + + \ No newline at end of file diff --git a/client/components/app/Appbar.vue b/client/components/app/Appbar.vue new file mode 100644 index 00000000..3ba21bfb --- /dev/null +++ b/client/components/app/Appbar.vue @@ -0,0 +1,88 @@ + + + + + \ No newline at end of file diff --git a/client/components/app/BookShelf.vue b/client/components/app/BookShelf.vue new file mode 100644 index 00000000..7408b74b --- /dev/null +++ b/client/components/app/BookShelf.vue @@ -0,0 +1,102 @@ + + + + + \ No newline at end of file diff --git a/client/components/app/StreamContainer.vue b/client/components/app/StreamContainer.vue new file mode 100644 index 00000000..85e94abe --- /dev/null +++ b/client/components/app/StreamContainer.vue @@ -0,0 +1,142 @@ + + + + + \ No newline at end of file diff --git a/client/components/app/TracksTable.vue b/client/components/app/TracksTable.vue new file mode 100644 index 00000000..e405b250 --- /dev/null +++ b/client/components/app/TracksTable.vue @@ -0,0 +1,67 @@ + + + \ No newline at end of file diff --git a/client/components/cards/BookCard.vue b/client/components/cards/BookCard.vue new file mode 100644 index 00000000..a0b39b64 --- /dev/null +++ b/client/components/cards/BookCard.vue @@ -0,0 +1,110 @@ + + + + + \ No newline at end of file diff --git a/client/components/cards/BookCover.vue b/client/components/cards/BookCover.vue new file mode 100644 index 00000000..5cc047a6 --- /dev/null +++ b/client/components/cards/BookCover.vue @@ -0,0 +1,72 @@ + + + \ No newline at end of file diff --git a/client/components/controls/VolumeControl.vue b/client/components/controls/VolumeControl.vue new file mode 100644 index 00000000..a92de3c7 --- /dev/null +++ b/client/components/controls/VolumeControl.vue @@ -0,0 +1,89 @@ + + + \ No newline at end of file diff --git a/client/components/modals/EditModal.vue b/client/components/modals/EditModal.vue new file mode 100644 index 00000000..115823c1 --- /dev/null +++ b/client/components/modals/EditModal.vue @@ -0,0 +1,86 @@ + + + \ No newline at end of file diff --git a/client/components/modals/Modal.vue b/client/components/modals/Modal.vue new file mode 100644 index 00000000..75c9b166 --- /dev/null +++ b/client/components/modals/Modal.vue @@ -0,0 +1,100 @@ + + + \ No newline at end of file diff --git a/client/components/modals/edit-tabs/Cover.vue b/client/components/modals/edit-tabs/Cover.vue new file mode 100644 index 00000000..a29d6507 --- /dev/null +++ b/client/components/modals/edit-tabs/Cover.vue @@ -0,0 +1,42 @@ + + + \ No newline at end of file diff --git a/client/components/modals/edit-tabs/Details.vue b/client/components/modals/edit-tabs/Details.vue new file mode 100644 index 00000000..5de818c8 --- /dev/null +++ b/client/components/modals/edit-tabs/Details.vue @@ -0,0 +1,135 @@ + + + \ No newline at end of file diff --git a/client/components/modals/edit-tabs/Match.vue b/client/components/modals/edit-tabs/Match.vue new file mode 100644 index 00000000..2f66cd26 --- /dev/null +++ b/client/components/modals/edit-tabs/Match.vue @@ -0,0 +1,100 @@ + + + \ No newline at end of file diff --git a/client/components/modals/edit-tabs/Tracks.vue b/client/components/modals/edit-tabs/Tracks.vue new file mode 100644 index 00000000..92572166 --- /dev/null +++ b/client/components/modals/edit-tabs/Tracks.vue @@ -0,0 +1,66 @@ + + + \ No newline at end of file diff --git a/client/components/ui/Btn.vue b/client/components/ui/Btn.vue new file mode 100644 index 00000000..5c9b47db --- /dev/null +++ b/client/components/ui/Btn.vue @@ -0,0 +1,67 @@ + + + + + \ No newline at end of file diff --git a/client/components/ui/LoadingIndicator.vue b/client/components/ui/LoadingIndicator.vue new file mode 100644 index 00000000..e5970628 --- /dev/null +++ b/client/components/ui/LoadingIndicator.vue @@ -0,0 +1,70 @@ + + + + + \ No newline at end of file diff --git a/client/components/ui/Menu.vue b/client/components/ui/Menu.vue new file mode 100644 index 00000000..402a2c3b --- /dev/null +++ b/client/components/ui/Menu.vue @@ -0,0 +1,54 @@ + + + \ No newline at end of file diff --git a/client/components/ui/TextInput.vue b/client/components/ui/TextInput.vue new file mode 100644 index 00000000..9abc8300 --- /dev/null +++ b/client/components/ui/TextInput.vue @@ -0,0 +1,47 @@ + + + + + \ No newline at end of file diff --git a/client/components/ui/TextInputWithLabel.vue b/client/components/ui/TextInputWithLabel.vue new file mode 100644 index 00000000..d10bcb22 --- /dev/null +++ b/client/components/ui/TextInputWithLabel.vue @@ -0,0 +1,31 @@ + + + \ No newline at end of file diff --git a/client/components/ui/TextareaInput.vue b/client/components/ui/TextareaInput.vue new file mode 100644 index 00000000..ab471860 --- /dev/null +++ b/client/components/ui/TextareaInput.vue @@ -0,0 +1,47 @@ +