• Stars
    star
    427
  • Rank 101,272 (Top 3 %)
  • Language
    JavaScript
  • Created over 12 years ago
  • Updated about 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An Ajax library that can target local JS code and web workers. (Replaced by ServiceWorkers!)

Local.js 0.6.2

[Repository | Issues | Documentation]

Overview

Local.js is an open-source security and IPC framework for socially-shareable Web plugins. It provides an Ajax interface for communicating interchangeably with javascript functions, parallel threads, and network peers. It also includes tools for managing and securing Web Workers, for emitting and subscribing to Server-Sent Events, and for exchanging and querying against links.

Examples

Run servers in the document:

local.addServer('foobar', function(req, res) {
    // Handles incoming requests from the application
    res.writeHead(200, 'ok', { 'Content-Type': 'text/plain' });
    res.end('Hello, application!');
});
local.dispatch({ method: 'GET', url: 'httpl://foobar' }).then(handle2or3xx, handle4or5xx);

Run servers in Web Workers:

local.spawnWorkerServer('http://myhost.com/myworker.js', function(req, res) {
    // Handles incoming requests from the worker
    res.writeHead(200, 'ok', { 'Content-Type': 'text/plain' });
    res.end('Hello, worker!');
});
local.dispatch({ method: 'GET', url: 'httpl://myworker.js' }).then(...);

Auto-spawn a temporary Worker to handle a request. After responding, the temp-worker is destroyed:

local.dispatch({ method: 'GET', url: 'httpl://myhost.com(/myworker.js)/' }).then(...);

Using bodyless request sugars:

local.HEAD('httpl://myhost.com(/myworker.js)/');
local.GET('httpl://myhost.com(/myworker.js)/');
local.GET({ url: 'httpl://myhost.com(/myworker.js)/', Accept: 'application/json' });
local.DELETE('httpl://myhost.com(/myworker.js)/');

// For reference, the non-sugar equivalent:
local.dispatch({ method: 'GET', url: 'httpl://myhost.com(/myworker.js)/', Accept: 'application/json' });

Using bodyfull request sugars:

local.POST({ foo: 'bar' }, 'httpl://myhost.com(/myworker.js)/');
local.PUT({ foo: 'bar' }, 'httpl://myhost.com(/myworker.js)/');
local.PATCH({ foo: 'bar' }, 'httpl://myhost.com(/myworker.js)/');
local.POST({ foo: 'bar' }, {
    url: 'httpl://myhost.com(/myworker.js)/',
    Accept: 'application/json',
    Content_Type: 'application/www-x-form-urlencoded'
});

// For reference, the non-sugar equivalent:
local.dispatch({
    method: 'POST',
    url: 'httpl://myhost.com(/myworker.js)/',
    Accept: 'application/json',
    Content_Type: 'application/www-x-form-urlencoded',
    body: { foo: 'bar' }
});

Note that headers may have their dashes changed to underscores. However, if in the request object, headers must be capitalized. To avoid this requirement, put them in the headers sub-object:

local.dispatch({
    method: 'POST',
    url: 'httpl://myhost.com(/myworker.js)/',
    headers: {
        accept: 'application/json',
        'content-type': 'application/www-x-form-urlencoded'
    },
    body: { foo: 'bar' }
});

If you need to stream the request, create a local.Request object, then send it to local.dispatch():

var req = new local.Request({ method: 'POST', url: 'http://foo.com', Content_Type: 'text/plain' });
local.dispatch(req).then(...);
for (var i = 0; i < 10; i++) {
    req.send(''+i+'\n');
}
req.end();

A dispatch call returns a promise which resolves to the response when the response-stream finishes. If the status is in the 200-300 range, it is fulfilled; otherwise, the promise is rejected with the response as the error-value.

If you need to stream the response, use the stream: true attribute in the request. The promise will be fulfilled when the headers are sent, and you can then attach to the 'data' and 'end' events:

local.GET({ url: 'http://foo.com', stream: true })
    .then(function(res) {
        console.log(res.status); // => 200
        res.on('data', function(chunk) {
            // ...
        });
        res.on('end', function() {
            // ...
        });
    });
}

Local.js includes a registry of content-type serializers and parsers which are auto-invoked on the 'end' events of requests and responses. By default, it ships with json and application/x-www-form-urlencoded, but you can register more with local.contentTypes.

If successful, the body attribute will include the parsed object. If parsing fails, or the content-type is not available, the body attribute will be a string. Note that server functions are fired when headers are received, and so must always wait for the 'end' event:

local.addServer('foobar', function(req, res) {
    console.log(req.header('Content-Type')); // => 'application/json'
    req.on('end', function() {
        res.writeHead(200, 'ok', { 'Content-Type': 'application/x-www-form-urlencoded' });
        res.end('foo='+req.body.foo);
    });
});
local.POST({ foo: 'bar' }, 'httpl://foobar') // will default content-type to json
    .then(function(res) {
        console.log(res.header('Content-Type')); // => 'application/x-www-form-urlencoded'
        console.log(res.body); // => { foo: 'bar' }
    });

Local.js also includes a registry of header serializers and parsers which are auto-invoked on dispatch - local.httpHeaders. By default, it ships with Link, Accept, and Via. In responses, the parsed headers are placed in the response.parsedHeaders object to avoid confusion:

local.HEAD('http://foo.com').then(function(res) {
    console.log(res.headers.link); // => '<http://foo.com>; rel="self service"; title="Foo!"'
    console.log(res.header('Link')); // => '<http://foo.com>; rel="self service"; title="Foo!"'
    console.log(res.parsedHeaders.link); // => [{ href: 'http://foo.com', rel: 'self service', title: 'Foo!' }]
});

To query the links, use local.queryLinks:

local.HEAD('http://foo.com').then(function(res) {
    var links = local.queryLinks(res.headers.link, { rel: 'self' });
    console.log(links); // => [{ href: 'http://foo.com', rel: 'service', title: 'Foo!' }]
    var links = local.queryLinks(res, { rel: 'self' })
    console.log(links); // => [{ href: 'http://foo.com', rel: 'service', title: 'Foo!' }]
});

To decide which content-type to respond with, use local.preferredType:

local.addServer('foobar', function(req, res) {
    var type = local.preferredType(req, ['text/html', 'text/plain', 'application/json']);
    if (!type) { return res.writeHead(406, 'Not Acceptable').end(); }
    if (type == 'text/html') { /* ... */ }
    // ...
});
local.GET({ url: 'httpl://foobar', Accept: 'text/plain' }); // will get text/plain
local.GET({ url: 'httpl://foobar', Accept: 'application/json, text/*' }); // will get application/json
local.GET({ url: 'httpl://foobar', Accept: '*/*' }); // will get text/html

Programmatically navigate with a headless user-agent:

// Fetch the profile of bob@foo.com
local.agent('http://foo.com')
    .follow({ rel: 'gwr.io/users' }) // documented at http://gwr.io/users
    .follow({ rel: 'item', id: 'bob' })
    .GET({ Accept: 'application/json' })

Further topics:


How it works

The core of Local.js is a message router which adds a new scheme, httpl://, for targeting requests at functions within the application. These in-app server functions work similarly to node.js servers, and support streaming for requests and responses. Special types of server functions, the "bridge" servers, serialize the streams into JSON and transport them over channels to other namespaces.

Further reading:


Getting Started

Download local.js or local.min.js from the repository. Then read the documentation at HTTPLocal.com. For an introduction to writing Local.js apps, read Intro: TodoSOA.

Getting Help

Contact @pfrazee or join #httpl on freenode.

Feedback & Bug Reporting

Send specific issues and suggestions to the GitHub issue tracker. Suggestions to improve the documentation can be added to the ongoing Documentation Improvements issue.


Misc

Special thanks and credits

Thank you to the following third-party library authors:

Special thanks to Goodybag.com for their support during the development of this project. If you're in Austin and need food delivered to the office, be sure to check out their website.

License

The MIT License (MIT) Copyright (c) 2014 Paul Frazee

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.

More Repositories

1

crdt_notes

918
star
2

base-emoji

Output a buffer (0xdeadbeef) in emojis (β„οΈπŸΌπŸš“πŸ‘…)
JavaScript
261
star
3

electron-browser

browser ui for electron, written in react
JavaScript
225
star
4

http-template-literal

Make HTTP requests the way TBL intended.
JavaScript
198
star
5

vitra

Cooperative databases using smart contracts.
TypeScript
178
star
6

suggest-box

πŸ’¬ decorates a textarea with GitHub-style suggestion popups (eg for emojis and users)
JavaScript
76
star
7

nodevms

A cryptographically auditable VM service using Nodejs and Dat.
JavaScript
69
star
8

dat-gateway

Quick Dat to HTTP gateway
JavaScript
47
star
9

infocivics

Information Civics paper
39
star
10

webterm

A web based command line interface (Beaker)
JavaScript
38
star
11

pauls-electron-rpc

My RPC solution for exporting APIs from the electron background process to renderers and webviews
JavaScript
37
star
12

citizen

A social web API for beaker/dat applications
JavaScript
32
star
13

pretty-hash

Output binary buffers as a nice shortened hex string
JavaScript
27
star
14

node-http-dat-forum

A Web forum built on Nodejs, Dat and HTTP
JavaScript
27
star
15

on-wakeup

Watches for the computer to fall asleep and then triggers an event callback on wakeup
JavaScript
26
star
16

diff-file-tree

Compare two file-trees, get a list of changes, then apply left or right
JavaScript
24
star
17

ctznry

A decentralized social networking webapp using CTZN
CSS
24
star
18

tmpdat

Create a temporary in-memory dat
JavaScript
23
star
19

parse-dat-url

Node url.parse updated to support versioned dat URLs.
JavaScript
20
star
20

libvms

API for running cryptographically auditable VM services.
JavaScript
20
star
21

multicb

Simple way to aggregate multiple node-style callbacks
JavaScript
19
star
22

dat-rss-reader

An rss-reader dat app
JavaScript
18
star
23

gsim

A little physics simulation which uses time-dilation to create attraction
JavaScript
18
star
24

json-lz

Simple self-describing JSON
17
star
25

hyper-sfw

Synced Files Workspace. A p2p collaborative filestructure built on Hypercore's Autobase.
TypeScript
16
star
26

example-atproto-rn-app

Demonstrates how to set up a React Native app to use the atproto api.
Java
14
star
27

scoped-fs

An FS wrapper that keeps all access scoped to a specific folder.
JavaScript
13
star
28

web-fritter

JavaScript
12
star
29

eco

Library of data types for building distributed applications on Phoenix/SSB
JavaScript
12
star
30

identify-filetype

Identifies the file-type of a buffer
JavaScript
11
star
31

hyper-vcr

A p2p version-controlled repo (built on hypercore)
TypeScript
11
star
32

ssbmail

encrypted mail
JavaScript
9
star
33

circular-append-file

A simple appendable-file interface which enforces a size cap by overwriting itself.
JavaScript
9
star
34

crdt_talk

JavaScript
8
star
35

hyper-search-experiments

A quick bench of FTS search indexes across multiple bees
JavaScript
8
star
36

pull-identify-filetype

Identify the type of file passing through the stream
JavaScript
7
star
37

ctzn.network

Website for the ctzn.network protocol
CSS
7
star
38

pauls-ui-kit

My basic UI kit for apps I make
HTML
7
star
39

webcomponents-yo

An experiment with WebComponents + the Yo-Yo rendering library
JavaScript
7
star
40

ssb-kvdb

A key-value database for Scuttlebot applications.
7
star
41

pauls-sliding-window-rate-limiter

Efficiently rate limit calls using a sliding window algorithm.
JavaScript
6
star
42

pfrazee.github.io

CSS
6
star
43

queryable-log

A structured append-only log which can be queried. Stores as ndjson and applies a log-size limit.
JavaScript
6
star
44

dat-source-explorer

A helpful widget for viewing the source of a dat site.
JavaScript
6
star
45

random-access-indexed-file

Continuous reading or writing to a file using random offsets and lengths (but for platforms that dont support sparse files)
JavaScript
6
star
46

electron-app-env

Apps environment using Electron
JavaScript
5
star
47

dat-profile-site

API for interacting with Dat Profile Sites.
JavaScript
5
star
48

example-self-mutating-dat-site

Example of self-mutating websites using the Dat APIs in Beaker
JavaScript
5
star
49

dat-imgbrowser

Browse image directories (dat app)
HTML
5
star
50

electron-tape

Tape testing harness for electron apps
JavaScript
5
star
51

vitra-confine-runtime

Confine runtime for "Vitra" scripts.
JavaScript
5
star
52

check-json-schema

CLI tool to check your JSON schemas.
JavaScript
4
star
53

zerr

custom js error construction
JavaScript
4
star
54

servware

An straight-forward Web server framework for Local.js
JavaScript
4
star
55

ctzn-editor

JavaScript
4
star
56

pull-ipc

Pull-stream wrapper around electron's IPC channel
JavaScript
4
star
57

nquery

local.js wrapper to jQuery so you can remotely operate on regions of the DOM
JavaScript
4
star
58

pause-offscreen

On web pages, hide gifs and pause videos when they're scrolled offscreen, to save CPU cycles
JavaScript
4
star
59

pfrazee.com

TypeScript
4
star
60

hyperswarm-bench

JavaScript
3
star
61

webshell

WebShell - An HTTP command-line environment with "fat" pipes, agents, creation-on-invocation, and GUI output (abandoned)
JavaScript
3
star
62

ssb-web-server-demo-app

A quick test/demo app for ssb-web-server
JavaScript
3
star
63

test-files

a set of test files
JavaScript
3
star
64

fuego

3
star
65

beakerbrowser-com-redirect

Archive site for beaker
TypeScript
3
star
66

process-sandbox

Run javascript in sandboxed child processes
JavaScript
3
star
67

textedit.pub

mutli-user text editing
JavaScript
2
star
68

scuttlebot-views

A materialized-views plugin for Scuttlebot
JavaScript
2
star
69

nodevms.com

Website for nodevms
CSS
2
star
70

mview

A CRDT view materialization library for distributed systems
JavaScript
2
star
71

autobee

An experiment with Autobase and Hyperbee
JavaScript
2
star
72

electron-bug-service-workers-failure

Demonstrates an issue registering service workers in custom protocols
JavaScript
2
star
73

log-reader

Simple demo dat app
JavaScript
2
star
74

dat-next-next-staging

Experimental quick-n-dirty file sharing tool on top of dat with a staging area
JavaScript
2
star
75

listen-random-port

Listen a node HTTP server on a random, unused port
JavaScript
2
star
76

preserved-feed-app

Just a backup of code pulled out of the beaker://feed experiment
JavaScript
2
star
77

simulated-autobee

An in-memory simulated autobee for testing
TypeScript
2
star
78

paulfrazee.com

The code and config for my personal site
JavaScript
2
star
79

muxrpc-validation

Validation library for muxrpc apis
JavaScript
2
star
80

slang

concatenative stack-based search language (turing complete queries)
JavaScript
2
star
81

pull-serializer

de/serialize pull streams
JavaScript
2
star
82

thepublisher-design

Design doc for a software publishing project
1
star
83

paste.space

post text dumps (like gists)
JavaScript
1
star
84

lugg

Take your $HOME with you
Shell
1
star
85

ssb-pub-status

a status-page server for ssb pub hosts
JavaScript
1
star
86

app-social

JavaScript
1
star
87

tintjs

Logicless templates
JavaScript
1
star
88

bezier-signatures

Repo to try out pubkey-signature rendering algorithms
JavaScript
1
star
89

wordgen

A random word generator
JavaScript
1
star
90

data-compression-talk

Slides and PDF for July 2016 Papers We Love: Data Compression
1
star
91

ssb-rawfeed

Small SSB feed-explorer tool
JavaScript
1
star
92

stack-assets-builder

live builds requests for js and css using browserify and less
JavaScript
1
star
93

protocols

DEPRECATED Protocol specs published at grimwire.com/rel
PHP
1
star
94

infiniscroll

infinite scroll web widget
JavaScript
1
star
95

peoplehere

JavaScript
1
star
96

input-url-detector

detect when a URL is in a textarea/input and automatically fetch info
1
star
97

bdat

Beaker Dat CLI tool. Wraps Dat with new commands for Beaker.
JavaScript
1
star
98

ssbc.github.io

site
CSS
1
star
99

example-deno-app

JavaScript
1
star
100

testify

A test-runner for beaker/dat apps
JavaScript
1
star