New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

braidify

Package Overview
Dependencies
Maintainers
1
Versions
23
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

braidify

Synchronization for the Web (reference implementation)

  • 0.1.8
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5
increased by66.67%
Maintainers
1
Weekly downloads
 
Created
Source

Braidify Library

Easily adds Braid to existing Javascript libraries.

  • npm package now available for testing
  • Source is in braidjs repo
  • Reference implementation. Meets Braid-HTTP 03.

Today it has wrappers for the following HTTP libraries:

require('braidify').fetch     // Browser fetch() API and require('node-fetch')
require('braidify').http      // Nodejs require('http') and require('https')

And we'd love to add Braid support to any other http API you like.

Let's look at some examples:

Browser fetch()

<script src="http-client.js"></script>
<script>
    fetch(
        'https://braid.org/chat',
        {subscribe: {keep_alive: true}},
    ).andThen(version => {
        console.log('We got a new version!', version)
        // {
        //   version: "me",
        //   parents: ["mom", "dad"],
        //   patches: [{unit: "json", range: ".foo", content: "3"}]
        //   body:    "3"
        // }
        //   // Version will contain either patches *or* body
    })
</script>

And if you want automatic reconnections:

function connect() {
    fetch(
        'https://braid.org/chat',
        {subscribe: {keep_alive: true}},
    ).andThen(version => {
        console.log('We got a new version!', version)
        // {
        //   version: "me",
        //   parents: ["mom", "dad"],
        //   patches: [{unit: "json", range: ".foo", content: "3"}]
        //   body:    "3"
        // }
        //   // Version will contain either patches *or* body
    }).catch(e => setTimeout(connect, 1000))
}
connect()

You can also use for await:

async function connect () {
    try {
        for await (var v of fetch('/chat', {subscribe: {keep_alive: true}})) {
            // Updates might come in the form of patches:
            if (v.patches)
                chat = apply_patches(v.patches, chat)

            // Or complete versions:
            else
                // Beware the server doesn't send these yet.
                chat = JSON.parse(v.body)

            render_stuff()
        }
    } catch (e) {
        console.log('Reconnecting...')
        setTimeout(connect, 4000)
    }
}

Nodejs client with fetch()

var fetch = require('braidify').fetch
// process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0

function connect () {
    fetch('https://localhost:3009/chat',
          {subscribe: {keep_alive: true}}).andThen(
              x => console.log('Got ', x)
              //x => {throw new Error('hi')}
          ).catch(e => {
              console.error('Reconnecting!', e);
              setTimeout(connect, 1000)
          })
}
connect()

Nodejs client with require('http')

// Use this line if necessary for self-signed certs
// process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0

var https = require('braidify').http(require('https'))
https.get(
   'https://braid.org/chat',
   {subscribe: true},
   (res) => {
      res.on('version', (version) => {
          console.log('well we got one', version)
      })
   }
)

To get auto-reconnections use:

function connect () {
    https.get(
        'https://braid.org/chat',
        {subscribe: true},
        (res) => {
            res.on('version', (version) => {
                // {
                //   version: "me",
                //   parents: ["mom", "dad"],
                //   patches: [{unit: "json", range: ".foo", content: "3"}]
                //   body:    "3"
                // }
                //   // Version will contain either patches *or* body, but not both
                console.log('We got a new version!', version)
            })

            res.on('end',   e => setTimeout(connect, 1000))
            res.on('error', e => setTimeout(connect, 1000))
        })
}
connect()

Nodejs server using require('express')

On the server using express:

var braidify = require('braidify').http

// Braidify will give you these fields and methods:
// - req.subscribe
// - req.startSubscription({onClose: cb})
// - res.sendVersion()
// - await req.patches()

var app = require('express')()

app.use(braidify)    // Add braid stuff to req and res

app.get('/', (req, res) => {
    // Now use it
    if (req.subscribe)
        res.startSubscription({ onClose: _=> null })
        // startSubscription automatically sets statusCode = 209
    else
        res.statusCode = 200

    // Send the current version
    res.sendVersion({
        version: 'greg',
        parents: ['gr','eg'],
        body: JSON.stringify({greg: 'greg'})
    })

    // Or you can send patches like this:
    // res.sendVersion({
    //     version: 'greg',
    //     parents: ['gr','eg'],
    //     patches: [{range: '.greg', unit: 'json', content: '"greg"'}]
    // })
})

require('http').createServer(app).listen(8583)

Nodejs server with require('http')

On the server using regular require('http'):

var braidify = require('braidify').http

require('http').createServer(
    (req, res) => {
        // Add braid stuff to req and res
        braidify(req, res)

        // Now use it
        if (req.subscribe)
            res.startSubscription({ onClose: _=> null })
            // startSubscription automatically sets statusCode = 209
        else
            res.statusCode = 200

        // Send the current version
        res.sendVersion({
            version: 'greg',
            body: JSON.stringify({greg: 'greg'})
        })
    }
).listen(9935)

FAQs

Package last updated on 18 Mar 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc