Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Frontesque committed Feb 11, 2022
0 parents commit 79f9255
Show file tree
Hide file tree
Showing 62 changed files with 10,530 additions and 0 deletions.
28 changes: 28 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Editor config helps developers define and maintain consistent
# coding styles between different editors and IDEs
# EditorConfig is awesome: http://editorconfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_style = space
indent_size = 2

# 2 space indentation
# Matches multiple files with brace expansion notation
[*.{yaml,yml}]
indent_style = space
indent_size = 2

# https://google.github.io/styleguide/shell.xml#Indentation
[*.{sh}]
indent_style = space
indent_size = 2

[*.md]
trim_trailing_whitespace = false
3 changes: 3 additions & 0 deletions .electron-nuxt/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
require('./check-engines')
process.env.NODE_ENV = 'production'
require('./index')
89 changes: 89 additions & 0 deletions .electron-nuxt/check-engines.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
This module cannot contain any external libraries!
*/

const {engines} = require('../package');

const RESET = "\x1b[0m";
const FG_RED = "\x1b[31m";

function checkNodeVersion(){
if(engines.node === undefined) return;
const requiredMinVersion = engines.node.replace(/[=<>]/g, '');
const installedVersion = process.versions.node;
if(compare(requiredMinVersion, installedVersion) === 1){

console.log(FG_RED);
console.log(`\tYou are running version v${installedVersion} of Node.js, which is not supported by Electron-nuxt.`);
console.log(`\tThe official Node.js version that is supported is ${requiredMinVersion} or greater.`);
console.log(RESET);
console.log('\n\tPlease visit https://nodejs.org/en/ to find instructions on how to update Node.js.\n')

throw new Error('Invalid node version');
}
}

//https://github.com/yarnpkg/yarn/issues/5063
function disallowNpm() {
const execPath = process.env.npm_execpath;
if(!execPath.includes('yarn')){

console.log(FG_RED);
console.log(`\tElectron-nuxt supports only Yarn package manager.`);
console.log(RESET);
console.log('\n\tPlease visit https://legacy.yarnpkg.com/en/docs/install to find instructions on how to install Yarn.\n')

throw new Error('Invalid package manager');
}
}


//https://stackoverflow.com/questions/6832596/how-to-compare-software-version-number-using-js-only-number
// Return 1 if a > b
// Return -1 if a < b
// Return 0 if a == b
function compare(a, b) {
if (a === b) {
return 0;
}

const a_components = a.split(".");
const b_components = b.split(".");

const len = Math.min(a_components.length, b_components.length);

// loop while the components are equal
for (let i = 0; i < len; i++) {
// A bigger than B
if (parseInt(a_components[i]) > parseInt(b_components[i])) {
return 1;
}

// B bigger than A
if (parseInt(a_components[i]) < parseInt(b_components[i])) {
return -1;
}
}

// If one's a prefix of the other, the longer one is greater.
if (a_components.length > b_components.length) {
return 1;
}

if (a_components.length < b_components.length) {
return -1;
}

// Otherwise they are the same.
return 0;
}

try{
checkNodeVersion();
disallowNpm();
// https://stackoverflow.com/questions/6398196/detect-if-called-through-require-or-directly-by-command-line
if (require.main === module) process.exit(0);
}catch (e) {
process.exit(1);
}

23 changes: 23 additions & 0 deletions .electron-nuxt/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const path = require('path')

const PROJECT_ROOT = path.join(__dirname, '..')
const SRC_DIR = path.join(PROJECT_ROOT, 'src')

const config = {
ELECTRON_RELAUNCH_CODE: 250, // valid range in unix system: <1,255>
ELECTRON_INSPECTION_PORT: 5858,
SERVER_PORT: 9080,
SERVER_HOST: 'http://localhost',

PROJECT_ROOT,
SRC_DIR,
MAIN_PROCESS_DIR: path.join(SRC_DIR, 'main'),
RENDERER_PROCESS_DIR: path.join(SRC_DIR, 'renderer'),
RESOURCES_DIR: path.join(SRC_DIR, 'extraResources'),
DIST_DIR: path.join(PROJECT_ROOT, 'dist'),
BUILD_DIR: path.join(PROJECT_ROOT, 'build'),

DISABLE_BABEL_LOADER: false // experimental
}

module.exports = Object.freeze(config)
3 changes: 3 additions & 0 deletions .electron-nuxt/dev.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
require('./check-engines')
process.env.NODE_ENV = 'development'
require('./index')
68 changes: 68 additions & 0 deletions .electron-nuxt/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

const path = require('path')
const webpack = require('webpack')
const electron = require('electron')

const { Pipeline, Logger } = require('@xpda-dev/core')
const { ElectronLauncher } = require('@xpda-dev/electron-launcher')
const { ElectronBuilder } = require('@xpda-dev/electron-builder')
const { Webpack } = require('@xpda-dev/webpack-step')
const resourcesPath = require('./resources-path-provider')
const { DIST_DIR, MAIN_PROCESS_DIR, SERVER_HOST, SERVER_PORT } = require('./config')
const NuxtApp = require('./renderer/NuxtApp')

const isDev = process.env.NODE_ENV === 'development'

const electronLogger = new Logger('Electron', 'teal')
electronLogger.ignore(text => text.includes('nhdogjmejiglipccpnnnanhbledajbpd')) // Clear vue devtools errors

const launcher = new ElectronLauncher({
logger: electronLogger,
electronPath: electron,
entryFile: path.join(DIST_DIR, 'main/index.js')
})

function hasConfigArgument (array) {
for (const el of array) if (el === '--config' || el === '-c') return true
return false
}
const argumentsArray = process.argv.slice(2)
if (!hasConfigArgument(argumentsArray)) argumentsArray.push('--config', 'builder.config.js')

const builder = new ElectronBuilder({
processArgv: argumentsArray
})

const webpackConfig = Webpack.getBaseConfig({
entry: isDev
? path.join(MAIN_PROCESS_DIR, 'boot/index.dev.js')
: path.join(MAIN_PROCESS_DIR, 'boot/index.prod.js'),
output: {
filename: 'index.js',
path: path.join(DIST_DIR, 'main')
},
plugins: [
new webpack.DefinePlugin({
'process.resourcesPath': resourcesPath.mainProcess(),
'process.env.DEV_SERVER_URL': `'${SERVER_HOST}:${SERVER_PORT}'`
})
]
})

const webpackMain = new Webpack({
logger: new Logger('Main', 'olive'),
webpackConfig,
launcher // need to restart launcher after compilation
})

const nuxt = new NuxtApp(new Logger('Nuxt', 'green'))

const pipe = new Pipeline({
title: 'Electron-nuxt',
isDevelopment: isDev,
steps: [webpackMain, nuxt],
launcher,
builder
})

pipe.run()
40 changes: 40 additions & 0 deletions .electron-nuxt/renderer/NuxtApp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const path = require('path')
const { fork } = require('child_process')
const { utils } = require('@xpda-dev/core')
const { killWithAllSubProcess } = utils

const NUXT_PROCESS_PATH = path.join(__dirname, 'nuxt-process.js')

/**
* @implements {IStep}
*/
class NuxtApp {
constructor (logger) {
this.logger = logger
}

async build (isDev) {
this.nuxtProcess = fork(NUXT_PROCESS_PATH, { silent: true })
this.redirectStdout()
return new Promise((resolve, reject) => {
this.nuxtProcess.send({ action: 'build', target: isDev ? 'development' : 'production' })
this.nuxtProcess.once('message', ({ status, err }) => {
if (status === 'ok') resolve()
else reject(err)
})
})
}

redirectStdout () {
this.nuxtProcess.stdout.pipe(this.logger.stdout)
this.nuxtProcess.stderr.pipe(this.logger.stderr)
}

async terminate () {
this.nuxtProcess.kill()
if (this.nuxtProcess && !this.nuxtProcess.killed) killWithAllSubProcess(this.nuxtProcess.pid)
this.nuxtProcess = null
}
}

module.exports = NuxtApp
6 changes: 6 additions & 0 deletions .electron-nuxt/renderer/do-nothing-loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Credits: https://github.com/axtgr/do-nothing-loader/blob/master/index.js

module.exports = function(source) {
this.cacheable && this.cacheable();
return source;
};
39 changes: 39 additions & 0 deletions .electron-nuxt/renderer/nuxt-process.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const { Nuxt, Builder, Generator } = require('nuxt')
const { SERVER_PORT } = require('../config')
const nuxtConfig = require('./nuxt.config.js')

const nuxt = new Nuxt(nuxtConfig)

process.on('message', async ({ action, target }) => {
if (action !== 'build') {
console.warn('Unknown action')
process.send({ status: 'error', err: `Nuxt process: unknown action ('${action}')` })
return
}

await nuxt.ready()

// https://github.com/nuxt/nuxt.js/blob/dev/packages/builder/src/builder.js
const builder = new Builder(nuxt)

// https://github.com/nuxt/nuxt.js/blob/dev/packages/generator/src/generator.js
const generator = new Generator(nuxt, builder)

if (target === 'development') {
builder.build().then(() => {
nuxt.listen(SERVER_PORT)
process.send({ status: 'ok' })
}).catch(err => {
console.error(err)
process.send({ status: 'error', err: err.message })
})
} else {
generator.generate({ build: true, init: true }).then(({ errors }) => {
if (errors.length === 0) process.send({ status: 'ok' })
else process.send({ status: 'error', err: 'Error occurred while generating pages' })
}).catch(err => {
console.error(err)
process.send({ status: 'error', err: err.message })
})
}
})
84 changes: 84 additions & 0 deletions .electron-nuxt/renderer/nuxt.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/* eslint no-param-reassign: 0 */
process.env.BABEL_ENV = 'renderer'
const isProduction = process.env.NODE_ENV === 'production'
const isDev = process.env.NODE_ENV === 'development'
const path = require('path')
const webpack = require('webpack')
const deepmerge = require('deepmerge')
const nodeExternals = require('webpack-node-externals')
const resourcesPath = require('../resources-path-provider')
const { RENDERER_PROCESS_DIR, DIST_DIR, DISABLE_BABEL_LOADER } = require('../config')
const userNuxtConfig = require('../../src/renderer/nuxt.config')

const baseConfig = {
srcDir: RENDERER_PROCESS_DIR,
rootDir: RENDERER_PROCESS_DIR,
router: {
mode: 'hash'
},
dev: isDev,
generate: {
dir: path.join(DIST_DIR, 'renderer')
}
};

const baseExtend = (config, { isClient }) => {
config.externals = [nodeExternals({
modulesFromFile: {
include: ['dependencies']
}
})]

config.target = 'electron-renderer'

config.node = {
__dirname: !isProduction,
__filename: !isProduction
}

config.plugins.push(
new webpack.DefinePlugin({
'process.resourcesPath': isClient ? resourcesPath.nuxtClient() : resourcesPath.nuxtServer()
})
)

config.module = config.module || {}
config.module.rules = config.module.rules || []

if (DISABLE_BABEL_LOADER) {
// https://github.com/nuxt/typescript/blob/master/packages/typescript-build/src/index.ts#L55
const jsLoader = config.module.rules.find(el => el.test.test('sample.js') === true)
if (jsLoader) jsLoader.use = [path.join(__dirname, 'do-nothing-loader.js')]
}

}

const mergeConfig = customConfig => {
const hasExtendFunction = (customConfig.build !== undefined && customConfig.build.extend !== undefined);
if(hasExtendFunction){
const userExtend = customConfig.build.extend;
customConfig.build.extend = function() {
baseExtend(...arguments) // eslint-disable-line prefer-rest-params
userExtend(...arguments) // eslint-disable-line prefer-rest-params
}
} else {
if(baseConfig.build === undefined) baseConfig.build = {};
baseConfig.build.extend = baseExtend;
}

if (customConfig.build !== undefined && customConfig.build.plugins !== undefined) {
// webpack config plugins should not use deep merge
let { plugins, ...rest } = customConfig.build;
customConfig.build = rest;
let result = deepmerge(baseConfig, customConfig);
result.build.plugins = plugins;
return result;
} else {
return deepmerge(baseConfig, customConfig);
}
}


module.exports = mergeConfig(userNuxtConfig);
module.exports.mergeConfig = mergeConfig;
module.exports.baseConfig = baseConfig;
Loading

0 comments on commit 79f9255

Please sign in to comment.