Upload via GUI (7543 Dateien)

This commit is contained in:
2026-10-22 06:58:16 +00:00
parent 68133f4d0f
commit 860c714301
50 changed files with 3039 additions and 0 deletions
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+27
View File
@@ -0,0 +1,27 @@
# `@malept/cross-spawn-promise`
> A promisified version of [`cross-spawn`](https://npm.im/cross-spawn) with slightly different behavior & extra options.
[![CI](https://github.com/malept/cross-spawn-promise/workflows/CI/badge.svg)](https://github.com/malept/cross-spawn-promise/actions?query=workflow%3ACI)
[![NPM package](https://img.shields.io/npm/v/@malept/cross-spawn-promise.svg)](https://www.npmjs.com/package/@malept/cross-spawn-promise)
[![codecov](https://codecov.io/gh/malept/cross-spawn-promise/branch/main/graph/badge.svg)](https://codecov.io/gh/malept/cross-spawn-promise)
## Different Behavior
If the spawned process exits with a non-zero code, an `ExitCodeError` is thrown with the original
command, code, `stdout`, and `stderr` as properties.
If the spawned process is terminated by a signal on non-Windows platforms, an `ExitSignalError` is
thrown with the original command, signal name, `stdout`, and `stderr` as properties.
## Extra Options
- `logger`: a `Function` such as `console.log` or `debug(name)` to log some information
about the spawned process.
- `updateErrorCallback`: a callback which mutates the error before it is re-thrown. Most commonly,
this is used to augment the error message of `ENOENT` error to provide a more human-friendly
message as to how to install the missing executable.
## Legal
This module is licensed under the Apache 2.0 license.
+61
View File
@@ -0,0 +1,61 @@
/// <reference types="node" />
import { SpawnOptions } from "child_process";
export declare type LoggerFunction = (message: string) => void;
/**
* List of string arguments.
*/
export declare type CrossSpawnArgs = ReadonlyArray<string> | undefined;
export declare type CrossSpawnOptions = SpawnOptions & {
/**
* A `Function` such as `console.log` or `debug(name)` to log some information about the
* spawned process.
*/
logger?: LoggerFunction;
/**
* A callback which mutates the error before it is rethrown. Most commonly, this is used to
* augment the error message of `ENOENT` errors to provide a more human-friendly message as to
* how to install the missing executable.
*
* @param error - The error thrown from the `spawn` function
* @param hasLogger - Whether `logger` was set
*/
updateErrorCallback?: (error: Error, hasLogger: boolean) => void;
};
/**
* Wrapper error for when the spawn function itself emits an error.
*/
export declare class CrossSpawnError extends Error {
originalError: Error;
constructor(cmd: string, args: CrossSpawnArgs, originalError: Error, stderr: string);
}
/**
* Base error class for when a process does not exit with a status code of zero.
*/
export declare abstract class ExitError extends Error {
cmd: string;
args: CrossSpawnArgs;
stdout: string;
stderr: string;
constructor(cmd: string, args: CrossSpawnArgs, message: string, stdout: string, stderr: string);
}
/**
* The error thrown when a process emits a non-zero exit code.
*/
export declare class ExitCodeError extends ExitError {
code: number;
constructor(cmd: string, args: CrossSpawnArgs, code: number, stdout: string, stderr: string);
}
/**
* The error thrown when a process exits via a signal.
*/
export declare class ExitSignalError extends ExitError {
signal: string;
constructor(cmd: string, args: CrossSpawnArgs, signal: string, stdout: string, stderr: string);
}
/**
* A wrapper around `cross-spawn`'s `spawn` function which can optionally log the command executed
* and/or change the error object via a callback.
*
* @param cmd - The command to run
*/
export declare function spawn(cmd: string, args?: CrossSpawnArgs, options?: CrossSpawnOptions): Promise<string>;
+113
View File
@@ -0,0 +1,113 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.spawn = exports.ExitSignalError = exports.ExitCodeError = exports.ExitError = exports.CrossSpawnError = void 0;
const cross_spawn_1 = __importDefault(require("cross-spawn"));
function stringifyCommand(cmd, args) {
if (args && Array.isArray(args) && args.length > 0) {
return `${cmd} ${args.join(" ")}`;
}
else {
return cmd;
}
}
/**
* Wrapper error for when the spawn function itself emits an error.
*/
class CrossSpawnError extends Error {
constructor(cmd, args, originalError, stderr) {
const fullCommand = stringifyCommand(cmd, args);
const errorMessage = originalError.message || originalError;
super(`Error executing command (${fullCommand}):\n${errorMessage}\n${stderr}`.trim());
this.originalError = originalError;
}
}
exports.CrossSpawnError = CrossSpawnError;
/**
* Base error class for when a process does not exit with a status code of zero.
*/
class ExitError extends Error {
constructor(cmd, args, message, stdout, stderr) {
super(message);
this.cmd = cmd;
this.args = args;
this.stdout = stdout;
this.stderr = stderr;
}
}
exports.ExitError = ExitError;
/**
* The error thrown when a process emits a non-zero exit code.
*/
class ExitCodeError extends ExitError {
constructor(cmd, args, code, stdout, stderr) {
const fullCommand = stringifyCommand(cmd, args);
super(cmd, args, `Command failed with a non-zero return code (${code}):\n${fullCommand}\n${stdout}\n${stderr}`.trim(), stdout, stderr);
this.code = code;
}
}
exports.ExitCodeError = ExitCodeError;
/**
* The error thrown when a process exits via a signal.
*/
class ExitSignalError extends ExitError {
constructor(cmd, args, signal, stdout, stderr) {
const fullCommand = stringifyCommand(cmd, args);
super(cmd, args, `Command terminated via a signal (${signal}):\n${fullCommand}\n${stdout}\n${stderr}`.trim(), stdout, stderr);
this.signal = signal;
}
}
exports.ExitSignalError = ExitSignalError;
/**
* A wrapper around `cross-spawn`'s `spawn` function which can optionally log the command executed
* and/or change the error object via a callback.
*
* @param cmd - The command to run
*/
async function spawn(cmd, args, options) {
if (!options) {
options = {};
}
const { logger, updateErrorCallback, ...spawnOptions } = options;
if (logger)
logger(`Executing command ${stringifyCommand(cmd, args)}`);
return new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
const process = cross_spawn_1.default(cmd, args, spawnOptions);
if (process.stdout) {
process.stdout.on("data", (data) => {
stdout += data.toString();
});
}
if (process.stderr) {
process.stderr.on("data",
/* istanbul ignore next */ (data) => {
stderr += data.toString();
});
}
process.on("close", (code, signal) => {
if (code === 0) {
resolve(stdout);
}
else if (code === null) {
// Why: assume signal is not null if code is null
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
reject(new ExitSignalError(cmd, args, signal, stdout, stderr));
}
else {
reject(new ExitCodeError(cmd, args, code, stdout, stderr));
}
});
process.on("error", (err) => {
if (updateErrorCallback) {
updateErrorCallback(err, !!logger);
}
reject(new CrossSpawnError(cmd, args, err, stderr));
});
});
}
exports.spawn = spawn;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,8DAAqC;AA4BrC,SAAS,gBAAgB,CAAC,GAAW,EAAE,IAA4B;IACjE,IAAI,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;QAClD,OAAO,GAAG,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;KACnC;SAAM;QACL,OAAO,GAAG,CAAC;KACZ;AACH,CAAC;AAED;;GAEG;AACH,MAAa,eAAgB,SAAQ,KAAK;IAGxC,YACE,GAAW,EACX,IAAoB,EACpB,aAAoB,EACpB,MAAc;QAEd,MAAM,WAAW,GAAG,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAChD,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,IAAI,aAAa,CAAC;QAC5D,KAAK,CACH,4BAA4B,WAAW,OAAO,YAAY,KAAK,MAAM,EAAE,CAAC,IAAI,EAAE,CAC/E,CAAC;QACF,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;CACF;AAhBD,0CAgBC;AAED;;GAEG;AACH,MAAsB,SAAU,SAAQ,KAAK;IAM3C,YACE,GAAW,EACX,IAAoB,EACpB,OAAe,EACf,MAAc,EACd,MAAc;QAEd,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,GAAG,C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BAAmB,EAAE;gBACvB,mBAAmB,CAAC,GAAG,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC;aACpC;YACD,MAAM,CAAC,IAAI,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;QACtD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AA9CD,sBA8CC"}
+107
View File
@@ -0,0 +1,107 @@
{
"name": "@malept/cross-spawn-promise",
"version": "2.0.0",
"description": "Promisified version of cross-spawn",
"main": "dist/src/index.js",
"repository": "https://github.com/malept/cross-spawn-promise",
"author": "Mark Lee",
"license": "Apache-2.0",
"engines": {
"node": ">= 12.13.0"
},
"scripts": {
"ava": "ava",
"build": "tsc",
"coverage": "nyc --reporter=lcov --reporter=text ava",
"docs": "typedoc src/index.ts",
"lint": "prettier --check . && eslint --ext .ts .",
"prepare": "husky install && yarn build",
"test": "yarn lint && yarn ava"
},
"files": [
"dist"
],
"dependencies": {
"cross-spawn": "^7.0.1"
},
"devDependencies": {
"@istanbuljs/nyc-config-typescript": "^1.0.1",
"@types/cross-spawn": "^6.0.1",
"@types/node": "^15.14.0",
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"ava": "^3.3.0",
"eslint": "^7.0.0",
"eslint-config-prettier": "^8.0.0",
"eslint-plugin-ava": "^12.0.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-prettier": "^3.1.2",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-tsdoc": "^0.2.5",
"husky": "^7.0.0",
"lint-staged": "^11.0.0",
"nyc": "^15.0.0",
"prettier": "^2.0.1",
"source-map-support": "^0.5.16",
"ts-node": "^10.0.0",
"typedoc": "^0.21.2",
"typescript": "~4.3.5"
},
"ava": {
"extensions": [
"ts"
],
"require": [
"ts-node/register"
]
},
"eslintConfig": {
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "2019",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint",
"eslint-plugin-tsdoc"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:ava/recommended",
"plugin:import/errors",
"plugin:import/warnings",
"plugin:import/typescript",
"plugin:prettier/recommended",
"plugin:promise/recommended",
"prettier"
],
"rules": {
"strict": "error",
"tsdoc/syntax": "warn"
}
},
"eslintIgnore": [
"dist"
],
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/malept"
},
{
"type": "tidelift",
"url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
}
],
"lint-staged": {
"*.{json,md,yml}": "prettier --write",
"*.ts": [
"prettier --write",
"eslint --fix"
]
},
"nyc": {
"extends": "@istanbuljs/nyc-config-typescript"
}
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2016 Endless Mobile, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+210
View File
@@ -0,0 +1,210 @@
# @malept/flatpak-bundler [![Version](https://img.shields.io/npm/v/@malept/flatpak-bundler.svg)](https://www.npmjs.com/package/@malept/flatpak-bundler) [![Build Status](https://github.com/malept/flatpak-bundler/workflows/CI/badge.svg)](https://github.com/malept/flatpak-bundler/actions?query=workflow%3ACI)
Build [flatpaks](https://flatpak.org/) from Node.js.
# Quick Start
Install `@malept/flatpak-bundler`.
```shell
$ npm install @malept/flatpak-bundler
```
[Build a flatpak with a Node script](#hello-world).
Install and run it!
```shell
$ flatpak install --user --bundle hello.flatpak
$ flatpak run org.world.Hello
Hello, world!
```
## Overview
This modules allows building flatpaks programmatically from Node. It requires
Node 10 or above and flatpak >= 0.6.13 to be installed on your system.
Under the hood, this is just a wrapper for the [flatpak-builder](https://docs.flatpak.org/en/latest/flatpak-builder.html)
tool with some extra sugar added.
With `flatpak-builder`, you specify a runtime, sandbox permissions and software
modules to build into your application, and build a flatpak from start to finish.
This module provides a few additional features:
- Supports auto installing flatpak runtime and app dependencies
- Supports exporting directly to the a single file flatpak bundle
- Supports easy copying files and creating symlinks directly in `/app`
The latter is particularly useful for [Electron](https://electronjs.org/) and
[nw.js](http://nwjs.io/) style Node applications, which often create packages
from prebuilt binaries and do not attempt to follow an autotools-like
[build api](https://github.com/cgwalters/build-api).
This module should make it easy to plug flatpak support into an Electron or nw.js
app packaging phase.
## Usage
### translateArch(arch)
Used to translate a Node-style arch (e.g., `x64`) into a Flatpak-compatible arch (e.g., `x86_64`).
If the arch is unknown, it will pass through the input value.
### bundle(manifest, buildOptions)
Takes an [app manifest](#manifest) and a build options object. It returns a Promise.
Both the manifest and options objects support both camelCase and dash-separated
variants of any option.
The promise is returned with a `finalBuildOptions` value. It contains the build
options after default values have been applied. Useful to read out the
`workingDir`, for example.
#### Manifest
This matches the format for [`flatpak-builder` app
manifests](https://docs.flatpak.org/en/latest/manifests.html), with a few extra
options added and camelCase variants supported.
- **id**: Required. The application id.
- **runtime**: Required. The runtime for your flatpak application.
- **sdk**: Required. The sdk for your flatpak application.
- **base**: An app to inherit from. Use the app as a "base" for `/app`
contents.
- **finishArgs**: The arguments to pass to `flatpak build-finish`. Use this to
add sandbox permissions. See the [Electron app example](#electron-app) for
some common app permissions.
- **modules**: If you need to build other software modules into you flatpak app
(anything not already in your runtime or base app), you can specify them
here.
#### Build Options
- **bundlePath**: Output location for a single file version of the flatpak. If
non supplied, the single file flatpak will not be created.
- **arch**: The architecture for the flatpak bundle. x86_64, i386 or arm.
- **workingDir**: The working directory to call `flatpak-builder` from.
Defaults to a new tmp directory.
- **buildDir**: The directory to build the application in. Defaults to
`${workingDir}/build`
- **repoDir**: The directory for a flatpak repo, can be used to publish to an
existing repo. Defaults to `${workingDir}/repo`
- **cleanTmpdirs**: Cleanup any tmp directories created during the build on
process exit. Defaults to true. Set false for easier debugging.
- **autoInstallRuntime**: Install/update the runtime while building. Defaults
to true if runtimeFlatpakref is set in the manifest.
- **autoInstallSdk**: Install/update the sdk while building. Defaults
to true if sdkFlatpakref is set in the manifest.
- **autoInstallBase**: Install/update the base app while building. Defaults
to true if baseFlatpakref is set in the manifest.
- **gpgSign**: The gpg key to use to sign the flatpak repo and bundle file.
- **gpgHomedir**: The gpg homedir to use when signing.
- **subject**: The single line subject to use for the flatpak repo commit
message.
- **body**: The description to use for the flatpak repo commit message.
- **files**: Files to copy directly into the app. Should be a list of [source,
dest] tuples. Source should be a relative/absolute path to a file/directory
to copy into the flatpak, and dest should be the path inside the app install
prefix (e.g. `/share/applications/`)
- **symlinks**: Symlinks to create in the app files. Should be a list of
[target, location] symlink tuples. Target can be either a relative or
absolute path inside the app install prefix, and location should be a
absolute path inside the prefix to create the symlink at.
- **extraExports**: Files to export outside of the flatpak sandbox, in addition
to the application desktop file, icons and appstream. File basename *must*
be prefixed with the app id. Should not be needed for common use.
- **runtimeFlatpakref**: A pathname or url to a flatpakref file to use to auto
install the runtime.
- **sdkFlatpakref**: A pathname or url to a flatpakref file to use to auto
install the sdk.
- **baseFlatpakref**: A pathname or url to a flatpakref file to use to auto
install the base app.
- **bundleRepoUrl**: Repo url for the single file bundle. Installing the bundle
will automatically configure a remote for this URL.
- **extraFlatpakBuilderArgs**: List of extra arguments to pass to the
[flatpak-builder](https://docs.flatpak.org/en/latest/flatpak-builder-command-reference.html) command.
- **extraFlatpakBuildExportArgs**: List of extra arguments to pass to the
[flatpak build-export](https://docs.flatpak.org/en/latest/flatpak-command-reference.html#flatpak-build-export) command.
- **extraFlatpakBuildBundleArgs**: List of extra arguments to pass to the
[flatpak build-bundle](https://docs.flatpak.org/en/latest/flatpak-command-reference.html#flatpak-build-bundle) command.
### Logging
To turn on debugging output, set the DEBUG environment variable:
```shell
DEBUG=flatpak-bundler npm run my-flatpak-command
```
## Examples
### Hello world
```javascript
const flatpakBundler = require('@malept/flatpak-bundler')
const fs = require('fs-extra')
// Write a hello world script to disk
await fs.writeFile('hello',
`#!/bin/bash
echo "Hello, world!"`, { mode: 0o755 })
// Make a flatpak with it!
try {
await flatpakBundler.bundle({
id: 'org.world.Hello',
runtime: 'org.freedesktop.Platform',
runtimeVersion: '1.4',
sdk: 'org.freedesktop.Sdk',
}, {
bundlePath: 'hello.flatpak',
files: [
['hello', '/bin/hello']
],
runtimeFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref'
})
console.log('Flatpak built successfully')
} catch (error) {
console.error('Error building flatpak', error)
}
```
### Electron App
```javascript
const flatpakBundler = require('@malept/flatpak-bundler')
try {
const finalBuildOptions = await flatpakBundler.bundle({ // Manifest
id: 'org.world.Hello',
base: 'io.atom.electron.BaseApp', // Electron base application
runtime: 'org.freedesktop.Platform', // Use the freedesktop runtime
runtimeVersion: '1.4',
sdk: 'org.freedesktop.Sdk',
finishArgs: [
'--share=ipc', '--socket=x11', // Allow app to show windows with X11
'--socket=pulseaudio', // Allow audio output
'--filesystem=home', // Allow access to users home directory
'--share=network', // Allow network access
'--device=dri' // Allow OpenGL rendering
],
renameDesktopFile: 'hello.desktop', // Rename the desktop file to agree with the app ID so flatpak will export it
renameIcon: 'hello' // Rename the icon to agree with the app ID so flatpak will export it
}, { // Build options
arch: 'x86_64',
baseFlatpakref: 'https://s3-us-west-2.amazonaws.com/electron-flatpak.endlessm.com/electron-base-app-master.flatpakref', // So we can auto install the runtime
bundlePath: 'dist/hello_x86_64.flatpak',
files: [
[ 'static/linux', '/share/' ], // Desktop file and icons
[ packagedFileDir, '/share/bar' ] // Application binaries and assets
],
gpgSign: '1234ABCD', // GPG key to sign with
runtimeFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref',
symlinks: [
[ '/share/bar/Bar', '/bin/Bar' ] // Create a symlink in /bin to to app executable
]
})
console.log('Flatpak built successfully.')
console.log(`Build dir and repo in ${finalBuildOptions.workingDir}`)
} catch (error) {
console.error('Error building flatpak', error)
}
```
+318
View File
@@ -0,0 +1,318 @@
'use strict'
const _ = require('lodash')
const childProcess = require('child_process')
const fs = require('fs-extra')
const path = require('path')
const { promisify } = require('util')
const tmp = require('tmp-promise')
const pkg = require('./package.json')
const logger = require('debug')(pkg.name)
const exec = promisify(childProcess.exec)
function kebabify (object) {
return _.cloneDeepWith(object, (value) => {
if (!value || typeof value !== 'object') return value
return Object.keys(value).reduce((newValue, key) => {
newValue[_.kebabCase(key)] = value[key]
return newValue
}, {})
})
}
function translateArch (arch) {
if (arch === 'ia32') return 'i386'
if (arch === 'x64') return 'x86_64'
if (arch === 'amd64') return 'x86_64'
if (arch === 'armv7l') return 'arm'
return arch
}
function getOptionsWithDefaults (options, manifest) {
const defaults = {
'build-dir': path.join(options['working-dir'], 'build'),
'repo-dir': path.join(options['working-dir'], 'repo'),
'manifest-path': path.join(options['working-dir'], 'manifest.json'),
'extra-flatpak-builder-args': [],
'extra-flatpak-build-bundle-args': [],
'extra-flatpak-build-export-args': [],
'clean-tmpdirs': true,
'auto-install-runtime': typeof options['runtime-flatpakref'] !== 'undefined',
'auto-install-sdk': typeof options['sdk-flatpakref'] !== 'undefined',
'auto-install-base': typeof options['base-flatpakref'] !== 'undefined'
}
options = _.defaults({}, options, defaults)
options['working-dir'] = path.resolve(options['working-dir'])
options['build-dir'] = path.resolve(options['build-dir'])
options['repo-dir'] = path.resolve(options['repo-dir'])
options['manifest-path'] = path.resolve(options['manifest-path'])
if (options['bundle-path']) options['bundle-path'] = path.resolve(options['bundle-path'])
return options
}
async function spawnWithLogging (options, command, args, allowFail) {
return new Promise((resolve, reject) => {
logger(`$ ${command} ${args.join(' ')}`)
const child = childProcess.spawn(command, args, { cwd: options['working-dir'] })
child.stdout.on('data', (data) => {
logger(`1> ${data}`)
})
child.stderr.on('data', (data) => {
logger(`2> ${data}`)
})
child.on('error', (error) => {
reject(error)
})
child.on('close', (code) => {
if (!allowFail && code !== 0) {
reject(new Error(`${command} failed with status code ${code}`))
}
resolve(code === 0)
})
})
}
function addCommandLineOption (args, name, value) {
if (!value) return
args.push(`--${name}`)
if (value !== true) args.push(value)
}
async function checkInstalled (id, options, version, checkUser) {
const args = ['info']
addCommandLineOption(args, 'show-commit', true)
addCommandLineOption(args, checkUser ? 'user' : 'system', true)
args.push([id, options.arch, version].join('/'))
return spawnWithLogging(options, 'flatpak', args, true)
}
let _flatpakBuilderVersion
/**
* Get the flatpak-builder version in a comparable form (Array of Numbers).
*/
async function flatpakBuilderVersion () {
if (!_flatpakBuilderVersion) {
const versionString = _.last((await exec('flatpak-builder --version')).toString().split(' '))
_flatpakBuilderVersion = versionString.split('.').map(part => parseInt(part, 10))
}
return _flatpakBuilderVersion
}
async function addAssumeYesArg (args) {
if ((await flatpakBuilderVersion()) >= [0, 9, 9]) {
logger('flatpak-builder is new enough, adding --assumeyes')
addCommandLineOption(args, 'assumeyes', true)
}
}
async function ensureRef (options, manifest, type, version) {
const flatpakref = options[`${type}-flatpakref`]
const id = manifest[type]
if (!options[`auto-install-${type}`]) {
return
}
logger(`Ensuring ${type} is up to date`)
logger(`Checking for install of ${id}`)
const [userInstall, systemInstall] = await Promise.all([
checkInstalled(id, options, version, true),
checkInstalled(id, options, version, false)
])
if (!userInstall && !systemInstall) {
logger(`No install of ${id} found, trying to install from ${flatpakref}`)
if (!flatpakref) {
throw new Error(`Cannot install ${id} without flatpakref`)
}
const args = ['install']
addCommandLineOption(args, 'user', true)
addCommandLineOption(args, 'no-deps', true)
addCommandLineOption(args, 'arch', options.arch)
await addAssumeYesArg(args)
if (flatpakref.startsWith('app/') || flatpakref.startsWith('runtime/')) {
args.push(flatpakref)
} else {
addCommandLineOption(args, 'from', flatpakref)
}
return spawnWithLogging(options, 'flatpak', args)
}
logger(`Found install of ${id}, trying to update`)
const args = ['update']
addCommandLineOption(args, 'user', userInstall)
addCommandLineOption(args, 'no-deps', true)
addCommandLineOption(args, 'arch', options.arch)
await addAssumeYesArg(args)
args.push(id)
if (version) {
args.push(version)
}
return spawnWithLogging(options, 'flatpak', args)
}
async function ensureRuntime (options, manifest) {
return ensureRef(options, manifest, 'runtime', manifest['runtime-version'])
}
async function ensureSdk (options, manifest) {
return ensureRef(options, manifest, 'sdk', manifest['runtime-version'])
}
async function ensureBase (options, manifest) {
return ensureRef(options, manifest, 'base', manifest['base-version'])
}
async function ensureWorkingDir (options) {
if (!options['working-dir']) {
const dir = await tmp.dir({ prefix: 'flatpak-bundler', unsafeCleanup: options['clean-tmpdirs'] })
options['working-dir'] = dir.path
} else {
return fs.ensureDir(options['working-dir'])
}
}
async function writeJsonFile (options, manifest) {
return fs.writeJson(options['manifest-path'], manifest, { space: ' ' })
}
async function copyFiles (options, manifest) {
if (!options.files) {
return
}
return Promise.all(options.files.map(async sourceDest => {
const source = path.resolve(sourceDest[0])
const dest = path.join(options['build-dir'], 'files', sourceDest[1])
let dir = dest
if (!dir.endsWith(path.sep)) {
dir = path.dirname(dir)
}
logger(`Copying ${source} to ${dest}`)
await fs.ensureDir(dir)
await fs.copy(source, dest)
}))
}
async function createSymlinks (options, manifest) {
if (!options.symlinks) {
return
}
return Promise.all(options.symlinks.map(async ([targetPath, location]) => {
const target = path.join('/app', targetPath)
const dest = path.join(options['build-dir'], 'files', location)
logger(`Symlinking ${target} at ${dest}`)
await fs.ensureDir(path.dirname(dest))
await fs.symlink(target, dest)
}))
}
async function copyExports (options, manifest) {
if (!options['extra-exports']) {
return
}
return Promise.all(options['extra-exports'].map(async source => {
const dest = path.join(options['build-dir'], 'export', source)
const dir = path.dirname(dest)
source = path.join(options['build-dir'], 'files', source)
logger(`Exporting ${source} to ${dest}`)
await fs.ensureDir(dir)
await fs.copy(source, dest)
}))
}
async function flatpakBuilder (options, manifest, finish) {
const args = []
addCommandLineOption(args, 'arch', options.arch)
addCommandLineOption(args, 'force-clean', true)
// If we are not compiling anything, allow building without the platform and sdk
// installed. Allows automated builds on a minimal environment, for example.
if (!manifest.modules || manifest.modules.length === 0) {
addCommandLineOption(args, 'allow-missing-runtimes', true)
}
if (!finish) {
addCommandLineOption(args, 'build-only', true)
} else {
addCommandLineOption(args, 'finish-only', true)
}
await addAssumeYesArg(args)
args.push.apply(args, options['extra-flatpak-builder-args'])
args.push(options['build-dir'])
args.push(options['manifest-path'])
return spawnWithLogging(options, 'flatpak-builder', args)
}
async function flatpakBuildExport (options, manifest) {
const args = ['build-export']
addCommandLineOption(args, 'arch', options.arch)
addCommandLineOption(args, 'gpg-sign', options['gpg-sign'])
addCommandLineOption(args, 'gpg-homedir', options['gpg-homedir'])
addCommandLineOption(args, 'subject', options.subject)
addCommandLineOption(args, 'body', options.body)
if (options['build-runtime']) addCommandLineOption(args, 'runtime', true)
args.push.apply(args, options['extra-flatpak-build-export-args'])
args.push(options['repo-dir'])
args.push(options['build-dir'])
if (manifest.branch) args.push(manifest.branch)
return spawnWithLogging(options, 'flatpak', args)
}
async function flatpakBuildBundle (options, manifest) {
if (!options['bundle-path']) {
return
}
const args = ['build-bundle']
addCommandLineOption(args, 'arch', options.arch)
addCommandLineOption(args, 'gpg-keys', options['gpg-keys'])
addCommandLineOption(args, 'gpg-homedir', options['gpg-homedir'])
addCommandLineOption(args, 'repo-url', options['bundle-repo-url'])
if (options['build-runtime']) addCommandLineOption(args, 'runtime', true)
args.push.apply(args, options['extra-flatpak-build-bundle-args'])
args.push(options['repo-dir'])
args.push(options['bundle-path'])
args.push(manifest.id)
if (manifest.branch) args.push(manifest.branch)
await fs.ensureDir(path.dirname(options['bundle-path']))
return spawnWithLogging(options, 'flatpak', args)
}
exports.bundle = async function (manifest, options) {
manifest = kebabify(manifest)
options = kebabify(options)
if (manifest['app-id']) manifest.id = manifest['app-id']
await ensureWorkingDir(options)
options = getOptionsWithDefaults(options, manifest)
options.arch = translateArch(options.arch)
logger(`Using manifest...\n${JSON.stringify(manifest, null, ' ')}`)
logger(`Using options...\n${JSON.stringify(options, null, ' ')}`)
await ensureRuntime(options, manifest)
await ensureSdk(options, manifest)
await ensureBase(options, manifest)
await writeJsonFile(options, manifest)
await flatpakBuilder(options, manifest, false)
await copyFiles(options, manifest)
await createSymlinks(options, manifest)
await flatpakBuilder(options, manifest, true)
await copyExports(options, manifest)
await flatpakBuildExport(options, manifest)
await flatpakBuildBundle(options, manifest)
return options
}
exports.translateArch = translateArch
+46
View File
@@ -0,0 +1,46 @@
{
"name": "@malept/flatpak-bundler",
"version": "0.4.0",
"description": "A small utility for packing files in a flatpak.",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/malept/flatpak-bundler.git"
},
"keywords": [
"flatpak"
],
"author": "Matt Watson <mattdangerw@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/malept/flatpak-bundler/issues"
},
"files": [],
"homepage": "https://github.com/malept/flatpak-bundler#readme",
"engines": {
"node": ">= 10.0.0"
},
"dependencies": {
"debug": "^4.1.1",
"fs-extra": "^9.0.0",
"lodash": "^4.17.15",
"tmp-promise": "^3.0.2"
},
"devDependencies": {
"husky": "^4.2.5",
"lint-staged": "^10.2.9",
"mocha": "^7.0.0",
"standard": "^14.0.0"
},
"scripts": {
"lint": "standard",
"mocha": "mocha",
"test": "standard && mocha"
},
"husky": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.js": "standard --fix"
}
}