Latest Threat Research:SANDWORM_MODE: Shai-Hulud-Style npm Worm Hijacks CI Workflows and Poisons AI Toolchains.Details
Socket
Book a DemoInstallSign in
Socket

@checle/zones

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@checle/zones

Simplistic, promise-based zones

Source
npmnpm
Version
0.6.0
Version published
Weekly downloads
6
Maintainers
1
Weekly downloads
 
Created
Source

zones

by Filip Dalüge

Build status

For a primer on zones in Dart, take a look at the Dart article. Find the complete API here.

Installation

Install using NPM:

npm install --save web-zones

Import zones:


import * as zones from 'web-zones'

Object.assign(global, zones) // Optionally, shim the host API (overrides setTimeout, Promise etc.)

Usage

Wait for operations

await Zone.exec(applicationFunction)

Listen to state

Zone.current.addEventListener('error', listener)

Cancel pending operations

Zone.current.cancel()

Bind function

func = Zone.current.bind(func)

Number of scheduled tasks

Zone.current.size

Examples

Instantiate a zone and listen for events

Create a zone object and listen for status events.

var zone = new Zone('custom-zone')

zone.addEventListener('finish', () => console.log('Zone has terminated'))
zone.addEventListener('error', error => console.log('Error occurred'))

function application () {
  setTimeout(() => null, 1000)
}

zone.run(application)

Asynchronous operations

Run an application that reads a file making use of asynchronous JS APIs. The result is then awaited, and its content printed.

import * as fs from 'fs'

// Application with unknown asynchronous operations
function application() {
  // Waits for a second
  setTimeout(readFile, 1000)

  function readFile () {
    // Read asynchronously
    fs.readFile('data.txt', data => {
      global.fileContent = data
    })
  }
}

try {
  // Call and wait for spawned tasks to terminate
  await Zone.exec(application)

  console.log('This file content has been read: ' + global.fileContent)
} catch (error) {
  console.log('Either setTimeout or fs.readFile threw an uncatched error')
}

Execute tasks parallely

Run three processes using Promise.all and wait for them to finish. Cancel any other zones if one zone throws an error.

try {
  await Promise.all([
    Zone.exec(app1),
    Zone.exec(app2),
    Zone.exec(app3),
  ])

  console.log('All tasks have concluded successfully')
} catch (error) {
  console.log('One zone errored')

  // Cancel all remaining zones
  Zone.current.cancel()
}

Extend zones

Add custom properties to Zone.current by inheritance.

class CustomEnvironment extends Zone {
  constructor () {
    super('custom-environment')

    this.created = Date.now()
  }
}

function routine () {
  if (Zone.current instanceof CustomEnvironment) {
    console.log('My environment was created at ' + this.created)
  } else {
    console.log("I think I've been running forever")
  }
}

Zone.current.run(routine) // "I think I've been running forever"

new CustomEnvironment().run(routine) // Prints the creation date

Override run()

You can hook into zone operations overriding run().

class MozillaZone extends Zone {
  run (func) {
    let previousDomain = global.domain

    try {
      global.domain = 'mozilla.org' // Switch global domain during run()

      return super.run(func)
    } finally {
      global.domain = previousDomain // Restore global domain
    }
  }
}

global.domain = 'example.com'

new MozillaZone().run(() => console.log(global.domain)) // "mozilla.org"

Zone.current.run(() => console.log(global.domain)) // "example.com"

Run untrusted code asynchronously

Run code in a sandbox using NodeJS' vm module and print the result.

const vm = require('vm')

// Create a sandbox global object
let sandbox = {print: console.log}

// Copies setTimeout, setInterval and Promise polyfills to the sandbox
Object.assign(sandbox, zone)

let applicationCode = `
  if (typeof console !== 'undefined') {
    console.log("I'm not that secure, it seems.")
  } else {
    print('Oh yes, I am.')
  }
`

try {
  // Use exec with vm to run a program in an isolated environment
  let result = await Zone.exec(() => vm.runInNewContext(applicationCode, sandbox))

  console.log('Terminated successfully with result', result)
} catch (error) {
  console.log('An error occurred')
)

API

interface Zone implements EventTarget {
  static current: Zone // Current zone

  // Run an entry function and resolve the result when all dependent tasks have
  // finished or reject the result and cancel pending tasks when an uncatched
  // error is thrown by any task
  static exec (entry: Function): Function

  readonly id: any // Optional ID
  readonly size: number // Number of pending tasks

  constructor (id?: any, spec?: any)

  // Add and manage custom tasks
  add (task: {cancel?: Function}, type?: string | symbol): number
  set (id: any, task: {cancel?: Function}, type?: string | symbol): this
  get (id: any, type?: string | symbol): any
  has (id: any, type?: string | symbol): boolean
  delete (id: any, type?: string | symbol): boolean

  async cancel (id?: any, type?: string | symbol): void // Cancel a task
  async cancel (): void // Cancel all in current and child zones

  // Run function inside zone; promise resolves immediately when microtasks
  // have been worked off
  run (entry: Function, thisArg?: any, ...args: any[]): any

  // Bind function to zone
  bind (fn: Function): Function

  // Add event listeners
  addEventListener(type: 'finish' | 'error', listener: Function, options: any): void
}

// Zone-supporting standard API
function setTimeout (handler, timeout, ...args)
function setInterval (handler, timeout, ...args)
function clearTimeout (id)
function clearInterval (id)
function Promise (executor)

License

MIT © 2016 Filip Dalüge (license)

FAQs

Package last updated on 24 May 2017

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