'Syntaxerror: invalid shorthand property initializer' for anonymous type in Microsoft ClearScript

121 views Asked by At

I would like to create a basic .NET wrapper for the markdown-it JavaScript library (see markdown-it.js source-code here). To accomplish this, I am using Microsoft ClearScript.

Please note that my knowledge of JavaScript is quite limited, and this is only the second JavaScript library I am attempting to integrate into .NET. So, similarly, my experience with Microsoft's ClearScript is also limited.

Well. After a simple research I understand that the Invalid shorthand property initializer error, in JavaScript, comes when we use equals operator (=) rather than colon (:) to separate key-values(properties) in object, that's ok, but the question is: how to solve the issue when trying to create and use that kind of key-values(properties) object in Microsoft ClearScript?.

This is what I have:

Public Shared Function ConvertMarkdownToHtml(str As String,
                                             Optional presetName As String = Nothing,
                                             Optional options As Object = Nothing) As String

    ' I set these values just to test the issue.
    presetName = "default"
    options = New With {.linkify = True}

    Dim htmlOutput As String
    Using engine As New V8ScriptEngine("markdownit_engine", V8ScriptEngineFlags.DisableGlobalMembers)

        ' https://raw.githubusercontent.com/markdown-it/markdown-it/master/dist/markdown-it.js
        Dim markdownItCode As String = My.Resources.markdown_it
        engine.Execute(markdownItCode)
        engine.Execute($"md = new markdownit('{presetName}', {options});
                         var renderResult = md.render('{str}');")

        htmlOutput = CStr(engine.Evaluate("renderResult"))

        engine.CollectGarbage(exhaustive:=True)
    End Using

    Return htmlOutput
End Function

As you can see in the code above, I'm using an anonymous type to create the options object. I think that object is sent and translated to the render function with "=" separators instead of ":", but I don't have idea how to solve that in this situation.


Finally, and if helpful, this is what the render function documentation says:

* new MarkdownIt([presetName, options])
* - presetName (String): optional, `commonmark` / `zero`
* - options (Object)
*
* Creates parser instanse with given config. Can be called without `new`.
*
* ##### presetName
*
* MarkdownIt provides named presets as a convenience to quickly
* enable/disable active syntax rules and options for common use cases.
*
* - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.js) -
*   configures parser to strict [CommonMark](http://commonmark.org/) mode.
* - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.js) -
*   similar to GFM, used when no preset name given. Enables all available rules,
*   but still without html, typographer & autolinker.
* - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.js) -
*   all rules disabled. Useful to quickly setup your config via `.enable()`.
*   For example, when you need only `bold` and `italic` markup and nothing else.
*
* ##### options:
*
* - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful!
*   That's not safe! You may need external sanitizer to protect output from XSS.
*   It's better to extend features via plugins, instead of enabling HTML.
* - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags
*   (`<br />`). This is needed only for full CommonMark compatibility. In real
*   world you will need HTML output.
* - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `<br>`.
* - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks.
*   Can be useful for external highlighters.
* - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links.
* - __typographer__  - `false`. Set `true` to enable [some language-neutral
*   replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js) +
*   quotes beautification (smartquotes).
* - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement
*   pairs, when typographer enabled and smartquotes on. For example, you can
*   use `'«»„“'` for Russian, `'„“‚‘'` for German, and
*   `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp).
* - __highlight__ - `null`. Highlighter function for fenced code blocks.
*   Highlighter `function (str, lang)` should return escaped HTML. It can also
*   return empty string if the source was not changed and should be escaped
*   externaly. If result starts with <pre... internal wrapper is skipped.
*
* ##### Example
*
* ```javascript
* // commonmark mode
* var md = require('markdown-it')('commonmark');
*
* // default mode
* var md = require('markdown-it')();
*
* // enable everything
* var md = require('markdown-it')({
*   html: true,
*   linkify: true,
*   typographer: true
* });
* ```

UPDATE

I've discovered a dirty way to fix the issue, by converting the anonymous type to string and doing some replacements:

Public Class MarkdownItOptions

    Public Sub New()
    End Sub

    Public Property Html As Boolean
    Public Property XhtmlOutput As Boolean
    Public Property BreakLines As Boolean
    Public Property LangPrefix As String = "language-"
    Public Property Linkify As Boolean
    Public Property Typographer As Boolean
    Public Property Quotes As String = "“”‘’"

    ''' <summary>
    ''' Builds the 'options' object to pass to the Markdown-It's 'render' function.
    ''' </summary>
    Protected Friend Function BuildMarkdownItOptionsObject() As String
        Dim options As New With {
            .html = Me.Html,
            .xhtmlOut = Me.XhtmlOutput,
            .breaks = Me.BreakLines,
            .langPrefix = $"'{Me.LangPrefix}'",
            .linkify = Me.Linkify,
            .typographer = Me.Typographer,
            .quotes = $"'{Me.Quotes}'"
        }

        Return options.ToString().Replace(" =", ":"c).
                                  Replace(": True", ": true").
                                  Replace(": False", ": false")
    End Function

End Class

This approach works fine for this specific situation, but it seems unsafe to manually do string replacements, it may not work in other situations when the property values are different and not convertible to string. So I keep this question open in search for a proper solution.

0

There are 0 answers