Swiftpack.co - Package - refectjam/scoly

Scoly

  • JavaScript runtime for macOS

get started

install

Package.swift
// swift-tools-version:4.0

// ...

// add to to dependencies
.package(
  url: "https://github.com/refectjam/scoly.git",
  from: "0.1.0")

// ...

// add to target's dependencies
.target(
  name: ...,
  dependencies: ["Scoly", ...])

example

main.swift
import Scoly
import Foundation // import RunLoop

// define services
enum Console: ScolyFixedService {
  static
  let namespace = "Console"

  static
  let api: Scoly.Service.Api =
    [ "log": log ]

  static
  let log: @convention(block) (String) -> Void =
    { print("JS: \($0)") }
}

class Counter: ScolyVariableService {
  var value = 0

  let namespace = "Counter"

  var api: Scoly.Service.Api {
    return [ "increment": increment ]
  }

  var increment: @convention(block) () -> Int {
    return {
      self.value += 1
      return self.value
    }
  }
}

// execute script
let incrementAndLogJS =
  """
  Counter
    .increment()
    .then(Console.log) // JS: 1
    .then(Counter.increment)
    .then(Console.log) // JS: 2
  """

Scoly.launch(
  script: incrementAndLogJS,
  with: [
    Console.scolyService,
    Counter().scolyService])

RunLoop.current.run() // used to keep process alive

api

  • Scoly.launch(script:with:)

    • script: String
    • with: [Scoly.Service]

    notes:

    • executes provided JavaScript
    • mounts services alongside script
  • Scoly.read(scriptAtPath:) throws -> String

    • scriptAtPath: String

    notes:

    • returns file located at path as String

    • path can either be absolute or relative to current directory

    • errors if file could not be read

concrete types

  • enum Scoly.Service

    • case fixed(ScolyFixedService.Type)
    • case variable(ScolyVariableService)

    notes:

    • facilitates service loading

    • ScolyFixedService and ScolyVariableService are extended with var scolyService: Scoly.Service, which supplies their corresponding case

  • typealias Scoly.Service.Api = [String: Any]

    notes:

    • associated JavaScript loosely maps to <<Scoly.Service>.namespace>.<String> = <Any>

    • Any should match @convention(block) <Closure Signature>

    • invocations of <Any> are wrapped in a Promise, and resolve when the native code returns

protocols

  • ScolyFixedService

    • static var namespace: String { get }
    • static var api: Scoly.Service.Api { get }

    notes:

    • preferred service type
  • ScolyVariableService

    • var namespace: String { get }
    • var api: Scoly.Service.Api { get }

    notes:

    • ideal for service that has internal state

caveats

  • running on iOS, tvOS, or watchOS should be feasible, but hurdles remain in package management

  • does not run on Linux, since the Objective-C runtime included on Apple platforms is required

  • no built-in services 😱

Github

link
Stars: 0
Help us keep the lights on

Dependencies

Used By

Total: 0