0.2.17 • Published 2 years ago

@socketsupply/socket-api v0.2.17

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Bluetooth

A high level, cross-platform API for Bluetooth Pub-Sub

Bluetooth (extends EventEmitter)

Create an instance of a Bluetooth service.

constructor(serviceId)

constructor is an example property that is set to true Creates a new service with key-value pairs

ArgumentTypeDefaultOptionalDescription
serviceIdstringfalseGiven a default value to determine the type

start()

Start the bluetooth service.

Return ValueTypeDescription
Not specifiedPromise<ipc.Result>

subscribe(id )

Start scanning for published values that correspond to a well-known UUID. Once subscribed to a UUID, events that correspond to that UUID will be emitted. To receive these events you can add an event listener, for example...

const ble = new Bluetooth(id)
ble.subscribe(uuid)
ble.on(uuid, (data, details) => {
  // ...do something interesting
})
ArgumentTypeDefaultOptionalDescription
idstringfalseA well-known UUID
Return ValueTypeDescription
Not specifiedPromise<ipc.Result>

publish(id, value)

Start advertising a new value for a well-known UUID

ArgumentTypeDefaultOptionalDescription
idstringfalseA well-known UUID
valuestringfalse
Return ValueTypeDescription
Not specifiedPromise

Buffer

External docs: https://nodejs.org/api/buffer.html#buffer_class_buffer

The buffer module from node.js, for the browser.

Buffer

If Buffer.TYPED_ARRAY_SUPPORT: === true Use Uint8Array implementation (fastest) === false Print warning and recommend using buffer v4.x which has an Object implementation (most compatible, even IE6)

Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+.

We report that the browser does not support typed arrays if the are not subclassable using proto. Firefox 4-29 lacks support for adding new properties to Uint8Array (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support for proto and has a buggy typed array implementation.

undefined

If Buffer.TYPED_ARRAY_SUPPORT: === true Use Uint8Array implementation (fastest) === false Print warning and recommend using buffer v4.x which has an Object implementation (most compatible, even IE6)

Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+.

We report that the browser does not support typed arrays if the are not subclassable using proto. Firefox 4-29 lacks support for adding new properties to Uint8Array (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support for proto and has a buggy typed array implementation.

undefined

If Buffer.TYPED_ARRAY_SUPPORT: === true Use Uint8Array implementation (fastest) === false Print warning and recommend using buffer v4.x which has an Object implementation (most compatible, even IE6)

Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+.

We report that the browser does not support typed arrays if the are not subclassable using proto. Firefox 4-29 lacks support for adding new properties to Uint8Array (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support for proto and has a buggy typed array implementation.

undefined

If Buffer.TYPED_ARRAY_SUPPORT: === true Use Uint8Array implementation (fastest) === false Print warning and recommend using buffer v4.x which has an Object implementation (most compatible, even IE6)

Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+.

We report that the browser does not support typed arrays if the are not subclassable using proto. Firefox 4-29 lacks support for adding new properties to Uint8Array (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support for proto and has a buggy typed array implementation.

undefined

The Buffer constructor returns instances of Uint8Array that have their prototype changed to Buffer.prototype. Furthermore, Buffer is a subclass of Uint8Array, so the returned instances will have all the node Buffer methods and the Uint8Array methods. Square bracket notation works as expected -- it returns a single octet.

The Uint8Array prototype remains unmodified.

Buffer

Functionally equivalent to Buffer(arg, encoding) but throws a TypeError if value is a number. Buffer.from(str, encoding) Buffer.from(array) Buffer.from(buffer) Buffer.from(arrayBuffer[, byteOffset, length])

undefined

Functionally equivalent to Buffer(arg, encoding) but throws a TypeError if value is a number. Buffer.from(str, encoding) Buffer.from(array) Buffer.from(buffer) Buffer.from(arrayBuffer[, byteOffset, length])

undefined

Functionally equivalent to Buffer(arg, encoding) but throws a TypeError if value is a number. Buffer.from(str, encoding) Buffer.from(array) Buffer.from(buffer) Buffer.from(arrayBuffer[, byteOffset, length])

undefined

Functionally equivalent to Buffer(arg, encoding) but throws a TypeError if value is a number. Buffer.from(str, encoding) Buffer.from(array) Buffer.from(buffer) Buffer.from(arrayBuffer[, byteOffset, length])

Buffer

Creates a new filled Buffer instance. alloc(size[, fill, encoding])

undefined

Creates a new filled Buffer instance. alloc(size[, fill, encoding])

undefined

Creates a new filled Buffer instance. alloc(size[, fill, encoding])

undefined

Creates a new filled Buffer instance. alloc(size[, fill, encoding])

Buffer

Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.

undefined

Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.

undefined

Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.

undefined

Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.

Buffer

Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.

undefined

Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.

undefined

Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.

undefined

Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.

Crypto

Some high level methods around the crypto.subtle api for getting random bytes and hashing.

webcrypto

WebCrypto API

getRandomValues(buffer)

External docs: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues

Generate cryptographically strong random values into buffer

ArgumentTypeDefaultOptionalDescription
bufferTypedArrayfalse
Return ValueTypeDescription
Not specifiedTypedArray

RANDOM_BYTES_QUOTA

Maximum total size of random bytes per page

MAX_RANDOM_BYTES

Maximum total size for random bytes.

MAX_RANDOM_BYTES_PAGES

Maximum total amount of allocated per page of bytes (max/quota)

randomBytes(size)

Generate size random bytes.

ArgumentTypeDefaultOptionalDescription
sizenumberfalseThe number of bytes to generate. The size must not be larger than 2**31 - 1.
Return ValueTypeDescription
Not specifiedBufferA promise that resolves with an instance of socket.Buffer with random bytes.

createDigest(algorithm, message)

ArgumentTypeDefaultOptionalDescription
algorithmstringfalseSHA-1SHA-256SHA-384SHA-512
messageBuffer | TypedArray | DataViewfalseAn instance of socket.Buffer, TypedArray or Dataview.
Return ValueTypeDescription
Not specifiedPromiseA promise that resolves with an instance of socket.Buffer with the hash.

Dgram

This module provides an implementation of UDP datagram sockets. It does not (yet) provide any of the multicast methods or properties.

ERR_SOCKET_ALREADY_BOUND (extends SocketError)

Thrown when a socket is already bound.

ERR_SOCKET_DGRAM_IS_CONNECTED (extends SocketError)

Thrown when the socket is already connected.

ERR_SOCKET_DGRAM_NOT_CONNECTED (extends SocketError)

Thrown when the socket is not connected.

ERR_SOCKET_DGRAM_NOT_RUNNING (extends SocketError)

Thrown when the socket is not running (not bound or connected).

ERR_SOCKET_BAD_TYPE (extends TypeError)

Thrown when a bad socket type is used in an argument.

ERR_SOCKET_BAD_PORT (extends RangeError)

Thrown when a bad port is given.

createSocket(options, callback)

Creates a Socket instance. if ()

ArgumentTypeDefaultOptionalDescription
optionsstring | Objectfalseeither a string ('udp4' or 'udp6') or an options object
options.typestringtrueThe family of socket. Must be either 'udp4' or 'udp6'. Required.
options.reuseAddrbooleanfalsetrueWhen true socket.bind() will reuse the address, even if another process has already bound a socket on it. Default: false.
options.ipv6OnlybooleanfalsetrueSetting ipv6Only to true will disable dual-stack support, i.e., binding to address :: won't make 0.0.0.0 be bound. Default: false.
options.recvBufferSizenumbertrueSets the SO_RCVBUF socket value.
options.sendBufferSizenumbertrueSets the SO_SNDBUF socket value.
options.signalAbortSignaltrueAn AbortSignal that may be used to close a socket.
callbackfunctiontrueAttached as a listener for 'message' events. Optional.
Return ValueTypeDescription
Not specifiedSocket

Socket (extends EventEmitter)

New instances of dgram.Socket are created using dgram.createSocket(). The new keyword is not to be used to create dgram.Socket instances.

bind(port, address, callback)

External docs: https://nodejs.org/api/dgram.html#socketbindport-address-callback

Listen for datagram messages on a named port and optional address If address is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a 'listening' event is emitted and the optional callback function is called.

If binding fails, an 'error' event is emitted.

ArgumentTypeDefaultOptionalDescription
portnumberfalseThe port to to listen for messages on
addressstringfalseThe address to bind to (0.0.0.0)
callbackfunctionfalseWith no parameters. Called when binding is complete.

connect(port, host, connectListener)

External docs: https://nodejs.org/api/dgram.html#socketconnectport-address-callback

Associates the dgram.Socket to a remote address and port. Every message sent by this handle is automatically sent to that destination. Also, the socket will only receive messages from that remote peer. Trying to call connect() on an already connected socket will result in an ERR_SOCKET_DGRAM_IS_CONNECTED exception. If address is not provided, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets) will be used by default. Once the connection is complete, a 'connect' event is emitted and the optional callback function is called. In case of failure, the callback is called or, failing this, an 'error' event is emitted.

ArgumentTypeDefaultOptionalDescription
portnumberfalsePort the client should connect to.
hoststringtrueHost the client should connect to.
connectListenerfunctiontrueCommon parameter of socket.connect() methods. Will be added as a listener for the 'connect' event once.

disconnect()

External docs: https://nodejs.org/api/dgram.html#socketdisconnect

A synchronous function that disassociates a connected dgram.Socket from its remote address. Trying to call disconnect() on an unbound or already disconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED exception.

send(msg, offset, length, port, address, callback)

External docs: https://nodejs.org/api/dgram.html#socketsendmsg-offset-length-port-address-callback

Broadcasts a datagram on the socket. For connectionless sockets, the destination port and address must be specified. Connected sockets, on the other hand, will use their associated remote endpoint, so the port and address arguments must not be set.

The msg argument contains the message to be sent. Depending on its type, different behavior can apply. If msg is a Buffer, any TypedArray or a DataView, the offset and length specify the offset within the Buffer where the message begins and the number of bytes in the message, respectively. If msg is a String, then it is automatically converted to a Buffer with 'utf8' encoding. With messages that contain multi-byte characters, offset and length will be calculated with respect to byte length and not the character position. If msg is an array, offset and length must not be specified.

The address argument is a string. If the value of address is a host name, DNS will be used to resolve the address of the host. If address is not provided or otherwise nullish, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets) will be used by default.

If the socket has not been previously bound with a call to bind, the socket is assigned a random port number and is bound to the "all interfaces" address ('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

An optional callback function may be specified to as a way of reporting DNS errors or for determining when it is safe to reuse the buf object. DNS lookups delay the time to send for at least one tick of the Node.js event loop.

The only way to know for sure that the datagram has been sent is by using a callback. If an error occurs and a callback is given, the error will be passed as the first argument to the callback. If a callback is not given, the error is emitted as an 'error' event on the socket object.

Offset and length are optional but both must be set if either are used. They are supported only when the first argument is a Buffer, a TypedArray, or a DataView.

ArgumentTypeDefaultOptionalDescription
msgBuffer | TypedArray | DataView | string | ArrayfalseMessage to be sent.
offsetintegertrueOffset in the buffer where the message starts.
lengthintegertrueNumber of bytes in the message.
portintegertrueDestination port.
addressstringtrueDestination host name or IP address.
callbackFunctiontrueCalled when the message has been sent.

close(callback)

External docs: https://nodejs.org/api/dgram.html#socketclosecallback

Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the 'close' event.

ArgumentTypeDefaultOptionalDescription
callbackfunctiontrueCalled when the connection is completed or on error.

address()

External docs: https://nodejs.org/api/dgram.html#socketaddress

Returns an object containing the address information for a socket. For UDP sockets, this object will contain address, family, and port properties.

This method throws EBADF if called on an unbound socket.

Return ValueTypeDescription
socketInfoObjectInformation about the local socket
socketInfo.addressstringThe IP address of the socket
socketInfo.portstringThe port of the socket
socketInfo.familystringThe IP family of the socket

remoteAddress()

External docs: https://nodejs.org/api/dgram.html#socketremoteaddress

Returns an object containing the address, family, and port of the remote endpoint. This method throws an ERR_SOCKET_DGRAM_NOT_CONNECTED exception if the socket is not connected.

Return ValueTypeDescription
socketInfoObjectInformation about the remote socket
socketInfo.addressstringThe IP address of the socket
socketInfo.portstringThe port of the socket
socketInfo.familystringThe IP family of the socket

setRecvBufferSize(size)

External docs: https://nodejs.org/api/dgram.html#socketsetrecvbuffersizesize

Sets the SO_RCVBUF socket option. Sets the maximum socket receive buffer in bytes.

ArgumentTypeDefaultOptionalDescription
sizenumberfalseThe size of the new receive buffer

setSendBufferSize(size)

External docs: https://nodejs.org/api/dgram.html#socketsetsendbuffersizesize

Sets the SO_SNDBUF socket option. Sets the maximum socket send buffer in bytes.

ArgumentTypeDefaultOptionalDescription
sizenumberfalseThe size of the new send buffer

getRecvBufferSize()

External docs: https://nodejs.org/api/dgram.html#socketgetrecvbuffersize

getSendBufferSize()

External docs: https://nodejs.org/api/dgram.html#socketgetsendbuffersize

Return ValueTypeDescription
Not specifiednumberthe SO_SNDBUF socket send buffer size in bytes.

DNS

This module enables name resolution. For example, use it to look up IP addresses of host names. Although named for the Domain Name System (DNS), it does not always use the DNS protocol for lookups. dns.lookup() uses the operating system facilities to perform name resolution. It may not need to perform any network communication. To perform name resolution the way other applications on the same system do, use dns.lookup().

lookup(hostname, opts, cb)

External docs: https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback

Resolves a host name (e.g. example.org) into the first found A (IPv4) or AAAA (IPv6) record. All option properties are optional. If options is an integer, then it must be 4 or 6 – if options is 0 or not provided, then IPv4 and IPv6 addresses are both returned if found.

From the node.js website...

With the all option set to true, the arguments for callback change to (err, addresses), with addresses being an array of objects with the properties address and family.

On error, err is an Error object, where err.code is the error code. Keep in mind that err.code will be set to 'ENOTFOUND' not only when the host name does not exist but also when the lookup fails in other ways such as no available file descriptors. dns.lookup() does not necessarily have anything to do with the DNS protocol. The implementation uses an operating system facility that can associate names with addresses and vice versa. This implementation can have subtle but important consequences on the behavior of any Node.js program. Please take some time to consult the Implementation considerations section before using dns.lookup().

ArgumentTypeDefaultOptionalDescription
hostnamestringfalseThe host name to resolve.
optsObjecttrueAn options object.
opts.familynumber | string0falseThe record family. Must be 4, 6, or 0. For backward compatibility reasons,'IPv4' and 'IPv6' are interpreted as 4 and 6 respectively. The value 0 indicates that IPv4 and IPv6 addresses are both returned. Default: 0.
cbfunctionfalseThe function to call after the method is complete.

DNS.promises

This module enables name resolution. For example, use it to look up IP addresses of host names. Although named for the Domain Name System (DNS), it does not always use the DNS protocol for lookups. dns.lookup() uses the operating system facilities to perform name resolution. It may not need to perform any network communication. To perform name resolution the way other applications on the same system do, use dns.lookup().

lookup(hostname, opts)

External docs: https://nodejs.org/api/dns.html#dnspromiseslookuphostname-options

ArgumentTypeDefaultOptionalDescription
hostnamestringfalseThe host name to resolve.
optsObjecttrueAn options object.
opts.familynumber | string0falseThe record family. Must be 4, 6, or 0. For backward compatibility reasons,'IPv4' and 'IPv6' are interpreted as 4 and 6 respectively. The value 0 indicates that IPv4 and IPv6 addresses are both returned. Default: 0.
Return ValueTypeDescription
Not specifiedPromise

File System

This module enables interacting with the file system in a way modeled on standard POSIX functions.

The Application Sandbox restricts access to the file system. Please see the Application Sandbox documentation for more information: https://sockets.sh/guides/#working-with-the-file-system-on-ios

To use the promise-based APIs:

import * as fs from '@socketsupply/socket-api/fs/promises.js';

To use the callback and async APIs:

import * as fs from '@socketsupply/socket-api/fs/index.js';

access(path, mode , callback)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fsopenpath-flags-mode-callback

Asynchronously check access a file for a given mode calling callback upon success or error.

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
modestringF_OK(0)true
callbackfunction(err, fd)false

chmod(path, mode, callback)

External docs: https://nodejs.org/api/fs.html#fschmodpath-mode-callback

Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
modenumberfalse
callbackfunction(err)false

close(fd, callback)

Asynchronously close a file descriptor calling callback upon success or error.

ArgumentTypeDefaultOptionalDescription
fdnumberfalse
callbackfunction(err)true

copyFile()

This is a FunctionDeclaration named copyFile in fs/index.js, it's exported but undocumented.

createReadStream(path, options)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fscreatewritestreampath-options

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
optionsobjecttrue
Return ValueTypeDescription
Not specifiedfs.ReadStream

createWriteStream(path, options)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fscreatewritestreampath-options

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
optionsobjecttrue
Return ValueTypeDescription
Not specifiedfs.WriteStream

fstat(fd, options, callback)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fsfstatfd-options-callback

Invokes the callback with the <fs.Stats> for the file descriptor. See the POSIX fstat(2) documentation for more detail.

ArgumentTypeDefaultOptionalDescription
fdnumberfalseA file descriptor.
optionsObjecttrueAn options object.
callbackfunctionfalseThe function to call after completion.

open(path, flags , mode , callback)

Asynchronously open a file calling callback upon success or error.

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
flagsstringrtrue
modestring0o666true
callbackfunction(err, fd)false

opendir(path, options, callback)

Asynchronously open a directory calling callback upon success or error.

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
optionsObjecttrue
options.encodingstringutf8true
options.withFileTypesbooleanfalsetrue
callbackfunction(err, fd)false

read(fd, buffer, offset, length, position, callback)

Asynchronously read from an open file descriptor.

ArgumentTypeDefaultOptionalDescription
fdnumberfalse
bufferobject | Buffer | TypedArrayfalseThe buffer that the data will be written to.
offsetnumberfalseThe position in buffer to write the data to.
lengthnumberfalseThe number of bytes to read.
positionnumber | BigInt | nullfalseSpecifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged.
callbackfunction(err, bytesRead, buffer)false

readdir(path, options, callback)

Asynchronously read all entries in a directory.

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
optionsobjecttrue
options.encodingstringutf8true
options.withFileTypesbooleanfalsetrue
callbackfunction(err, buffer)false

readFile(path, options, callback)

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URL | numberfalse
optionsobjecttrue
options.encodingstringutf8true
options.flagstringrtrue
options.signalAbortSignaltrue
callbackfunction(err, buffer)false

stat(path, options, callback)

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URL | numberfalsefilename or file descriptor
optionsobjecttrue
options.encodingstringutf8true
options.flagstringrtrue
options.signalAbortSignaltrue
callbackfunction(err, data)false

writeFile(path, data, options, callback)

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URL | numberfalsefilename or file descriptor
datastring | Buffer | TypedArray | DataView | objectfalse
optionsobjecttrue
options.encodingstringutf8true
options.modestring0o666true
options.flagstringwtrue
options.signalAbortSignaltrue
callbackfunction(err)false

writev()

This is a FunctionDeclaration named writev in fs/index.js, it's exported but undocumented.

FS.promises

access(path, mode, options)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fspromisesaccesspath-mode

Asynchronously check access a file.

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
modestringtrue
optionsobjecttrue

chmod(path, mode)

External docs: https://nodejs.org/api/fs.html#fspromiseschmodpath-mode

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
modenumberfalse
Return ValueTypeDescription
Not specifiedPromise

mkdir(path, options)

Asynchronously creates a directory.

ArgumentTypeDefaultOptionalDescription
pathStringfalseThe path to create
optionsObjectfalseThe optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false.
Return ValueTypeDescription
Not specifiedPrimiseUpon success, fulfills with undefined if recursive is false, or the first directory path created if recursive is true.

open(path, flags, mode)

External docs: https://nodejs.org/api/fs.html#fspromisesopenpath-flags-mode

Asynchronously open a file.

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
flagsstringfalsedefault: 'r'
modestringfalsedefault: 0o666
Return ValueTypeDescription
Not specifiedPromise

opendir(path, options)

External docs: https://nodejs.org/api/fs.html#fspromisesopendirpath-options

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
optionsobjecttrue
options.encodingstringutf8true
options.bufferSizenumber32true
Return ValueTypeDescription
Not specifiedPromise<FileSystem,Dir>

readdir(path, options)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fspromisesreaddirpath-options

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
optionsobjecttrue
options.encodingstringutf8true
options.withFileTypesbooleanfalsetrue

readFile(path, options)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fspromisesreadfilepath-options

ArgumentTypeDefaultOptionalDescription
pathstringfalse
optionsobjecttrue
options.encodingstring | nullnulltrue
options.flagstringrtrue
options.signalAbortSignaltrue
Return ValueTypeDescription
Not specifiedPromise<Bufferstring>

stat(path, options)

External docs: https://nodejs.org/api/fs.html#fspromisesstatpath-options

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URLfalse
optionsobjecttrue
options.bigintbooleanfalsetrue
Return ValueTypeDescription
Not specifiedPromise

writeFile(path, data, options)

External docs: https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fspromiseswritefilefile-data-options

ArgumentTypeDefaultOptionalDescription
pathstring | Buffer | URL | FileHandlefalsefilename or FileHandle
datastring | Buffer | Array | DataView | TypedArray | Streamfalse
optionsobjecttrue
options.encodingstring | nullutf8false
options.modenumber0o666false
options.flagstringwfalse
options.signalAbortSignaltrue
Return ValueTypeDescription
Not specifiedPromise

FS.Stream

DEFAULT_STREAM_HIGH_WATER_MARK

This is a VariableDeclaration named DEFAULT_STREAM_HIGH_WATER_MARK in fs/stream.js, it's exported but undocumented.

ReadStream (extends Readable)

A Readable stream for a FileHandle.

constructor()

ReadStream class constructor

setHandle(handle)

Sets file handle for the ReadStream.

ArgumentTypeDefaultOptionalDescription
handleFileHandlefalse

highWaterMark()

The max buffer size for the ReadStream.

path()

Relative or absolute path of the underlying FileHandle.

pending()

true if the stream is in a pending state.

emit()

Handles shouldEmitClose setting from options.emitClose in constructor.

WriteStream (extends Writable)

A Writable stream for a FileHandle.

constructor()

WriteStream class constructor

setHandle(handle)

Sets file handle for the WriteStream.

ArgumentTypeDefaultOptionalDescription
handleFileHandlefalse

highWaterMark()

The max buffer size for the Writetream.

path()

Relative or absolute path of the underlying FileHandle.

pending()

true if the stream is in a pending state.

emit()

Handles shouldEmitClose setting from options.emitClose in constructor.

FileReadStream

This is a VariableDeclaration named FileReadStream in fs/stream.js, it's exported but undocumented.

FileWriteStream

This is a VariableDeclaration named FileWriteStream in fs/stream.js, it's exported but undocumented.

IPC

This is a low level API which you don't need unless you are implementing a library on top of Socket SDK. A Socket SDK app has two or three processes.

  • The Render process, the UI where the HTML, CSS and JS is run.
  • The Bridge process, the thin layer of code that managers everything.
  • The Main processs, for apps that need to run heavier compute jobs. And unlike electron it's optional.

    The Bridge process manages the Render and Main process, it may also broker data between them.

    The Binding process uses standard input and output as a way to communicate. Data written to the write-end of the pipe is buffered by the OS until it is read from the read-end of the pipe.

    The IPC protocol uses a simple URI-like scheme. Data is passed as ArrayBuffers.

    ipc://command?key1=value1&key2=value2...

postMessage()

This is a FunctionDeclaration named postMessage in ipc.js, it's exported but undocumented.

OK

Represents an OK IPC status.

ERROR

Represents an ERROR IPC status.

TIMEOUT

Timeout in milliseconds for IPC requests.

kDebugEnabled

Symbol for the ipc.debug.enabled property

parseSeq(seq, options)

Parses seq as integer value

ArgumentTypeDefaultOptionalDescription
seqstring | numberfalse
optionsobjecttrue
options.bigintbooleanfalsefalse

debug(enable)

If debug.enabled === true, then debug output will be printed to console.

ArgumentTypeDefaultOptionalDescription
enablebooleanfalse
Return ValueTypeDescription
Not specifiedboolean

Message (extends URL)

A container for a IPC message based on a ipc:// URI scheme.

PROTOCOL()

The expected protocol for an IPC message.

from(input, params)

Creates a Message instance from a variety of input.

ArgumentTypeDefaultOptionalDescription
inputstring | URL | Message | Buffer | objectfalse
paramsobject | string | URLSearchParamstrue
Return ValueTypeDescription
Not specifiedMessage

isValidInput(input)

Predicate to determine if input is valid for constructing a new Message instance.

ArgumentTypeDefaultOptionalDescription
inputstring | URL | Message | Buffer | objectfalse
Return ValueTypeDescription
Not specifiedboolean

constructor(input)

Message class constructor.

ArgumentTypeDefaultOptionalDescription
inputstring | URLfalse

command()

Computed IPC message name.

name()

Computed IPC message name.

id()

Computed id value for the command.

seq()

Computed seq (sequence) value for the command.

value()

Computed message value potentially given in message parameters. This value is automatically decoded, but not treated as JSON.

index()

Computed index value for the command potentially referring to the window index the command is scoped to or originating from. If not specified in the message parameters, then this value defaults to -1.

json()

Computed value parsed as JSON. This value is null if the value is not present or it is invalid JSON.

params()

Computed readonly object of message parameters.

entries()

Returns computed parameters as entries

Return ValueTypeDescription
Not specifiedArray<Array<string,mixed>>

set(key, value)

Set a parameter value by key.

ArgumentTypeDefaultOptionalDescription
keystringfalse
valuemixedfalse

get(key, defaultValue)

Get a parameter value by key.

ArgumentTypeDefaultOptionalDescription
keystringfalse
defaultValuemixedfalse
Return ValueTypeDescription
Not specifiedmixed

delete(key)

Delete a parameter by key.

ArgumentTypeDefaultOptionalDescription
keystringfalse
Return ValueTypeDescription
Not specifiedboolean

keys()

Computed parameter keys.

Return ValueTypeDescription
Not specifiedArray

values()

Computed parameter values.

Return ValueTypeDescription
Not specifiedArray

has(key)

Predicate to determine if parameter key is present in parameters.

ArgumentTypeDefaultOptionalDescription
keystringfalse
Return ValueTypeDescription
Not specifiedboolean

toJSON()

Converts a Message instance into a plain JSON object.

Result

A result type used internally for handling IPC result values from the native layer that are in the form of { err?, data? }. The data and err properties on this type of object are in tuple form and be accessed at [data?,err?]

from(result, maybeError, maybeSource)

Creates a Result instance from input that may be an object like { err?, data? }, an Error instance, or just data.

ArgumentTypeDefaultOptionalDescription
resultobject | Error | mixedtrue
maybeErrorErrortrue
maybeSourcestringtrue
Return ValueTypeDescription
Not specifiedResult

constructor(err , data , source )

Result class constructor.

ArgumentTypeDefaultOptionalDescription
errErrornulltrue
dataobjectnulltrue
sourcestringundefinedtrue

length()

Computed result length.

ready()

Waits for the native IPC layer to be ready and exposed on the global window object.

sendSync(command, params)

Sends a synchronous IPC command over XHR returning a Result upon success or error.

ArgumentTypeDefaultOptionalDescription
commandstringfalse
paramsobject | stringtrue
Return ValueTypeDescription
Not specifiedResult

emit(name, value, target , options)

Emit event to be dispatched on window object.

ArgumentTypeDefaultOptionalDescription
namestringfalse
valueMixedfalse
targetEventTargetwindowtrue
optionsObjecttrue

resolve(seq, value)

Resolves a request by seq with possible value.

ArgumentTypeDefaultOptionalDescription
seqstringfalse
valueMixedfalse

send(command, value)

Sends an async IPC command request with parameters.

ArgumentTypeDefaultOptionalDescription
commandstringfalse
valueMixedtrue
Return ValueTypeDescription
Not specifiedPromise

write(command, params, buffer, options)

Sends an async IPC command request with parameters and buffered bytes.

ArgumentTypeDefaultOptionalDescription
commandstringfalse
paramsobjecttrue
bufferBuffer | TypeArray | ArrayBuffer | string | Arraytrue
optionsobjecttrue

request(command, params, options)

Sends an async IPC command request with parameters requesting a response with buffered bytes.

ArgumentTypeDefaultOptionalDescription
commandstringfalse
paramsobjecttrue
optionsobjecttrue

createBinding(domain, ctx)

Factory for creating a proxy based IPC API.

ArgumentTypeDefaultOptionalDescription
domainstringfalse
ctxfunction | objecttrue
ctx.defaultstringtrue
Return ValueTypeDescription
Not specifiedProxy

OS

This module provides normalized system information from all the major operating systems.

arch()

This is a FunctionDeclaration named arch in os.js, it's exported but undocumented.

networkInterfaces()

This is a FunctionDeclaration named networkInterfaces in os.js, it's exported but undocumented.

platform()

This is a FunctionDeclaration named platform in os.js, it's exported but undocumented.

type()

This is a FunctionDeclaration named type in os.js, it's exported but undocumented.

isWindows()

This is a FunctionDeclaration named isWindows in os.js, it's exported but undocumented.

tmpdir()

This is a FunctionDeclaration named tmpdir in os.js, it's exported but undocumented.

EOL

This is a VariableDeclaration named EOL in os.js, it's exported but undocumented.

Path

Path

This is a ClassDeclaration named Path in path/path.js, it's exported but undocumented.

cwd(opts)

Computes current working directory for a path

ArgumentTypeDefaultOptionalDescription
optsobjecttrue
opts.posix Set to true to force POSIX style pathbooleantrue

constructor(opts)

Path class constructor.

ArgumentTypeDefaultOptionalDescription
optsobjecttrue
opts.rootstringtrue
opts.basestringtrue
opts.namestringtrue
opts.dirstringtrue
opts.extstringtrue

resolve()

normalize()

Process

homedir()

Return ValueTypeDescription
Not specifiedstringThe home directory of the current user.

exit(code)

ArgumentTypeDefaultOptionalDescription
codenumber0trueThe exit code. Default: 0.

Runtime

Provides runtime-specific methods

currentWindow

This is a VariableDeclaration named currentWindow in runtime.js, it's exported but undocumented.

debug

This is a VariableDeclaration named debug in runtime.js, it's exported but undocumented.

config

This is a VariableDeclaration named config in runtime.js, it's exported but undocumented.

send()

This is a FunctionDeclaration named send in runtime.js, it's exported but undocumented.

getWindows()

This is a FunctionDeclaration named getWindows in runtime.js, it's exported but undocumented.

openExternal()

This is a FunctionDeclaration named openExternal in runtime.js, it's exported but undocumented.

exit(options)

Quits the backend process and then quits the render process, the exit code used is the final exit code to the OS.

ArgumentTypeDefaultOptionalDescription
optionsobjectfalsean options object
Return ValueTypeDescription
Not specifiedPromise

setTitle(options)

Sets the title of the window (if applicable).

ArgumentTypeDefaultOptionalDescription
optionsobnjectfalsean options object
Return ValueTypeDescription
Not specifiedPromise<ipc.Result>

inspect()

This is a FunctionDeclaration named inspect in runtime.js, it's exported but undocumented.

show(opts)

ArgumentTypeDefaultOptionalDescription
optsobjectfalsean options object
Return ValueTypeDescription
Not specifiedPromise<ipc.Result>

hide(opts)

ArgumentTypeDefaultOptionalDescription
optsobjectfalsean options object
Return ValueTypeDescription
Not specifiedPromise<ipc.Result>

navigate(opts)

ArgumentTypeDefaultOptionalDescription
optsobjectfalsean options object
opts.windownumbercurrentWindowfalsethe index of the window
opts.urlnumberfalsethe path to the HTML file to load into the window
Return ValueTypeDescription
Not specifiedPromise<ipc.Result>

setWindowBackgroundColor()

This is a FunctionDeclaration named setWindowBackgroundColor in runtime.js, it's exported but undocumented.

setContextMenu(options)

Opens a native context menu.

ArgumentTypeDefaultOptionalDescription
optionsobjectfalsean options object
Return ValueTypeDescription
Not specifiedPromise

setSystemMenuItemEnabled()

This is a FunctionDeclaration named setSystemMenuItemEnabled in runtime.js, it's exported but undocumented.

setSystemMenu(options)

Set the native menu for the app.

Socket Runtime provides a minimalist DSL that makes it easy to create cross platform native system and context menus.

Menus are created at run time. They can be created from either the Main or Render process. The can be recreated instantly by calling the setSystemMenu method.

The method takes a string. Here's an example of a menu. The semi colon is significant indicates the end of the menu. Use an underscore when there is no accelerator key. Modifiers are optional. And well known OS menu options like the edit menu will automatically get accelerators you dont need to specify them.

socket.runtime.setSystemMenu({ index: 0, value: `
  App:
    Foo: f;

  Edit:
    Cut: x
    Copy: c
    Paste: v
    Delete: _
    Select All: a;

  Other:
    Apple: _
    Another Test: T
    !Im Disabled: I
    Some Thing: S + Meta
    ---
    Bazz: s + Meta, Control, Alt;
`)

Separators

To create a separator, use three dashes ---.

Accelerator Modifiers

Accelerator modifiers are used as visual indicators but don't have a material impact as the actual key binding is done in the event listener.

A capital letter implies that the accelerator is modified by the Shift key.

Additional accelerators are Meta, Control, Option, each separated by commas. If one is not applicable for a platform, it will just be ignored.

On MacOS Meta is the same as Command.

Disabled Items

If you want to disable a menu item just prefix the item with the ! character. This will cause the item to appear disabled when the system menu renders.

Submenus

We feel like nested menus are an anti-pattern. We don't use them. If you have a strong argument for them and a very simple pull request that makes them work we may consider them.

Event Handling

When a menu item is activated, it raises the menuItemSelected event in the front end code, you can then communicate with your backend code if you want from there.

For example, if the Apple item is selected from the Other menu...

0.2.17

2 years ago

0.2.16

2 years ago

0.2.15

2 years ago

0.2.14

2 years ago

0.2.13

2 years ago

0.2.11

2 years ago

0.2.10

2 years ago

0.2.9

2 years ago

0.2.8

3 years ago

0.2.7

3 years ago

0.2.6

3 years ago