Verified Commit 33de7893 authored by CompileNix's avatar CompileNix
Browse files

WIP: initial

parents
Pipeline #95 failed with stages
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
{
"extends": "standard",
"env": {
"browser": false,
"node": true
}
}
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless
# FuseBox cache
.fusebox/
*.pem
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/Index.js"
}
]
}
#!/usr/bin/env node
'use strict'
const fs = require('fs')
const crypto = require('crypto')
const http = require('http')
const express = require('express')
const morgan = require('morgan')
const staticModule = require('static-module')
const app = express()
app.use(morgan('combined'))
app.get('/sw.js', async (req, res) => {
const filePath = './static/sw.js'
if (fs.accessSync(filePath, fs.constants.R_OK)) {
res.sendStatus(404)
return
}
const fileReader = fs.createReadStream(filePath)
res.set({
'Content-Type': 'application/javascript; charset=UTF-8',
'Cache-Control': 'public, no-cache'
})
fileReader.pipe(staticModule({ // see https://www.npmjs.com/package/static-module
'to-cache': () => JSON.stringify([
'/site.css',
'/Index.js',
'/header.html',
'/footer.html',
'/SiteAppander.js'
], null, ' '),
'version': () => JSON.stringify(1),
'blacklist': () => JSON.stringify(['/login'])
}))
.pipe(res)
})
app.use(express.static('static', {
'etag': false,
'lastModified': true,
setHeaders: (res, path, stat) => {
res.set('Cache-Control', 'public, no-cache') // TODO: add max-age if static content has unique names per file vesion and is generated using build process
}
}))
app.get('/', (req, res) => {
console.log(req.url)
// req.item = req.params[0];
let content
if ('partial' in req.query) {
// TODO: implement partial content loading
} else {
content = [
fs.readFileSync('static/header.html'),
// TODO: add requested content
fs.readFileSync('static/footer.html')
]
}
Promise.all(content)
.then(content => content.map(x => x.toString('utf-8')))
.then(content => {
const contentFinal = content.join('')
res.set({
'ETag': crypto.createHash('sha256').update(contentFinal).digest('hex'),
'Cache-Control': 'public, no-cache'
})
res.send(contentFinal)
})
.catch(err => res.status(500).send(err.toString()))
})
// https.createServer({key: fs.readFileSync("key.pem"),cert: fs.readFileSync("cert.pem")}, app).listen(8081);
http.createServer(app).listen(8081)
console.log('http://localhost:8081/')
MIT License
Copyright (c) 2018 Compilenix
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#!/bin/bash
openssl genrsa -out privkey.pem 2048
echo -e "[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\ncommonName=Common Name\ncommonName_default=localhost\n[v3_req]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @alt_names\n[alt_names]\nDNS.1 = localhost\n" >openssl.cfg
openssl req -new -x509 -days 18250 -subj "/CN=localhost" -config openssl.cfg -sha256 -key privkey.pem -out cert.pem
rm openssl.cfg
This diff is collapsed.
{
"name": "example-service-worker",
"version": "1.0.0",
"description": "this is a simple service worker example app",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://git.compilenix.org/Compilenix/example-service-worker"
},
"author": {
"name": "Compilenix",
"url": "https://compilenix.org"
},
"scripts": {
"start": "node ./Index.js"
},
"dependencies": {
"express": "^4.16.2",
"morgan": "^1.9.0",
"static-module": "^2.2.2"
},
"devDependencies": {
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^8.0.0",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"standard": "^12.0.1"
}
}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script type="application/javascript">
if ("serviceWorker" in navigator) {
addEventListener("load", async() => {
try {
const registration = await navigator.serviceWorker.register("/sw.js");
console.log("ServiceWorker registration successful with scope: ", registration.scope);
} catch (err) {
console.log("ServiceWorker registration failed: ", err);
}
});
}
</script>
</head>
<body>
// require(...) see https://www.npmjs.com/package/static-module
const files = require('to-cache')()
const version = require('version')()
const blacklist = require('blacklist')()
const cacheName = `cache-v${version}`
let debug1 = console.log
let debug = console.log
let info = console.log
let log = console.log
self.addEventListener('install', event => {
skipWaiting()
event.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll(files)
})
)
log('ServiceWorker installed')
})
self.addEventListener('activate', event => {
return event.waitUntil(
// TODO: migrate not yet expired dynamic content into new cache
caches.keys().then(keys => {
return Promise.all(
keys.map(cache => {
info(`ServiceWorker: remove element from cache during activation => ${cache}`)
return caches.delete(cache)
})
)
})
log('ServiceWorker activated')
)
})
self.addEventListener('fetch', event => {
debug('ServiceWorker is intercepting a client fetch')
event.respondWith(
caches.match(event.request).then(response => {
if (response) {
debug("ServiceWorker is resolving the client fetch using it's cache")
return response
}
return fetch(event.request).then(response => {
debug('ServiceWorker has to fetch requested resource from server')
var shouldCache = response.ok
for (var i = 0; i < blacklist.length; ++i) {
var expression = new RegExp(blacklist[i])
if (expression.test(event.request.url)) {
debug1("ServiceWorker decided to NOT cache the response from the server, based on the ServiceWorker's cache-blacklist")
shouldCache = false
break
}
}
if (event.request.method == 'POST') {
debug1('ServiceWorker decided to NOT cache the response from the server, because the request is a HTTP POST')
shouldCache = false
}
if (shouldCache) {
return caches.open(cacheName).then(cache => {
debug("ServiceWorker is going to cache the server's response")
cache.put(event.request, response.clone())
return response
})
} else {
return response
}
})
})
)
})
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment