Skip to content

Add init(unsafelyWrapping:JSObject) on @JS struct #510

@MaxDesiatov

Description

@MaxDesiatov

The goal is to support the following code

import JavaScriptKit

@JS protocol JSON {
    func parse(_ message: String) throws(JSException) -> JSObject
    func serialize(_ message: JSObject) throws(JSException) -> String
}

@JSGetter(from: .global) var json: JSON

@JS struct ShoppingCart {
    var x: Int

    @JS public func toJSON() throws(JSException) -> String {
        json.serialize(self.jsObject)
    }

    @JS static public func fromJSON(_ string: String) throws(JSException) -> ShoppingCart {
        self.init(unsafelyWrapping: json.parse(string))
    }
}

There's an opinion that such struct should follow value semantics, for which it has to copy its property values out to Wasm linear memory out of JS. To control copying strategies we might consider adding an argument to @JS controlling this, i.e. @JS(copy: .lazy), @JS(copy: .eager).

In the long term we should also support @JS struct Foo: ~Copyable that avoids copies altogether and always gives access to backing JS object reference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationenhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions