Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Experiment] Build the JS API with Deno instead of Rollup #1556

Closed
wants to merge 2 commits into from
Closed

[Experiment] Build the JS API with Deno instead of Rollup #1556

wants to merge 2 commits into from

Conversation

Pierstoval
Copy link
Contributor

@Pierstoval Pierstoval commented Apr 21, 2021

⚠ This is an experiment, so this is not (yet?) ought to be merged.


As you can see, to build with deno, a very few amount of changes are necessary in order to make it work:

  • Update all imports to add the .ts suffix to TS imports
  • Instead of relying on node_modules to import the generator-runtime lib, use the one from Unpkg which is already bundled
  • Update tsconfig.json to use the Deno lib and specify the usage of the DOM library (since it's mostly dedicated to browsers)
  • Run deno bundle src/bundle.ts --config=./tsconfig.json dist/bundle.js, and the code is bundled.

Of course, it must be checked by Tauri experts to be sure it contains everything one needs to use the API!

⬇ Click here to see the contents of the generated `bundle.js` file
var runtime = function(exports) {
    "use strict";
    var Op = Object.prototype;
    var hasOwn = Op.hasOwnProperty;
    var undefined;
    var $Symbol = typeof Symbol === "function" ? Symbol : {
    };
    var iteratorSymbol = $Symbol.iterator || "@@iterator";
    var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
    var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
    function define(obj, key, value) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
        return obj[key];
    }
    try {
        define({
        }, "");
    } catch (err) {
        define = function(obj, key, value) {
            return obj[key] = value;
        };
    }
    function wrap(innerFn, outerFn, self, tryLocsList) {
        var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
        var generator = Object.create(protoGenerator.prototype);
        var context = new Context(tryLocsList || []);
        generator._invoke = makeInvokeMethod(innerFn, self, context);
        return generator;
    }
    exports.wrap = wrap;
    function tryCatch(fn, obj, arg) {
        try {
            return {
                type: "normal",
                arg: fn.call(obj, arg)
            };
        } catch (err) {
            return {
                type: "throw",
                arg: err
            };
        }
    }
    var GenStateSuspendedStart = "suspendedStart";
    var GenStateSuspendedYield = "suspendedYield";
    var GenStateExecuting = "executing";
    var GenStateCompleted = "completed";
    var ContinueSentinel = {
    };
    function Generator() {
    }
    function GeneratorFunction() {
    }
    function GeneratorFunctionPrototype() {
    }
    var IteratorPrototype = {
    };
    IteratorPrototype[iteratorSymbol] = function() {
        return this;
    };
    var getProto = Object.getPrototypeOf;
    var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
    if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
        IteratorPrototype = NativeIteratorPrototype;
    }
    var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
    GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
    GeneratorFunctionPrototype.constructor = GeneratorFunction;
    GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction");
    function defineIteratorMethods(prototype) {
        [
            "next",
            "throw",
            "return"
        ].forEach(function(method) {
            define(prototype, method, function(arg) {
                return this._invoke(method, arg);
            });
        });
    }
    exports.isGeneratorFunction = function(genFun) {
        var ctor = typeof genFun === "function" && genFun.constructor;
        return ctor ? ctor === GeneratorFunction || (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
    };
    exports.mark = function(genFun) {
        if (Object.setPrototypeOf) {
            Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
        } else {
            genFun.__proto__ = GeneratorFunctionPrototype;
            define(genFun, toStringTagSymbol, "GeneratorFunction");
        }
        genFun.prototype = Object.create(Gp);
        return genFun;
    };
    exports.awrap = function(arg) {
        return {
            __await: arg
        };
    };
    function AsyncIterator(generator, PromiseImpl) {
        function invoke(method, arg, resolve, reject) {
            var record = tryCatch(generator[method], generator, arg);
            if (record.type === "throw") {
                reject(record.arg);
            } else {
                var result = record.arg;
                var value = result.value;
                if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
                    return PromiseImpl.resolve(value.__await).then(function(value1) {
                        invoke("next", value1, resolve, reject);
                    }, function(err) {
                        invoke("throw", err, resolve, reject);
                    });
                }
                return PromiseImpl.resolve(value).then(function(unwrapped) {
                    result.value = unwrapped;
                    resolve(result);
                }, function(error) {
                    return invoke("throw", error, resolve, reject);
                });
            }
        }
        var previousPromise;
        function enqueue(method, arg) {
            function callInvokeWithMethodAndArg() {
                return new PromiseImpl(function(resolve, reject) {
                    invoke(method, arg, resolve, reject);
                });
            }
            return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
        }
        this._invoke = enqueue;
    }
    defineIteratorMethods(AsyncIterator.prototype);
    AsyncIterator.prototype[asyncIteratorSymbol] = function() {
        return this;
    };
    exports.AsyncIterator = AsyncIterator;
    exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
        if (PromiseImpl === void 0) PromiseImpl = Promise;
        var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
        return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function(result) {
            return result.done ? result.value : iter.next();
        });
    };
    function makeInvokeMethod(innerFn, self, context) {
        var state = GenStateSuspendedStart;
        return function invoke(method, arg) {
            if (state === GenStateExecuting) {
                throw new Error("Generator is already running");
            }
            if (state === GenStateCompleted) {
                if (method === "throw") {
                    throw arg;
                }
                return doneResult();
            }
            context.method = method;
            context.arg = arg;
            while(true){
                var delegate = context.delegate;
                if (delegate) {
                    var delegateResult = maybeInvokeDelegate(delegate, context);
                    if (delegateResult) {
                        if (delegateResult === ContinueSentinel) continue;
                        return delegateResult;
                    }
                }
                if (context.method === "next") {
                    context.sent = context._sent = context.arg;
                } else if (context.method === "throw") {
                    if (state === GenStateSuspendedStart) {
                        state = GenStateCompleted;
                        throw context.arg;
                    }
                    context.dispatchException(context.arg);
                } else if (context.method === "return") {
                    context.abrupt("return", context.arg);
                }
                state = GenStateExecuting;
                var record = tryCatch(innerFn, self, context);
                if (record.type === "normal") {
                    state = context.done ? GenStateCompleted : GenStateSuspendedYield;
                    if (record.arg === ContinueSentinel) {
                        continue;
                    }
                    return {
                        value: record.arg,
                        done: context.done
                    };
                } else if (record.type === "throw") {
                    state = GenStateCompleted;
                    context.method = "throw";
                    context.arg = record.arg;
                }
            }
        };
    }
    function maybeInvokeDelegate(delegate, context) {
        var method = delegate.iterator[context.method];
        if (method === undefined) {
            context.delegate = null;
            if (context.method === "throw") {
                if (delegate.iterator["return"]) {
                    context.method = "return";
                    context.arg = undefined;
                    maybeInvokeDelegate(delegate, context);
                    if (context.method === "throw") {
                        return ContinueSentinel;
                    }
                }
                context.method = "throw";
                context.arg = new TypeError("The iterator does not provide a 'throw' method");
            }
            return ContinueSentinel;
        }
        var record = tryCatch(method, delegate.iterator, context.arg);
        if (record.type === "throw") {
            context.method = "throw";
            context.arg = record.arg;
            context.delegate = null;
            return ContinueSentinel;
        }
        var info = record.arg;
        if (!info) {
            context.method = "throw";
            context.arg = new TypeError("iterator result is not an object");
            context.delegate = null;
            return ContinueSentinel;
        }
        if (info.done) {
            context[delegate.resultName] = info.value;
            context.next = delegate.nextLoc;
            if (context.method !== "return") {
                context.method = "next";
                context.arg = undefined;
            }
        } else {
            return info;
        }
        context.delegate = null;
        return ContinueSentinel;
    }
    defineIteratorMethods(Gp);
    define(Gp, toStringTagSymbol, "Generator");
    Gp[iteratorSymbol] = function() {
        return this;
    };
    Gp.toString = function() {
        return "[object Generator]";
    };
    function pushTryEntry(locs) {
        var entry = {
            tryLoc: locs[0]
        };
        if (1 in locs) {
            entry.catchLoc = locs[1];
        }
        if (2 in locs) {
            entry.finallyLoc = locs[2];
            entry.afterLoc = locs[3];
        }
        this.tryEntries.push(entry);
    }
    function resetTryEntry(entry) {
        var record = entry.completion || {
        };
        record.type = "normal";
        delete record.arg;
        entry.completion = record;
    }
    function Context(tryLocsList) {
        this.tryEntries = [
            {
                tryLoc: "root"
            }
        ];
        tryLocsList.forEach(pushTryEntry, this);
        this.reset(true);
    }
    exports.keys = function(object) {
        var keys = [];
        for(var key in object){
            keys.push(key);
        }
        keys.reverse();
        return function next() {
            while(keys.length){
                var key1 = keys.pop();
                if (key1 in object) {
                    next.value = key1;
                    next.done = false;
                    return next;
                }
            }
            next.done = true;
            return next;
        };
    };
    function values(iterable) {
        if (iterable) {
            var iteratorMethod = iterable[iteratorSymbol];
            if (iteratorMethod) {
                return iteratorMethod.call(iterable);
            }
            if (typeof iterable.next === "function") {
                return iterable;
            }
            if (!isNaN(iterable.length)) {
                var i = -1, next = function next1() {
                    while((++i) < iterable.length){
                        if (hasOwn.call(iterable, i)) {
                            next1.value = iterable[i];
                            next1.done = false;
                            return next1;
                        }
                    }
                    next1.value = undefined;
                    next1.done = true;
                    return next1;
                };
                return next.next = next;
            }
        }
        return {
            next: doneResult
        };
    }
    exports.values = values;
    function doneResult() {
        return {
            value: undefined,
            done: true
        };
    }
    Context.prototype = {
        constructor: Context,
        reset: function(skipTempReset) {
            this.prev = 0;
            this.next = 0;
            this.sent = this._sent = undefined;
            this.done = false;
            this.delegate = null;
            this.method = "next";
            this.arg = undefined;
            this.tryEntries.forEach(resetTryEntry);
            if (!skipTempReset) {
                for(var name in this){
                    if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
                        this[name] = undefined;
                    }
                }
            }
        },
        stop: function() {
            this.done = true;
            var rootEntry = this.tryEntries[0];
            var rootRecord = rootEntry.completion;
            if (rootRecord.type === "throw") {
                throw rootRecord.arg;
            }
            return this.rval;
        },
        dispatchException: function(exception) {
            if (this.done) {
                throw exception;
            }
            var context = this;
            function handle(loc, caught) {
                record.type = "throw";
                record.arg = exception;
                context.next = loc;
                if (caught) {
                    context.method = "next";
                    context.arg = undefined;
                }
                return !!caught;
            }
            for(var i = this.tryEntries.length - 1; i >= 0; --i){
                var entry = this.tryEntries[i];
                var record = entry.completion;
                if (entry.tryLoc === "root") {
                    return handle("end");
                }
                if (entry.tryLoc <= this.prev) {
                    var hasCatch = hasOwn.call(entry, "catchLoc");
                    var hasFinally = hasOwn.call(entry, "finallyLoc");
                    if (hasCatch && hasFinally) {
                        if (this.prev < entry.catchLoc) {
                            return handle(entry.catchLoc, true);
                        } else if (this.prev < entry.finallyLoc) {
                            return handle(entry.finallyLoc);
                        }
                    } else if (hasCatch) {
                        if (this.prev < entry.catchLoc) {
                            return handle(entry.catchLoc, true);
                        }
                    } else if (hasFinally) {
                        if (this.prev < entry.finallyLoc) {
                            return handle(entry.finallyLoc);
                        }
                    } else {
                        throw new Error("try statement without catch or finally");
                    }
                }
            }
        },
        abrupt: function(type, arg) {
            for(var i = this.tryEntries.length - 1; i >= 0; --i){
                var entry = this.tryEntries[i];
                if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
                    var finallyEntry = entry;
                    break;
                }
            }
            if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
                finallyEntry = null;
            }
            var record = finallyEntry ? finallyEntry.completion : {
            };
            record.type = type;
            record.arg = arg;
            if (finallyEntry) {
                this.method = "next";
                this.next = finallyEntry.finallyLoc;
                return ContinueSentinel;
            }
            return this.complete(record);
        },
        complete: function(record, afterLoc) {
            if (record.type === "throw") {
                throw record.arg;
            }
            if (record.type === "break" || record.type === "continue") {
                this.next = record.arg;
            } else if (record.type === "return") {
                this.rval = this.arg = record.arg;
                this.method = "return";
                this.next = "end";
            } else if (record.type === "normal" && afterLoc) {
                this.next = afterLoc;
            }
            return ContinueSentinel;
        },
        finish: function(finallyLoc) {
            for(var i = this.tryEntries.length - 1; i >= 0; --i){
                var entry = this.tryEntries[i];
                if (entry.finallyLoc === finallyLoc) {
                    this.complete(entry.completion, entry.afterLoc);
                    resetTryEntry(entry);
                    return ContinueSentinel;
                }
            }
        },
        "catch": function(tryLoc) {
            for(var i = this.tryEntries.length - 1; i >= 0; --i){
                var entry = this.tryEntries[i];
                if (entry.tryLoc === tryLoc) {
                    var record = entry.completion;
                    if (record.type === "throw") {
                        var thrown = record.arg;
                        resetTryEntry(entry);
                    }
                    return thrown;
                }
            }
            throw new Error("illegal catch attempt");
        },
        delegateYield: function(iterable, resultName, nextLoc) {
            this.delegate = {
                iterator: values(iterable),
                resultName: resultName,
                nextLoc: nextLoc
            };
            if (this.method === "next") {
                this.arg = undefined;
            }
            return ContinueSentinel;
        }
    };
    return exports;
}(typeof module === "object" ? module.exports : {
});
try {
    regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
    Function("r", "regeneratorRuntime = r")(runtime);
}
function uid() {
    const length = new Int8Array(1);
    window.crypto.getRandomValues(length);
    const array = new Uint8Array(Math.max(16, Math.abs(length[0])));
    window.crypto.getRandomValues(array);
    return array.join('');
}
function transformCallback(callback, once = false) {
    const identifier = uid();
    Object.defineProperty(window, identifier, {
        value: (result)=>{
            if (once) {
                Reflect.deleteProperty(window, identifier);
            }
            return callback?.(result);
        },
        writable: false,
        configurable: true
    });
    return identifier;
}
async function invoke(cmd, args = {
}) {
    return new Promise((resolve, reject)=>{
        const callback = transformCallback((e)=>{
            resolve(e);
            Reflect.deleteProperty(window, error);
        }, true);
        const error = transformCallback((e)=>{
            reject(e);
            Reflect.deleteProperty(window, callback);
        }, true);
        window.rpc.notify(cmd, {
            callback,
            error,
            ...args
        });
    });
}
const mod = function() {
    return {
        transformCallback: transformCallback,
        invoke: invoke
    };
}();
async function invokeTauriCommand(command) {
    return invoke('tauri', command);
}
async function getVersion() {
    return invokeTauriCommand({
        __tauriModule: 'App',
        mainThread: true,
        message: {
            cmd: 'getAppVersion'
        }
    });
}
async function getName() {
    return invokeTauriCommand({
        __tauriModule: 'App',
        mainThread: true,
        message: {
            cmd: 'getAppName'
        }
    });
}
async function getTauriVersion() {
    return invokeTauriCommand({
        __tauriModule: 'App',
        mainThread: true,
        message: {
            cmd: 'getTauriVersion'
        }
    });
}
async function exit(exitCode = 0) {
    return invokeTauriCommand({
        __tauriModule: 'App',
        mainThread: true,
        message: {
            cmd: 'exit',
            exitCode
        }
    });
}
async function relaunch() {
    return invokeTauriCommand({
        __tauriModule: 'App',
        mainThread: true,
        message: {
            cmd: 'relaunch'
        }
    });
}
const mod1 = function() {
    return {
        getName: getName,
        getVersion: getVersion,
        getTauriVersion: getTauriVersion,
        relaunch: relaunch,
        exit: exit
    };
}();
async function getMatches() {
    return invokeTauriCommand({
        __tauriModule: 'Cli',
        message: {
            cmd: 'cliMatches'
        }
    });
}
const mod2 = function() {
    return {
        getMatches: getMatches
    };
}();
async function open(options = {
}) {
    if (typeof options === 'object') {
        Object.freeze(options);
    }
    return invokeTauriCommand({
        __tauriModule: 'Dialog',
        mainThread: true,
        message: {
            cmd: 'openDialog',
            options
        }
    });
}
async function save(options = {
}) {
    if (typeof options === 'object') {
        Object.freeze(options);
    }
    return invokeTauriCommand({
        __tauriModule: 'Dialog',
        mainThread: true,
        message: {
            cmd: 'saveDialog',
            options
        }
    });
}
const mod3 = function() {
    return {
        open: open,
        save: save
    };
}();
async function emit(event, windowLabel, payload) {
    await invokeTauriCommand({
        __tauriModule: 'Event',
        message: {
            cmd: 'emit',
            event,
            windowLabel,
            payload
        }
    });
}
async function _unlisten(eventId) {
    return invokeTauriCommand({
        __tauriModule: 'Event',
        message: {
            cmd: 'unlisten',
            eventId
        }
    });
}
async function listen(event, handler) {
    return invokeTauriCommand({
        __tauriModule: 'Event',
        message: {
            cmd: 'listen',
            event,
            handler: transformCallback(handler)
        }
    }).then((eventId)=>{
        return async ()=>_unlisten(eventId)
        ;
    });
}
async function once(event, handler) {
    return listen(event, (eventData)=>{
        handler(eventData);
        _unlisten(eventData.id).catch(()=>{
        });
    });
}
async function emit1(event, payload) {
    return emit(event, undefined, payload);
}
const mod4 = function() {
    return {
        listen: listen,
        once: once,
        emit: emit1
    };
}();
async function installUpdate() {
    let unlistenerFn;
    function cleanListener() {
        if (unlistenerFn) {
            unlistenerFn();
        }
        unlistenerFn = undefined;
    }
    return new Promise((resolve, reject)=>{
        function onStatusChange(statusResult) {
            if (statusResult.error) {
                cleanListener();
                return reject(statusResult.error);
            }
            if (statusResult.status === 'DONE') {
                cleanListener();
                return resolve();
            }
        }
        listen('tauri://update-status', (data)=>{
            onStatusChange(data?.payload);
        }).then((fn)=>{
            unlistenerFn = fn;
        }).catch((e)=>{
            cleanListener();
            throw e;
        });
        emit1('tauri://update-install').catch((e)=>{
            cleanListener();
            throw e;
        });
    });
}
async function checkUpdate() {
    let unlistenerFn;
    function cleanListener() {
        if (unlistenerFn) {
            unlistenerFn();
        }
        unlistenerFn = undefined;
    }
    return new Promise((resolve, reject)=>{
        function onUpdateAvailable(manifest) {
            cleanListener();
            return resolve({
                manifest,
                shouldUpdate: true
            });
        }
        function onStatusChange(statusResult) {
            if (statusResult.error) {
                cleanListener();
                return reject(statusResult.error);
            }
            if (statusResult.status === 'UPTODATE') {
                cleanListener();
                return resolve({
                    shouldUpdate: false
                });
            }
        }
        once('tauri://update-available', (data)=>{
            onUpdateAvailable(data?.payload);
        }).catch((e)=>{
            cleanListener();
            throw e;
        });
        listen('tauri://update-status', (data)=>{
            onStatusChange(data?.payload);
        }).then((fn)=>{
            unlistenerFn = fn;
        }).catch((e)=>{
            cleanListener();
            throw e;
        });
        emit1('tauri://update').catch((e)=>{
            cleanListener();
            throw e;
        });
    });
}
const mod5 = function() {
    return {
        installUpdate: installUpdate,
        checkUpdate: checkUpdate
    };
}();
var BaseDirectory;
(function(BaseDirectory1) {
    BaseDirectory1[BaseDirectory1["Audio"] = 1] = "Audio";
    BaseDirectory1[BaseDirectory1["Cache"] = 2] = "Cache";
    BaseDirectory1[BaseDirectory1["Config"] = 3] = "Config";
    BaseDirectory1[BaseDirectory1["Data"] = 4] = "Data";
    BaseDirectory1[BaseDirectory1["LocalData"] = 5] = "LocalData";
    BaseDirectory1[BaseDirectory1["Desktop"] = 6] = "Desktop";
    BaseDirectory1[BaseDirectory1["Document"] = 7] = "Document";
    BaseDirectory1[BaseDirectory1["Download"] = 8] = "Download";
    BaseDirectory1[BaseDirectory1["Executable"] = 9] = "Executable";
    BaseDirectory1[BaseDirectory1["Font"] = 10] = "Font";
    BaseDirectory1[BaseDirectory1["Home"] = 11] = "Home";
    BaseDirectory1[BaseDirectory1["Picture"] = 12] = "Picture";
    BaseDirectory1[BaseDirectory1["Public"] = 13] = "Public";
    BaseDirectory1[BaseDirectory1["Runtime"] = 14] = "Runtime";
    BaseDirectory1[BaseDirectory1["Template"] = 15] = "Template";
    BaseDirectory1[BaseDirectory1["Video"] = 16] = "Video";
    BaseDirectory1[BaseDirectory1["Resource"] = 17] = "Resource";
    BaseDirectory1[BaseDirectory1["App"] = 18] = "App";
    BaseDirectory1[BaseDirectory1["Current"] = 19] = "Current";
})(BaseDirectory || (BaseDirectory = {
}));
async function readTextFile(filePath, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'readTextFile',
            path: filePath,
            options
        }
    });
}
async function readBinaryFile(filePath, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'readBinaryFile',
            path: filePath,
            options
        }
    });
}
async function writeFile(file, options = {
}) {
    if (typeof options === 'object') {
        Object.freeze(options);
    }
    if (typeof file === 'object') {
        Object.freeze(file);
    }
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'writeFile',
            path: file.path,
            contents: file.contents,
            options
        }
    });
}
function uint8ArrayToString(arr) {
    if (arr.length < 65536) {
        return String.fromCharCode.apply(null, Array.from(arr));
    }
    let result = '';
    const arrLen = arr.length;
    for(let i = 0; i < arrLen; i++){
        const chunk = arr.subarray(i * 65536, (i + 1) * 65536);
        result += String.fromCharCode.apply(null, Array.from(chunk));
    }
    return result;
}
function arrayBufferToBase64(buffer) {
    const str = uint8ArrayToString(new Uint8Array(buffer));
    return btoa(str);
}
async function writeBinaryFile(file, options = {
}) {
    if (typeof options === 'object') {
        Object.freeze(options);
    }
    if (typeof file === 'object') {
        Object.freeze(file);
    }
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'writeBinaryFile',
            path: file.path,
            contents: arrayBufferToBase64(file.contents),
            options
        }
    });
}
async function readDir(dir, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'readDir',
            path: dir,
            options
        }
    });
}
async function createDir(dir, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'createDir',
            path: dir,
            options
        }
    });
}
async function removeDir(dir, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'removeDir',
            path: dir,
            options
        }
    });
}
async function copyFile(source, destination, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'copyFile',
            source,
            destination,
            options
        }
    });
}
async function removeFile(file, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'removeFile',
            path: file,
            options: options
        }
    });
}
async function renameFile(oldPath, newPath, options = {
}) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'renameFile',
            oldPath,
            newPath,
            options
        }
    });
}
const mod6 = function() {
    return {
        BaseDirectory: BaseDirectory,
        Dir: BaseDirectory,
        readTextFile: readTextFile,
        readBinaryFile: readBinaryFile,
        writeFile: writeFile,
        writeBinaryFile: writeBinaryFile,
        readDir: readDir,
        createDir: createDir,
        removeDir: removeDir,
        copyFile: copyFile,
        removeFile: removeFile,
        renameFile: renameFile
    };
}();
async function appDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.App
        }
    });
}
async function audioDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Audio
        }
    });
}
async function cacheDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Cache
        }
    });
}
async function configDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Config
        }
    });
}
async function dataDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Data
        }
    });
}
async function desktopDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Desktop
        }
    });
}
async function documentDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Document
        }
    });
}
async function downloadDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Download
        }
    });
}
async function executableDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Executable
        }
    });
}
async function fontDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Font
        }
    });
}
async function homeDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Home
        }
    });
}
async function localDataDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.LocalData
        }
    });
}
async function pictureDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Picture
        }
    });
}
async function publicDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Public
        }
    });
}
async function resourceDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Resource
        }
    });
}
async function runtimeDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Runtime
        }
    });
}
async function templateDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Template
        }
    });
}
async function videoDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Video
        }
    });
}
async function currentDir() {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path: '',
            directory: BaseDirectory.Current
        }
    });
}
async function resolve(path, directory) {
    return invokeTauriCommand({
        __tauriModule: 'Fs',
        message: {
            cmd: 'resolvePath',
            path,
            directory
        }
    });
}
const mod7 = function() {
    return {
        appDir: appDir,
        audioDir: audioDir,
        cacheDir: cacheDir,
        configDir: configDir,
        dataDir: dataDir,
        desktopDir: desktopDir,
        documentDir: documentDir,
        downloadDir: downloadDir,
        executableDir: executableDir,
        fontDir: fontDir,
        homeDir: homeDir,
        localDataDir: localDataDir,
        pictureDir: pictureDir,
        publicDir: publicDir,
        resourceDir: resourceDir,
        runtimeDir: runtimeDir,
        templateDir: templateDir,
        videoDir: videoDir,
        currentDir: currentDir,
        resolvePath: resolve
    };
}();
var ResponseType;
(function(ResponseType1) {
    ResponseType1[ResponseType1["JSON"] = 1] = "JSON";
    ResponseType1[ResponseType1["Text"] = 2] = "Text";
    ResponseType1[ResponseType1["Binary"] = 3] = "Binary";
})(ResponseType || (ResponseType = {
}));
class Body {
    type;
    payload;
    constructor(type, payload1){
        this.type = type;
        this.payload = payload1;
    }
    static form(data) {
        return new Body('Form', data);
    }
    static json(data) {
        return new Body('Json', data);
    }
    static text(value) {
        return new Body('Text', value);
    }
    static bytes(bytes) {
        return new Body('Bytes', bytes);
    }
}
class Client {
    id;
    constructor(id){
        this.id = id;
    }
    async drop() {
        return invokeTauriCommand({
            __tauriModule: 'Http',
            message: {
                cmd: 'dropClient',
                client: this.id
            }
        });
    }
    async request(options) {
        return invokeTauriCommand({
            __tauriModule: 'Http',
            message: {
                cmd: 'httpRequest',
                client: this.id,
                options
            }
        });
    }
    async get(url, options) {
        return this.request({
            method: 'GET',
            url,
            ...options
        });
    }
    async post(url, body, options) {
        return this.request({
            method: 'POST',
            url,
            body,
            ...options
        });
    }
    async put(url, body, options) {
        return this.request({
            method: 'PUT',
            url,
            body,
            ...options
        });
    }
    async patch(url, options) {
        return this.request({
            method: 'PATCH',
            url,
            ...options
        });
    }
    async delete(url, options) {
        return this.request({
            method: 'DELETE',
            url,
            ...options
        });
    }
}
async function getClient(options) {
    return invokeTauriCommand({
        __tauriModule: 'Http',
        message: {
            cmd: 'createClient',
            options
        }
    }).then((id1)=>new Client(id1)
    );
}
let defaultClient = null;
async function fetch(url, options) {
    if (defaultClient === null) {
        defaultClient = await getClient();
    }
    return defaultClient.request({
        url,
        method: options?.method ?? 'GET',
        ...options
    });
}
const mod8 = function() {
    return {
        ResponseType: ResponseType,
        Body: Body,
        Client: Client,
        getClient: getClient,
        fetch: fetch
    };
}();
async function execute(program, sidecar, onEvent, args) {
    if (typeof args === 'object') {
        Object.freeze(args);
    }
    return invokeTauriCommand({
        __tauriModule: 'Shell',
        message: {
            cmd: 'execute',
            program,
            sidecar,
            onEventFn: transformCallback(onEvent),
            args: typeof args === 'string' ? [
                args
            ] : args
        }
    });
}
class EventEmitter {
    eventListeners = Object.create(null);
    addEventListener(event, handler) {
        if (event in this.eventListeners) {
            this.eventListeners[event].push(handler);
        } else {
            this.eventListeners[event] = [
                handler
            ];
        }
    }
    _emit(event, payload) {
        if (event in this.eventListeners) {
            const listeners = this.eventListeners[event];
            for (const listener of listeners){
                listener(payload);
            }
        }
    }
    on(event, handler) {
        this.addEventListener(event, handler);
        return this;
    }
}
class Child {
    pid;
    constructor(pid1){
        this.pid = pid1;
    }
    async write(data) {
        return invokeTauriCommand({
            __tauriModule: 'Shell',
            message: {
                cmd: 'stdinWrite',
                pid: this.pid,
                buffer: data
            }
        });
    }
    async kill() {
        return invokeTauriCommand({
            __tauriModule: 'Shell',
            message: {
                cmd: 'killChild',
                pid: this.pid
            }
        });
    }
}
class Command extends EventEmitter {
    program;
    args;
    sidecar = false;
    stdout = new EventEmitter();
    stderr = new EventEmitter();
    pid = null;
    constructor(program1, args1 = []){
        super();
        this.program = program1;
        this.args = typeof args1 === 'string' ? [
            args1
        ] : args1;
    }
    static sidecar(program, args = []) {
        const instance = new Command(program, args);
        instance.sidecar = true;
        return instance;
    }
    async spawn() {
        return execute(this.program, this.sidecar, (event)=>{
            switch(event.event){
                case 'Error':
                    this._emit('error', event.payload);
                    break;
                case 'Terminated':
                    this._emit('close', event.payload);
                    break;
                case 'Stdout':
                    this.stdout._emit('data', event.payload);
                    break;
                case 'Stderr':
                    this.stderr._emit('data', event.payload);
                    break;
            }
        }, this.args).then((pid2)=>new Child(pid2)
        );
    }
    async execute() {
        return new Promise((resolve1, reject)=>{
            this.on('error', reject);
            const stdout = [];
            const stderr = [];
            this.stdout.on('data', (line)=>{
                stdout.push(line);
            });
            this.stderr.on('data', (line)=>{
                stderr.push(line);
            });
            this.on('close', (payload2)=>{
                resolve1({
                    code: payload2.code,
                    signal: payload2.signal,
                    stdout: stdout.join('\n'),
                    stderr: stderr.join('\n')
                });
            });
            this.spawn().catch(reject);
        });
    }
}
async function open1(path, openWith) {
    return invokeTauriCommand({
        __tauriModule: 'Shell',
        message: {
            cmd: 'open',
            path,
            with: openWith
        }
    });
}
const mod9 = function() {
    return {
        Command: Command,
        Child: Child,
        open: open1
    };
}();
function getCurrent() {
    return new WebviewWindowHandle(window.__TAURI__.__currentWindow.label);
}
function getAll() {
    return window.__TAURI__.__windows;
}
const localTauriEvents = [
    'tauri://created',
    'tauri://error'
];
class WebviewWindowHandle {
    label;
    listeners;
    constructor(label2){
        this.label = label2;
        this.listeners = Object.create(null);
    }
    async listen(event, handler) {
        if (this._handleTauriEvent(event, handler)) {
            return Promise.resolve(()=>{
                const listeners = this.listeners[event];
                listeners.splice(listeners.indexOf(handler), 1);
            });
        }
        return listen(event, handler);
    }
    async once(event, handler) {
        if (this._handleTauriEvent(event, handler)) {
            return Promise.resolve(()=>{
                const listeners = this.listeners[event];
                listeners.splice(listeners.indexOf(handler), 1);
            });
        }
        return once(event, handler);
    }
    async emit(event, payload) {
        if (localTauriEvents.includes(event)) {
            for (const handler of this.listeners[event] || []){
                handler({
                    event,
                    id: -1,
                    payload
                });
            }
            return Promise.resolve();
        }
        return emit(event, this.label, payload);
    }
    _handleTauriEvent(event, handler) {
        if (localTauriEvents.includes(event)) {
            if (!(event in this.listeners)) {
                this.listeners[event] = [
                    handler
                ];
            } else {
                this.listeners[event].push(handler);
            }
            return true;
        }
        return false;
    }
}
class WebviewWindow extends WebviewWindowHandle {
    constructor(label1, options = {
    }){
        super(label1);
        invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'createWebview',
                options: {
                    label: label1,
                    ...options
                }
            }
        }).then(async ()=>this.emit('tauri://created')
        ).catch(async (e)=>this.emit('tauri://error', e)
        );
    }
    static getByLabel(label) {
        if (getAll().some((w)=>w.label === label
        )) {
            return new WebviewWindowHandle(label);
        }
        return null;
    }
}
class WindowManager {
    async setResizable(resizable) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setResizable',
                resizable
            }
        });
    }
    async setTitle(title) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setTitle',
                title
            }
        });
    }
    async maximize() {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'maximize'
            }
        });
    }
    async unmaximize() {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'unmaximize'
            }
        });
    }
    async minimize() {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'minimize'
            }
        });
    }
    async unminimize() {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'unminimize'
            }
        });
    }
    async show() {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'show'
            }
        });
    }
    async hide() {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'hide'
            }
        });
    }
    async close() {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'close'
            }
        });
    }
    async setDecorations(decorations) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setDecorations',
                decorations
            }
        });
    }
    async setAlwaysOnTop(alwaysOnTop) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setAlwaysOnTop',
                alwaysOnTop
            }
        });
    }
    async setWidth(width) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setWidth',
                width
            }
        });
    }
    async setHeight(height) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setHeight',
                height
            }
        });
    }
    async resize(width, height) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'resize',
                width,
                height
            }
        });
    }
    async setMinSize(minWidth, minHeight) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setMinSize',
                minWidth,
                minHeight
            }
        });
    }
    async setMaxSize(maxWidth, maxHeight) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setMaxSize',
                maxWidth,
                maxHeight
            }
        });
    }
    async setX(x) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setX',
                x
            }
        });
    }
    async setY(y) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setY',
                y
            }
        });
    }
    async setPosition(x, y) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setPosition',
                x,
                y
            }
        });
    }
    async setFullscreen(fullscreen) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setFullscreen',
                fullscreen
            }
        });
    }
    async setIcon(icon) {
        return invokeTauriCommand({
            __tauriModule: 'Window',
            message: {
                cmd: 'setIcon',
                icon
            }
        });
    }
}
const appWindow = new WindowManager();
const mod10 = function() {
    return {
        WindowManager: WindowManager,
        WebviewWindow: WebviewWindow,
        getCurrent: getCurrent,
        getAll: getAll,
        appWindow: appWindow
    };
}();
async function isPermissionGranted() {
    if (window.Notification.permission !== 'default') {
        return Promise.resolve(window.Notification.permission === 'granted');
    }
    return invokeTauriCommand({
        __tauriModule: 'Notification',
        message: {
            cmd: 'isNotificationPermissionGranted'
        }
    });
}
async function requestPermission() {
    return window.Notification.requestPermission();
}
function sendNotification(options1) {
    if (typeof options1 === 'string') {
        new window.Notification(options1);
    } else {
        new window.Notification(options1.title, options1);
    }
}
const mod11 = function() {
    return {
        sendNotification: sendNotification,
        requestPermission: requestPermission,
        isPermissionGranted: isPermissionGranted
    };
}();
async function register(shortcut, handler) {
    return invokeTauriCommand({
        __tauriModule: 'GlobalShortcut',
        message: {
            cmd: 'register',
            shortcut,
            handler: transformCallback(handler)
        }
    });
}
async function registerAll(shortcuts, handler) {
    return invokeTauriCommand({
        __tauriModule: 'GlobalShortcut',
        message: {
            cmd: 'registerAll',
            shortcuts,
            handler: transformCallback(handler)
        }
    });
}
async function isRegistered(shortcut) {
    return invokeTauriCommand({
        __tauriModule: 'GlobalShortcut',
        message: {
            cmd: 'isRegistered',
            shortcut
        }
    });
}
async function unregister(shortcut) {
    return invokeTauriCommand({
        __tauriModule: 'GlobalShortcut',
        message: {
            cmd: 'unregister',
            shortcut
        }
    });
}
async function unregisterAll() {
    return invokeTauriCommand({
        __tauriModule: 'GlobalShortcut',
        message: {
            cmd: 'unregisterAll'
        }
    });
}
const mod12 = function() {
    return {
        register: register,
        registerAll: registerAll,
        isRegistered: isRegistered,
        unregister: unregister,
        unregisterAll: unregisterAll
    };
}();
export { mod1 as app, mod2 as cli, mod3 as dialog, mod4 as event, mod5 as updater, mod6 as fs, mod7 as path, mod8 as http, mod9 as shell, mod as tauri, mod10 as window, mod11 as notification, mod12 as globalShortcut };

Why?

  • At first, using Rollup or Webpack or others (Grunt, Gulp, Vite, etc.), all these bundlers have a bloated configuration system which often needs to go back and forth with the documentation almost everytime you have to touch the bundle system.
  • Deno brings up a simpler standard: the typescript compiler.
  • Deno's native dependency system can be a simple import_map.json in order to determine where the dependencies come from. It's similar to a package.json, but manually maintained. The latter is used in this PR.

Cons

  • To keep interoperability, Tauri will need to maintain the import_map.json for each tool that has to be bundled.
  • Native deno bundle command doesn't allow multiple targets. For this, we need to create a specific script that makes use of the internal compiler API. It's not that much of a disadvantage per se, and it is only a problem if Tauri must publish more than one JS file for each tool. Note: today Tauri exports a CJS file index.js and an ESM one .mjs for each tool.

Pros

  • Still a JS bundle, so it should work the same for the end user
  • Way less dev dependencies (only use Deno itself, instead of relying on Rollup and all its dependencies)
  • esbuild can still be used to minify the final package, it has to be scripted in the building process. After all, esbuild is a Go package, and it has a Deno implementation: https://deno.land/x/[email protected]

@nothingismagick
Copy link
Member

Not gunna lie - I am allergic to CDNs even if unpkg should be reliable.

@nothingismagick
Copy link
Member

We also need to verify that this will run for vanillajs users (i.e. without any transpilation).

@Pierstoval
Copy link
Contributor Author

We also need to verify that this will run for vanillajs users (i.e. without any transpilation).

Definitely! It's the goal of all of this 😉

@lucasfernog
Copy link
Member

I think the problem was fixed. Thanks for your help anyway, we loved it! We'd never think of using Deno for that, good to know that the community is into it :P

@Pierstoval
Copy link
Contributor Author

I'll keep trying on my side anyway 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants