Current Dev State

This commit is contained in:
Tim Lorsbach
2025-06-23 20:13:54 +02:00
parent b4f9bb277d
commit ded50edaa2
22617 changed files with 4345095 additions and 174 deletions

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Matt DesLauriers
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.

View File

@ -0,0 +1,154 @@
# watchify-middleware
[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges)
A simple middleware for watchify which provides a few features for a better development experience:
- suspends the server response so you are never served a stale or empty bundle
- removes the default 600ms delay (left up to the developer to reconfigure)
- emits timing information in a `'log'` event
- (optional) allows for a browser-based error handler (eg: print to DevTools console)
For practical implementations, see [watchify-server](https://www.npmjs.com/package/watchify-server) or [budo](https://www.npmjs.com/package/budo).
## Install
```sh
npm install watchify-middleware --save
```
## Example
```js
var watchifyMiddleware = require('watchify-middleware')
var defaultIndex = require('simple-html-index')
var staticUrl = 'bundle.js'
var bundler = browserify('app.js', {
// config for watchify
cache: {},
packageCache: {},
basedir: __dirname
})
var watchify = watchifyMiddleware(bundler)
var server = http.createServer(function (req, res) {
if (req.url === '/') {
defaultIndex({ entry: staticUrl }).pipe(res)
} else if (req.url === '/' + staticUrl) {
watchify(req, res)
}
})
server.listen(8000, 'localhost', function () {
console.log('Listening on http://localhost:8000/')
})
```
For a more complete example, see [example/server.js](example/server.js).
## Usage
[![NPM](https://nodei.co/npm/watchify-middleware.png)](https://www.npmjs.com/package/watchify-middleware)
#### `middleware = watchifyMiddleware(browserify[, opt])`
Returns a `middleware(req, res)` function from the given `browserify` bundler instance and options:
- `delay` (default 0) a delay to debounce the rebuild, useful for things like git branch switches (where hundreds of files may change at once)
- `errorHandler` (default false) a boolean or function for handling errors
- `initialBundle` (default true) whether to initially bundle and emit `'pending'`
`errorHandler` can be a function that accepts `(err)` parameter and optionally returns the new contents (String|Buffer) of the JavaScript bundle. If `errorHandler` is `true`, it will default to the following:
```js
var stripAnsi = require('strip-ansi')
function defaultErrorHandler (err) {
console.error('%s', err)
var msg = stripAnsi(err.message)
return ';console.error(' + JSON.stringify(msg) + ');'
}
```
<sup>(some plugins produce ANSI color codes in error messages)</sup>
Otherwise, it assumes the normal behaviour for error handling (which is typically just an uncaught error event).
#### `emitter = watchifyMiddleware.emitter(browserify[, opt])`
The same as above, except this returns an EventEmitter for handling bundle updates.
##### `emitter.middleware`
The `middleware(req, res)` function for use in your server.
##### `emitter.bundle()`
Triggers a bundle event. Usually should only be called if `initialBundle` is set to false, to trigger the initial bundle.
##### `emitter.on('pending', fn)`
Called when watchify begins its incremental rebuild.
##### `emitter.on('update', fn)`
Called when bundling is finished, with parameter `(contents, rows)`.
`contents` is a Buffer/String of the bundle and `rows` is a list of dependencies that have changed since last update. On first run, this will be an empty array.
##### `emitter.on('log', fn)`
Provides timing and server request logging, passing an `(event)` parameter.
Server request logs look like this:
```js
{ level: 'debug', type: 'request', message: 'bundle (pending|ready)'}
```
Bundle updates look like this:
```js
{ elapsed: Number, level: 'info', type: 'bundle' }
```
These events work well with [garnish](https://github.com/mattdesl/garnish) and other ndjson-based tools.
##### `emitter.on('error', fn)`
If `errorHandler` was `fasle`, this will get triggered on bundle errors. If an error handler is being used, this will not get triggered.
##### `emitter.on('bundle-error', fn)`
This will get triggered on bundle errors, regardless of whether `errorHandler` is being used. This can be used to respond to syntax errors, such as showing a stylized notification.
##### `emitter.close()`
Closes the `watchify` instance and stops file watching.
#### `version = watchifyMiddleware.getWatchifyVersion()`
Primarily useful for debugging, this will return the *actual* version number of the `watchify` module being used by `watchify-middleware`.
## running the demo
To run the example, first git clone and install dependencies.
```sh
git clone https://github.com/mattdesl/watchify-middleware.git
cd watchify-middleware
npm install
```
Then:
```sh
npm start
```
And open [http://localhost:8000/](http://localhost:8000/). Try making changes to [example/app.js](example/app.js) and you will see timing information in console, and reloading the browser will provide the new bundle.
## License
MIT, see [LICENSE.md](http://github.com/mattdesl/watchify-middleware/blob/master/LICENSE.md) for details.

View File

@ -0,0 +1,5 @@
var url = require('url')
console.log(url.parse(window.location.href))
var file = require('fs').readFileSync(__dirname + '/../README.md', 'utf8')
console.log(file)

View File

@ -0,0 +1,49 @@
var watchifyMiddleware = require('../')
var http = require('http')
var defaultIndex = require('simple-html-index')
var browserify = require('browserify')
var staticUrl = 'bundle.js'
var bundler = browserify('app.js', {
// config for watchify
cache: {},
transform: [ require('babelify'), 'brfs' ],
packageCache: {},
debug: true,
basedir: __dirname
})
var watcher = watchifyMiddleware.emitter(bundler, {
errorHandler: true
})
watcher.on('pending', function () {
console.log('pending request')
})
watcher.on('update', function () {
console.log('update request')
})
watcher.on('log', function (ev) {
if (ev.elapsed) {
ev.elapsed = ev.elapsed + 'ms'
ev.url = staticUrl
}
ev.name = 'server'
console.log(JSON.stringify(ev))
})
var middleware = watcher.middleware
var server = http.createServer(function (req, res) {
if (req.url === '/') {
defaultIndex({ entry: staticUrl }).pipe(res)
} else if (req.url === '/' + staticUrl) {
middleware(req, res)
}
})
server.listen(8000, 'localhost', function () {
console.log('Listening on http://localhost:8000/')
})

View File

@ -0,0 +1,57 @@
var createBundler = require('./lib/bundler')
module.exports = function watchifyMiddleware (browserify, opt) {
var emitter = createEmitter(browserify, opt)
return emitter.middleware
}
module.exports.emitter = createEmitter
module.exports.getWatchifyVersion = function () {
return require('watchify/package.json').version
}
function createEmitter (browserify, opt) {
var bundler = createBundler(browserify, opt)
var pending = false
var contents = ''
bundler.on('pending', function () {
pending = true
})
bundler.on('update', function (data) {
pending = false
contents = data
})
bundler.middleware = function middleware (req, res) {
if (pending) {
bundler.emit('log', {
level: 'debug',
type: 'request',
message: 'bundle pending'
})
bundler.once('update', function () {
bundler.emit('log', {
level: 'debug',
type: 'request',
message: 'bundle ready'
})
submit(req, res)
})
} else {
submit(req, res)
}
}
return bundler
function submit (req, res) {
res.setHeader('content-type', 'application/javascript; charset=utf-8')
res.setHeader('content-length', contents.length)
res.statusCode = req.statusCode || 200
res.end(contents)
}
}

View File

@ -0,0 +1,133 @@
var createWatchify = require('watchify')
var EventEmitter = require('events').EventEmitter
var debounce = require('debounce')
var concat = require('concat-stream')
var assign = require('object-assign')
var stripAnsi = require('strip-ansi')
var parseError = require('./parse-error')
module.exports = bundler
function bundler (browserify, opt) {
opt = opt || {}
var emitter = new EventEmitter()
var delay = opt.delay || 0
var closed = false
var pending = false
var time = Date.now()
var updates = []
var errorHandler = opt.errorHandler
if (errorHandler === true) {
errorHandler = defaultErrorHandler
}
var watchify = createWatchify(browserify, assign({}, opt, {
// we use our own debounce, so make sure watchify
// ignores theirs
delay: 0
}))
var contents = null
emitter.close = function () {
if (closed) return
closed = true
if (watchify) {
// needed for watchify@3.0.0
// this needs to be revisited upstream
setTimeout(function () {
watchify.close()
}, 200)
}
}
var bundleDebounced = debounce(bundle, delay)
watchify.on('update', function (rows) {
if (closed) return
updates = rows
pending = true
time = Date.now()
emitter.emit('pending')
bundleDebounced()
})
emitter.bundle = function () {
if (closed) return
time = Date.now()
if (!pending) {
pending = true
process.nextTick(function () {
emitter.emit('pending')
})
}
bundle()
}
// initial bundle
if (opt.initialBundle !== false) {
emitter.bundle()
}
return emitter
function bundle () {
if (closed) {
update()
return
}
var didError = false
var outStream = concat(function (body) {
if (!didError) {
contents = body
var delay = Date.now() - time
emitter.emit('log', {
contentLength: contents.length,
elapsed: Math.round(delay),
level: 'info',
type: 'bundle'
})
bundleEnd()
}
})
var wb = watchify.bundle()
// it can be nice to handle errors gracefully
if (typeof errorHandler === 'function') {
wb.once('error', function (err) {
err.message = parseError(err)
contents = errorHandler(err) || ''
didError = true
bundleEnd()
emitter.emit('bundle-error', err)
})
} else {
wb.once('error', function (err) {
err.message = parseError(err)
emitter.emit('error', err)
emitter.emit('bundle-error', err)
})
}
wb.pipe(outStream)
function bundleEnd () {
update()
}
}
function update () {
if (closed) return
if (pending) {
pending = false
emitter.emit('update', contents, updates)
updates = []
}
}
}
function defaultErrorHandler (err) {
console.error('%s', err)
var msg = stripAnsi(err.message)
return ';console.error(' + JSON.stringify(msg) + ');'
}

View File

@ -0,0 +1,9 @@
// parses a syntax error for pretty-printing to console
module.exports = parseError
function parseError (err) {
if (err.codeFrame) { // babelify@6.x
return [err.message, err.codeFrame].join('\n\n')
} else { // babelify@5.x and browserify
return err.annotated || err.message
}
}

View File

@ -0,0 +1,84 @@
{
"_from": "watchify-middleware@^1.6.0",
"_id": "watchify-middleware@1.6.0",
"_inBundle": false,
"_integrity": "sha1-bbbijwJ53hyhIJrk8afwY3RYd8Q=",
"_location": "/watchify-middleware",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "watchify-middleware@^1.6.0",
"name": "watchify-middleware",
"escapedName": "watchify-middleware",
"rawSpec": "^1.6.0",
"saveSpec": null,
"fetchSpec": "^1.6.0"
},
"_requiredBy": [
"/budo"
],
"_resolved": "https://registry.npmjs.org/watchify-middleware/-/watchify-middleware-1.6.0.tgz",
"_shasum": "6db6e28f0279de1ca1209ae4f1a7f063745877c4",
"_spec": "watchify-middleware@^1.6.0",
"_where": "/home/manfred/enviPath/ketcher2/ketcher/node_modules/budo",
"author": {
"name": "Matt DesLauriers",
"email": "dave.des@gmail.com",
"url": "https://github.com/mattdesl"
},
"bugs": {
"url": "https://github.com/mattdesl/watchify-middleware/issues"
},
"bundleDependencies": false,
"dependencies": {
"concat-stream": "^1.5.0",
"debounce": "^1.0.0",
"events": "^1.0.2",
"object-assign": "^4.0.1",
"strip-ansi": "^3.0.0",
"watchify": "^3.3.1"
},
"deprecated": false,
"description": "a server for faster watchify development",
"devDependencies": {
"babelify": "^6.3.0",
"brfs": "^1.4.1",
"browserify": "^11.2.0",
"faucet": "0.0.1",
"garnish": "^2.3.0",
"got": "^4.2.0",
"minimist": "^1.1.3",
"semver": "^5.0.3",
"simple-html-index": "^1.0.1",
"tape": "^4.2.0"
},
"homepage": "https://github.com/mattdesl/watchify-middleware",
"keywords": [
"watchify",
"server",
"fast",
"reload",
"incremental",
"suspend",
"request",
"response",
"wait",
"delay",
"live",
"browser",
"browserify"
],
"license": "MIT",
"main": "index.js",
"name": "watchify-middleware",
"repository": {
"type": "git",
"url": "git://github.com/mattdesl/watchify-middleware.git"
},
"scripts": {
"start": "node example/server.js ",
"test": "node test/index.js | faucet"
},
"version": "1.6.0"
}