@gjsify/cli 0.64.40 → 0.64.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli-app.js CHANGED
@@ -18,7 +18,7 @@
18
18
  import yargs from 'yargs';
19
19
  import { classifyCliFailure } from './cli-fail.js';
20
20
  import { cliVersion } from './utils/publish-headers.js';
21
- import { buildCommand as build, clearCommand as clear, copyCommand as copy, envCommand as env, execCommand as exec, testCommand as test, runCommand as run, infoCommand as info, systemCheckCommand as systemCheck, checkCommand as check, showcaseCommand as showcase, createCommand as create, gresourceCommand as gresource, gettextCommand as gettext, gsettingsCommand as gsettings, flatpakCommand as flatpak, shipCommand as ship, dlxCommand as dlx, installCommand as install, linkCommand as link, unlinkCommand as unlink, foreachCommand as foreach, workspaceCommand as workspace, packCommand as pack, publishCommand as publish, whoamiCommand as whoami, releaseNotesCommand as releaseNotes, androidIconsCommand as androidIcons, creditsCommand as credits, loginCommand as login, logoutCommand as logout, trustCommand as trust, onboardCommand as onboard, selfUpdateCommand as selfUpdate, generateInstallerCommand as generateInstaller, pruneCommand as prune, uninstallCommand as uninstall, formatCommand as format, lintCommand as lint, fixCommand as fix, upgradeCommand as upgrade, barrelsCommand as barrels, tscCommand as tsc, affectedCommand as affected, storybookCommand as storybook, siteCommand as site, devCommand as dev, debugCommand as debug, devtoolsCommand as devtools, browseCommand as browse, webextCommand as webext, blueprintCommand as blueprint, } from './commands/index.js';
21
+ import { buildCommand as build, clearCommand as clear, copyCommand as copy, envCommand as env, execCommand as exec, testCommand as test, runCommand as run, infoCommand as info, systemCheckCommand as systemCheck, checkCommand as check, showcaseCommand as showcase, createCommand as create, gresourceCommand as gresource, gettextCommand as gettext, gsettingsCommand as gsettings, flatpakCommand as flatpak, shipCommand as ship, flatparkCommand as flatpark, dlxCommand as dlx, installCommand as install, linkCommand as link, unlinkCommand as unlink, foreachCommand as foreach, workspaceCommand as workspace, packCommand as pack, publishCommand as publish, whoamiCommand as whoami, releaseNotesCommand as releaseNotes, androidIconsCommand as androidIcons, creditsCommand as credits, loginCommand as login, logoutCommand as logout, trustCommand as trust, onboardCommand as onboard, selfUpdateCommand as selfUpdate, generateInstallerCommand as generateInstaller, pruneCommand as prune, uninstallCommand as uninstall, formatCommand as format, lintCommand as lint, fixCommand as fix, upgradeCommand as upgrade, barrelsCommand as barrels, tscCommand as tsc, affectedCommand as affected, storybookCommand as storybook, siteCommand as site, devCommand as dev, debugCommand as debug, devtoolsCommand as devtools, browseCommand as browse, webextCommand as webext, blueprintCommand as blueprint, } from './commands/index.js';
22
22
  import { APP_NAME } from './constants.js';
23
23
  import { isBun, isDeno, isNode, gjsSystemVersion } from '@gjsify/rolldown-plugin-gjsify/runtime';
24
24
  import { ensureGjsifyShimOnPath } from './utils/gjsify-shim.js';
@@ -112,6 +112,7 @@ export async function runCli(argv) {
112
112
  .command(gsettings.command, gsettings.description, gsettings.builder, gsettings.handler)
113
113
  .command(flatpak.command, flatpak.description, flatpak.builder, flatpak.handler)
114
114
  .command(ship.command, ship.description, ship.builder, ship.handler)
115
+ .command(flatpark.command, flatpark.description, flatpark.builder, flatpark.handler)
115
116
  .command(foreach.command, foreach.description, foreach.builder, foreach.handler)
116
117
  .command(workspace.command, workspace.description, workspace.builder, workspace.handler)
117
118
  .command(pack.command, pack.description, pack.builder, pack.handler)
@@ -0,0 +1,11 @@
1
+ import type { Command } from '../types/index.js';
2
+ interface FlatparkOptions {
3
+ project?: string;
4
+ out: string;
5
+ stage?: string;
6
+ 'release-dir'?: string;
7
+ repo?: string;
8
+ 'tag-prefix': string;
9
+ }
10
+ export declare const flatparkCommand: Command<unknown, FlatparkOptions>;
11
+ export {};
@@ -0,0 +1,147 @@
1
+ // `gjsify flatpark [project] --out <dir>` — write the FlatPark package directory
2
+ // (`registry/<app-id>/`) for a project that already ran `gjsify ship`.
3
+ //
4
+ // It only WRITES FILES. No pull request, no push, no network, no hashing: the
5
+ // download URL, sha256 and size come from the release record `ship` wrote beside
6
+ // the `linux-tar-flatpak` archive, and a missing record stops the command. What
7
+ // goes where is the module header of `utils/ship/flatpark.ts` and ADR 0143.
8
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join, relative, resolve } from 'node:path';
10
+ import { Config } from '../config.js';
11
+ import { readPackageJson } from '../utils/pkg-json.js';
12
+ import { parseGithubRepo, readFlatparkSources, releaseDateOf, renderFlatparkPackage } from '../utils/ship/flatpark.js';
13
+ import { readStageManifest } from '../utils/ship/stage-manifest.js';
14
+ const LOG = '[gjsify flatpark]';
15
+ /** `--repo`, else the project's `repository`, else `gjsify.site.repository` of it or of an ancestor. */
16
+ function resolveRepo(flag, projectDir) {
17
+ const candidates = [];
18
+ if (flag !== undefined)
19
+ candidates.push(['--repo', flag]);
20
+ let dir = projectDir;
21
+ for (let depth = 0; depth < 5; depth++) {
22
+ const pkg = readPackageJson(join(dir, 'package.json'));
23
+ if (pkg !== undefined && pkg !== null) {
24
+ const repository = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository?.url;
25
+ if (depth === 0)
26
+ candidates.push([`${join(dir, 'package.json')} repository`, repository]);
27
+ candidates.push([`${join(dir, 'package.json')} gjsify.site.repository`, pkg.gjsify?.site?.repository]);
28
+ }
29
+ if (dirname(dir) === dir)
30
+ break;
31
+ dir = dirname(dir);
32
+ }
33
+ for (const [source, value] of candidates) {
34
+ if (value === undefined)
35
+ continue;
36
+ const repo = parseGithubRepo(value);
37
+ if (repo === undefined)
38
+ throw new Error(`${LOG} ${source} is "${value}", which is not a GitHub repository.`);
39
+ return repo;
40
+ }
41
+ throw new Error(`${LOG} no GitHub repository to download from. Pass --repo owner/name, or set \`repository\` in ` +
42
+ 'package.json or `gjsify.site.repository`.');
43
+ }
44
+ export const flatparkCommand = {
45
+ command: 'flatpark [project]',
46
+ description: 'Write the FlatPark package directory (registry/<app-id>/) for a project that ran `gjsify ship`.',
47
+ builder: (yargs) => yargs
48
+ .positional('project', {
49
+ type: 'string',
50
+ description: 'The project directory. Default: the current directory.',
51
+ })
52
+ .option('out', {
53
+ type: 'string',
54
+ demandOption: true,
55
+ requiresArg: true,
56
+ description: 'The package directory to write, e.g. `<flatpark>/registry/eu.example.App`.',
57
+ })
58
+ .option('stage', {
59
+ type: 'string',
60
+ requiresArg: true,
61
+ description: 'A `gjsify ship --stage` directory. Default: `<out dir of ship>/stage` of the project.',
62
+ })
63
+ .option('release-dir', {
64
+ type: 'string',
65
+ requiresArg: true,
66
+ description: 'The directory holding `<artifact>.gjsify-release.json`. Default: `out/` of the ship out dir.',
67
+ })
68
+ .option('repo', {
69
+ type: 'string',
70
+ requiresArg: true,
71
+ description: 'GitHub `owner/name` the releases are published on. Default: read from the project.',
72
+ })
73
+ .option('tag-prefix', {
74
+ type: 'string',
75
+ default: 'v',
76
+ description: 'What precedes the version in the release tag.',
77
+ }),
78
+ handler: async (args) => {
79
+ const projectDir = resolve(args.project ?? process.cwd());
80
+ const config = await new Config().forCommand(projectDir);
81
+ const shipOut = resolve(projectDir, config.ship?.outDir ?? 'ship');
82
+ const stageDir = resolve(projectDir, args.stage ?? join(shipOut, 'stage'));
83
+ const releaseDir = resolve(projectDir, args['release-dir'] ?? join(shipOut, 'out'));
84
+ const outDir = resolve(args.out);
85
+ const manifest = readStageManifest(stageDir);
86
+ const settings = manifest.settings;
87
+ const staged = (path) => {
88
+ const file = join(stageDir, path);
89
+ if (!existsSync(file)) {
90
+ throw new Error(`${LOG} the stage has no ${path}. A FlatPark package needs a desktop application: ` +
91
+ 'stage it with `gjsify ship --stage` on a project of `kind: app`.');
92
+ }
93
+ return file;
94
+ };
95
+ const repo = resolveRepo(args.repo, projectDir);
96
+ const icon = pickIcon(stageDir, settings.appId);
97
+ const sources = readFlatparkSources({
98
+ dir: releaseDir,
99
+ repo,
100
+ version: settings.version,
101
+ tagPrefix: args['tag-prefix'],
102
+ stageArch: manifest.target.arch,
103
+ });
104
+ const files = renderFlatparkPackage({
105
+ appId: settings.appId,
106
+ name: settings.name,
107
+ binaryName: settings.binaryName,
108
+ summary: settings.summary,
109
+ version: settings.version,
110
+ ...(settings.homepage === undefined ? {} : { homepage: settings.homepage }),
111
+ repo,
112
+ flatpak: settings.flatpak,
113
+ sources,
114
+ desktopEntry: readFileSync(staged(`share/applications/${settings.appId}.desktop`), 'utf-8'),
115
+ metainfo: readFileSync(staged(`share/metainfo/${settings.appId}.metainfo.xml`), 'utf-8'),
116
+ icon,
117
+ releaseDate: releaseDateOf(manifest.mtime),
118
+ });
119
+ mkdirSync(outDir, { recursive: true });
120
+ for (const file of files) {
121
+ writeFileSync(join(outDir, file.path), file.data, { mode: file.mode });
122
+ }
123
+ console.log(`${LOG} wrote ${files.length} file(s) for ${settings.appId} ${settings.version} to ${outDir}`);
124
+ for (const source of sources)
125
+ console.log(`${LOG} ${source.arch}: ${source.url}`);
126
+ console.log(`${LOG} next: ${relative(process.cwd(), join(outDir, 'flatpark.yml')) || 'flatpark.yml'} has ` +
127
+ "`upstream_approved: false`; a row in FlatPark's docs/reference/upstream-approvals.md is the maintainer's.");
128
+ },
129
+ };
130
+ /** The 128 px raster when the stage has one, else the largest up to 512 px. FlatPark takes no bigger. */
131
+ function pickIcon(stageDir, appId) {
132
+ const base = join(stageDir, 'share', 'icons', 'hicolor');
133
+ const sizes = existsSync(base)
134
+ ? readdirSync(base)
135
+ .map((entry) => /^(\d+)x\1$/.exec(entry)?.[1])
136
+ .filter((size) => size !== undefined)
137
+ .map(Number)
138
+ .filter((size) => size <= 512 && existsSync(join(base, `${size}x${size}`, 'apps', `${appId}.png`)))
139
+ .sort((a, b) => a - b)
140
+ : [];
141
+ const size = sizes.includes(128) ? 128 : sizes[sizes.length - 1];
142
+ if (size === undefined) {
143
+ throw new Error(`${LOG} the stage has no PNG icon for ${appId} up to 512 px under share/icons/hicolor/. FlatPark ` +
144
+ 'takes a PNG or an SVG, and an SVG can fail AppStream compose, so this command wants a raster.');
145
+ }
146
+ return { bytes: readFileSync(join(base, `${size}x${size}`, 'apps', `${appId}.png`)), size };
147
+ }
@@ -15,6 +15,7 @@ export * from './gettext.js';
15
15
  export * from './gsettings.js';
16
16
  export { flatpakCommand } from './flatpak/index.js';
17
17
  export * from './ship.js';
18
+ export * from './flatpark.js';
18
19
  export * from './dlx.js';
19
20
  export * from './install.js';
20
21
  export * from './link.js';
@@ -15,6 +15,7 @@ export * from './gettext.js';
15
15
  export * from './gsettings.js';
16
16
  export { flatpakCommand } from './flatpak/index.js';
17
17
  export * from './ship.js';
18
+ export * from './flatpark.js';
18
19
  export * from './dlx.js';
19
20
  export * from './install.js';
20
21
  export * from './link.js';
@@ -262,6 +262,9 @@ async function fetchOnce(session, startUrl, { forceHttp1 = false } = {}) {
262
262
  if (status !== Soup.Status.OK) {
263
263
  const err = new Error(`HTTP ${status} from ${url}`);
264
264
  err.httpStatus = status;
265
+ // Who said no: a refusal from a redirect TARGET is the CDN's signed URL
266
+ // misbehaving; from the first hop it is the host we asked answering.
267
+ err.fromRedirect = hop > 0;
265
268
  throw err;
266
269
  }
267
270
  return bytes.get_data();
@@ -286,6 +289,13 @@ async function fetchOnce(session, startUrl, { forceHttp1 = false } = {}) {
286
289
  * is it saying no; retrying either would only delay the same result while making a real
287
290
  * outage look like a hang.
288
291
  *
292
+ * SECOND INCIDENT (2026-11-14, PR #2639): three CI attempts in a row died on `HTTP 403 from
293
+ * https://release-assets.githubusercontent.com/…`, for the `.sha256` and the bundle alike.
294
+ * github.com answers 302 to a short-lived SIGNED CDN URL and that CDN transiently answers
295
+ * 403. So a 403 from a REDIRECT TARGET (hop > 0) is a hiccup too and is retried — each
296
+ * retry restarts at the original URL, which mints a fresh signed URL. A 403 from the FIRST
297
+ * hop (the host we asked, github.com itself) stays an answer, exactly like a 404.
298
+ *
289
299
  * FIVE attempts, not three, and the numbers come from a run rather than a preference:
290
300
  * with three the CI log showed `retry 2/3` and `retry 3/3` and still failed, because each
291
301
  * attempt takes ~20 s to give up — so the 500ms/1500ms backoff was noise beside it and the
@@ -308,7 +318,11 @@ async function fetchBytes(session, url) {
308
318
  } catch (err) {
309
319
  lastErr = err;
310
320
  const status = err.httpStatus;
311
- const retriable = status === undefined || status === 429 || status >= 500;
321
+ const retriable =
322
+ status === undefined ||
323
+ status === 429 ||
324
+ status >= 500 ||
325
+ (status === 403 && err.fromRedirect === true);
312
326
  if (!retriable || attempt === attempts) break;
313
327
  const wait = RETRY_BACKOFF_MS[Math.min(attempt - 1, RETRY_BACKOFF_MS.length - 1)];
314
328
  info(`Fetch of ${url} failed (${err.message}) — retry ${attempt + 1}/${attempts} in ${wait}ms`);
@@ -0,0 +1,84 @@
1
+ import type { ShipFlatpakSettings } from './types.js';
2
+ /** The extra-data file name inside the Flatpak. Fixed: the hook and the resolver both name it. */
3
+ export declare const FLATPARK_EXTRA_FILE = "app.tar.gz";
4
+ /** The only format whose archive is meant as an `extra-data` source (ADR 0142). */
5
+ export declare const FLATPARK_RECORD_FORMAT = "linux-tar-flatpak";
6
+ export interface FlatparkSource {
7
+ /** Flatpak spelling: `x86_64` or `aarch64`. */
8
+ arch: string;
9
+ /** Release asset name — the record's `artifact`. */
10
+ artifact: string;
11
+ url: string;
12
+ sha256: string;
13
+ size: number;
14
+ }
15
+ export interface FlatparkInputs {
16
+ appId: string;
17
+ name: string;
18
+ binaryName: string;
19
+ summary: string;
20
+ version: string;
21
+ homepage?: string;
22
+ /** `owner/name` of the GitHub repository the releases are published on. */
23
+ repo: string;
24
+ flatpak: Pick<ShipFlatpakSettings, 'runtime' | 'runtimeVersion' | 'sdk' | 'finishArgs'>;
25
+ /** Sorted by arch by the caller of {@link readFlatparkSources}; rendered in the order given. */
26
+ sources: readonly FlatparkSource[];
27
+ /** The stage's own, as `gjsify ship` rendered it. */
28
+ desktopEntry: string;
29
+ metainfo: string;
30
+ icon: {
31
+ bytes: Uint8Array;
32
+ size: number;
33
+ };
34
+ /** `YYYY-MM-DD`, UTC. */
35
+ releaseDate: string;
36
+ }
37
+ export interface FlatparkFile {
38
+ /** Relative to the package directory. */
39
+ path: string;
40
+ mode: number;
41
+ data: string | Uint8Array;
42
+ }
43
+ /** `owner/name` out of `owner/name`, a github.com URL, or a `git+https://….git` URL. */
44
+ export declare function parseGithubRepo(value: string): string | undefined;
45
+ /** The UTC calendar date of a build stamp (seconds since the epoch). */
46
+ export declare function releaseDateOf(mtime: number): string;
47
+ /**
48
+ * The release records beside the artifacts in `dir`, as FlatPark sources.
49
+ *
50
+ * The URL is the only thing derived here and it is derived from the repository
51
+ * and the version, never fetched; `sha256` and `size` are the record's, which
52
+ * `gjsify ship` took from the bytes it wrote. A missing record is an error and
53
+ * not a reason to hash the file ourselves: a hash this command computed would
54
+ * describe whatever is on this disk, not what was published.
55
+ */
56
+ export declare function readFlatparkSources(input: {
57
+ dir: string;
58
+ repo: string;
59
+ version: string;
60
+ tagPrefix: string;
61
+ /**
62
+ * The arch the stage was assembled for. A pure-script payload records `noarch`, but its archive
63
+ * name still carries one label and a FlatPark source needs an arch to pin — the stage's.
64
+ */
65
+ stageArch?: string;
66
+ }): FlatparkSource[];
67
+ /** The unpack hook. No version anywhere; the one asserted path derives from `binaryName`. */
68
+ export declare function renderApplyExtra(binaryName: string): string;
69
+ export declare function renderWrapper(binaryName: string): string;
70
+ /**
71
+ * The Flatpak manifest. The `extra-data` sources sit between marker comments
72
+ * because FlatPark's updater rewrites exactly that block on every release.
73
+ */
74
+ export declare function renderManifest(input: FlatparkInputs): string;
75
+ export declare function renderDescriptor(input: FlatparkInputs): string;
76
+ export declare function renderResolveUpdate(input: FlatparkInputs): string;
77
+ /**
78
+ * The metainfo with a `<releases>` block carrying this version, unless it has
79
+ * one. FlatPark compares the resolver's version against the newest `<release>`
80
+ * here, and Flatpak ignores an undated one — so a package starts with exactly one.
81
+ */
82
+ export declare function withRelease(metainfo: string, version: string, date: string): string;
83
+ /** Every file of the package directory, in a fixed order. */
84
+ export declare function renderFlatparkPackage(input: FlatparkInputs): FlatparkFile[];
@@ -0,0 +1,298 @@
1
+ // `gjsify flatpark` — the FlatPark package directory (ADR 0143).
2
+ //
3
+ // FlatPark (https://github.com/flatpark/flatpark) builds `extra-data` Flatpaks from
4
+ // an upstream tarball: a `registry/<app-id>/` directory of a manifest, a hook that
5
+ // unpacks the download, a few install files and a descriptor. This module renders
6
+ // that directory from what `gjsify ship` already produced — the stage's desktop
7
+ // entry, metainfo and icon, the stage manifest's settings, and the release record
8
+ // beside the tarball — and WRITES NOTHING ELSE: no network, no hashing, no clock.
9
+ //
10
+ // Two rules the rendering is shaped by, both measured in the Phase-0 spike:
11
+ //
12
+ // * `apply_extra.sh` never names a version. The tarball's top directory is
13
+ // `<bin>-<version>-linux-<arch>`, so a hook that hard-codes it breaks on the
14
+ // first update that FlatPark's resolver pins. The hook finds the one top-level
15
+ // directory and refuses anything else; the only path it asserts is
16
+ // `bin/<binaryName>`, which is stable.
17
+ // * The same inputs give the same bytes. Nothing here reads a path, a hostname
18
+ // or the time: the release date is the stage's build stamp (`mtime`), which is
19
+ // the one stamp every other file of that stage already shares.
20
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+ import { RELEASE_RECORD_SUFFIX } from './release-record.js';
23
+ import { xmlEscape } from './xml.js';
24
+ /** The extra-data file name inside the Flatpak. Fixed: the hook and the resolver both name it. */
25
+ export const FLATPARK_EXTRA_FILE = 'app.tar.gz';
26
+ /** The only format whose archive is meant as an `extra-data` source (ADR 0142). */
27
+ export const FLATPARK_RECORD_FORMAT = 'linux-tar-flatpak';
28
+ /** `process.arch` spelling → Flatpak arch. */
29
+ const FLATPAK_ARCH = { x64: 'x86_64', arm64: 'aarch64' };
30
+ /** `owner/name` out of `owner/name`, a github.com URL, or a `git+https://….git` URL. */
31
+ export function parseGithubRepo(value) {
32
+ const trimmed = value.trim().replace(/^git\+/, '');
33
+ const bare = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(trimmed);
34
+ const url = /^(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(trimmed);
35
+ const hit = url ?? bare;
36
+ return hit === null ? undefined : `${hit[1]}/${hit[2].replace(/\.git$/, '')}`;
37
+ }
38
+ /** The UTC calendar date of a build stamp (seconds since the epoch). */
39
+ export function releaseDateOf(mtime) {
40
+ return new Date(mtime * 1000).toISOString().slice(0, 10);
41
+ }
42
+ /**
43
+ * The release records beside the artifacts in `dir`, as FlatPark sources.
44
+ *
45
+ * The URL is the only thing derived here and it is derived from the repository
46
+ * and the version, never fetched; `sha256` and `size` are the record's, which
47
+ * `gjsify ship` took from the bytes it wrote. A missing record is an error and
48
+ * not a reason to hash the file ourselves: a hash this command computed would
49
+ * describe whatever is on this disk, not what was published.
50
+ */
51
+ export function readFlatparkSources(input) {
52
+ const records = [];
53
+ if (existsSync(input.dir)) {
54
+ for (const file of readdirSync(input.dir).sort()) {
55
+ if (!file.endsWith(RELEASE_RECORD_SUFFIX))
56
+ continue;
57
+ const record = JSON.parse(readFileSync(join(input.dir, file), 'utf-8'));
58
+ if (record.format === FLATPARK_RECORD_FORMAT && record.os === 'linux')
59
+ records.push(record);
60
+ }
61
+ }
62
+ if (records.length === 0) {
63
+ throw new Error(`gjsify flatpark: no release record for \`${FLATPARK_RECORD_FORMAT}\` in ${input.dir}. The URL, sha256 ` +
64
+ `and size come from \`<artifact>${RELEASE_RECORD_SUFFIX}\`, which \`gjsify ship --target ` +
65
+ `${FLATPARK_RECORD_FORMAT}\` writes beside the archive. Run that first, or point --release-dir at ` +
66
+ 'the directory that holds the record.');
67
+ }
68
+ const tag = `${input.tagPrefix}${input.version}`;
69
+ const sources = records.map((record) => {
70
+ const arch = FLATPAK_ARCH[record.arch === 'noarch' ? (input.stageArch ?? record.arch) : record.arch];
71
+ if (arch === undefined) {
72
+ throw new Error(`gjsify flatpark: ${record.artifact} is built for \`${record.arch}\`, which has no Flatpak arch ` +
73
+ `(known: ${Object.keys(FLATPAK_ARCH).join(', ')}).`);
74
+ }
75
+ return {
76
+ arch,
77
+ artifact: record.artifact,
78
+ url: `https://github.com/${input.repo}/releases/download/${tag}/${record.artifact}`,
79
+ sha256: record.sha256,
80
+ size: record.size,
81
+ };
82
+ });
83
+ const seen = new Set();
84
+ for (const source of sources) {
85
+ if (seen.has(source.arch)) {
86
+ throw new Error(`gjsify flatpark: two release records for ${source.arch} in ${input.dir}; keep one.`);
87
+ }
88
+ seen.add(source.arch);
89
+ }
90
+ return sources.sort((a, b) => a.arch.localeCompare(b.arch));
91
+ }
92
+ /** The unpack hook. No version anywhere; the one asserted path derives from `binaryName`. */
93
+ export function renderApplyExtra(binaryName) {
94
+ return `#!/bin/sh
95
+ set -eu
96
+
97
+ extra_root="\${EXTRA_ROOT:-/app/extra}"
98
+ cd "$extra_root"
99
+
100
+ [ -f ${FLATPARK_EXTRA_FILE} ] || { echo "missing extra-data: ${FLATPARK_EXTRA_FILE}" >&2; exit 1; }
101
+
102
+ rm -rf stage app
103
+ mkdir stage
104
+ bsdtar --no-same-owner -xf ${FLATPARK_EXTRA_FILE} -C stage
105
+
106
+ top="$(find stage -mindepth 1 -maxdepth 1 -type d)"
107
+ [ "$(printf '%s\\n' "$top" | wc -l)" -eq 1 ] || { echo "expected one top-level directory" >&2; exit 1; }
108
+ mv "$top" app
109
+ [ -x app/bin/${shellWord(binaryName)} ] || { echo "${shellWord(binaryName)} launcher not found in the tarball" >&2; exit 1; }
110
+
111
+ rm -rf stage ${FLATPARK_EXTRA_FILE}
112
+ `;
113
+ }
114
+ export function renderWrapper(binaryName) {
115
+ return `#!/bin/sh
116
+ set -eu
117
+ exec /app/extra/app/bin/${shellWord(binaryName)} "$@"
118
+ `;
119
+ }
120
+ /** A binary name is a package name; anything outside this set would need quoting we do not do. */
121
+ function shellWord(value) {
122
+ if (!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(value)) {
123
+ throw new Error(`gjsify flatpark: binary name "${value}" is not a plain file name.`);
124
+ }
125
+ return value;
126
+ }
127
+ /** A YAML scalar: plain when that reads back as the same string, JSON-quoted otherwise. */
128
+ function yamlString(value) {
129
+ const plain = /^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(value) &&
130
+ !/^(?:true|false|null|yes|no|on|off|~)$/i.test(value) &&
131
+ !/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(value) &&
132
+ !/: |:$| $|^- /.test(value) &&
133
+ !/^0[xo]/i.test(value);
134
+ return plain ? value : JSON.stringify(value);
135
+ }
136
+ /**
137
+ * The Flatpak manifest. The `extra-data` sources sit between marker comments
138
+ * because FlatPark's updater rewrites exactly that block on every release.
139
+ */
140
+ export function renderManifest(input) {
141
+ const { appId, binaryName } = input;
142
+ const files = [
143
+ 'apply_extra.sh',
144
+ `${binaryName}-wrapper`,
145
+ `${appId}.desktop`,
146
+ `${appId}.metainfo.xml`,
147
+ `${appId}.png`,
148
+ ];
149
+ const lines = [
150
+ `id: ${yamlString(appId)}`,
151
+ `runtime: ${yamlString(input.flatpak.runtime)}`,
152
+ `runtime-version: ${JSON.stringify(input.flatpak.runtimeVersion)}`,
153
+ `sdk: ${yamlString(input.flatpak.sdk)}`,
154
+ `command: ${yamlString(binaryName)}`,
155
+ 'separate-locales: false',
156
+ 'build-options:',
157
+ ' no-debuginfo: true',
158
+ 'finish-args:',
159
+ ...input.flatpak.finishArgs.map((arg) => ` - ${yamlString(arg)}`),
160
+ 'modules:',
161
+ ` - name: ${yamlString(binaryName)}`,
162
+ ' buildsystem: simple',
163
+ ' build-commands:',
164
+ ' - install -Dm755 apply_extra.sh /app/bin/apply_extra',
165
+ ` - install -Dm755 ${binaryName}-wrapper /app/bin/${binaryName}`,
166
+ ` - install -Dm644 ${appId}.desktop /app/share/applications/${appId}.desktop`,
167
+ ` - install -Dm644 ${appId}.metainfo.xml /app/share/metainfo/${appId}.metainfo.xml`,
168
+ ` - install -Dm644 ${appId}.png /app/share/icons/hicolor/${input.icon.size}x${input.icon.size}/apps/${appId}.png`,
169
+ ' sources:',
170
+ ' # BEGIN MANAGED EXTRA-DATA',
171
+ ...input.sources.flatMap((source) => [
172
+ ' - type: extra-data',
173
+ ` filename: ${FLATPARK_EXTRA_FILE}`,
174
+ ' only-arches:',
175
+ ` - ${source.arch}`,
176
+ ` url: ${yamlString(source.url)}`,
177
+ ` sha256: ${source.sha256}`,
178
+ ` size: ${source.size}`,
179
+ ]),
180
+ ' # END MANAGED EXTRA-DATA',
181
+ ...files.flatMap((path) => [' - type: file', ` path: ${yamlString(path)}`]),
182
+ ];
183
+ return `${lines.join('\n')}\n`;
184
+ }
185
+ /** The first `<category>` of the metainfo — FlatPark's catalogue takes one. */
186
+ function firstCategory(metainfo) {
187
+ return /<category>([^<]+)<\/category>/.exec(metainfo)?.[1]?.trim() ?? 'Utility';
188
+ }
189
+ function keywords(metainfo) {
190
+ return [...metainfo.matchAll(/<keyword>([^<]+)<\/keyword>/g)].map((hit) => hit[1].trim());
191
+ }
192
+ export function renderDescriptor(input) {
193
+ const tags = keywords(input.metainfo);
194
+ const lines = [
195
+ `id: ${yamlString(input.appId)}`,
196
+ `name: ${yamlString(input.name)}`,
197
+ `summary: ${yamlString(input.summary)}`,
198
+ `website: ${yamlString(input.homepage ?? `https://github.com/${input.repo}`)}`,
199
+ `source_url: https://github.com/${input.repo}`,
200
+ 'build:',
201
+ ` manifest: ${input.appId}.yml`,
202
+ ' branch: stable',
203
+ ' mode: extra-data',
204
+ ` arches: [${input.sources.map((source) => source.arch).join(', ')}]`,
205
+ 'catalog:',
206
+ ` category: ${yamlString(firstCategory(input.metainfo))}`,
207
+ // The row in FlatPark's `upstream-approvals.md` is the maintainer's to add.
208
+ ' upstream_approved: false',
209
+ ...(tags.length === 0 ? [] : [' tags:', ...tags.map((tag) => ` - ${yamlString(tag)}`)]),
210
+ 'update:',
211
+ ' command: ./resolve-update.sh',
212
+ 'policy:',
213
+ ' proprietary: false',
214
+ ' dangerous_permissions: []',
215
+ ];
216
+ return `${lines.join('\n')}\n`;
217
+ }
218
+ /** `jq`'s regex (Oniguruma), for the asset name of one arch with the version abstracted. */
219
+ function assetPattern(source, version) {
220
+ const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
221
+ const at = source.artifact.indexOf(version);
222
+ if (at < 0) {
223
+ throw new Error(`gjsify flatpark: ${source.artifact} does not contain the version ${version}.`);
224
+ }
225
+ return `^${escaped(source.artifact.slice(0, at))}[0-9][0-9A-Za-z.+~-]*${escaped(source.artifact.slice(at + version.length))}$`;
226
+ }
227
+ export function renderResolveUpdate(input) {
228
+ const sourceVars = input.sources.map((source) => {
229
+ const key = source.arch.replace(/[^a-z0-9]/g, '_');
230
+ return { source, key, pattern: assetPattern(source, input.version).replace(/\\/g, '\\\\') };
231
+ });
232
+ const lookups = sourceVars.map(({ key, pattern }) => `url_${key}="$(jq -r '.assets[] | select(.name | test("${pattern}")) | .browser_download_url' <<<"$rel" | head -n1)"\n` +
233
+ `[ -n "$url_${key}" ] || { echo "no ${key} asset in this release" >&2; exit 1; }`);
234
+ const sources = sourceVars.map(({ source, key }) => `{filename:"${FLATPARK_EXTRA_FILE}", arch:"${source.arch}", url:$u_${key}}`);
235
+ const args = sourceVars.map(({ key }) => `--arg u_${key} "$url_${key}"`);
236
+ return `#!/usr/bin/env bash
237
+ # Update resolver for ${input.name}, written by \`gjsify flatpark\`.
238
+ #
239
+ # Prints the latest release on stdout as JSON:
240
+ # { "version": "…", "releaseDate": "YYYY-MM-DD",
241
+ # "sources": [ { "filename": "${FLATPARK_EXTRA_FILE}", "arch": "…", "url": "…" } ] }
242
+ # Logs go to stderr. No hashing and no manifest rewriting: FlatPark downloads
243
+ # each URL and computes the extra-data sha256 and size itself.
244
+ set -euo pipefail
245
+
246
+ repo="${input.repo}"
247
+
248
+ need() { command -v "$1" >/dev/null 2>&1 || { echo "missing command: $1" >&2; exit 1; }; }
249
+ need curl; need jq
250
+
251
+ rel="$(curl -fsSL \${GITHUB_TOKEN:+-H "Authorization: Bearer $GITHUB_TOKEN"} \\
252
+ "https://api.github.com/repos/$repo/releases/latest")"
253
+
254
+ version="$(jq -r '.tag_name | ltrimstr("v")' <<<"$rel")"
255
+ date="$(jq -r '.published_at' <<<"$rel" | cut -c1-10)"
256
+ [ -n "$version" ] && [ "$version" != "null" ] || { echo "failed to resolve the latest release of $repo" >&2; exit 1; }
257
+
258
+ ${lookups.join('\n')}
259
+ echo "resolved ${input.name} $version ($date)" >&2
260
+
261
+ jq -n --arg v "$version" --arg d "$date" ${args.join(' ')} \\
262
+ '{version:$v, releaseDate:$d, sources:[${sources.join(', ')}]}'
263
+ `;
264
+ }
265
+ /**
266
+ * The metainfo with a `<releases>` block carrying this version, unless it has
267
+ * one. FlatPark compares the resolver's version against the newest `<release>`
268
+ * here, and Flatpak ignores an undated one — so a package starts with exactly one.
269
+ */
270
+ export function withRelease(metainfo, version, date) {
271
+ if (/<releases[\s>]/.test(metainfo))
272
+ return metainfo;
273
+ const block = ` <releases>\n <release version="${xmlEscape(version)}" date="${date}" />\n </releases>\n`;
274
+ const close = metainfo.lastIndexOf('</component>');
275
+ if (close < 0)
276
+ throw new Error('gjsify flatpark: the staged metainfo has no </component>.');
277
+ return `${metainfo.slice(0, close)}${block}${metainfo.slice(close)}`;
278
+ }
279
+ /** Every file of the package directory, in a fixed order. */
280
+ export function renderFlatparkPackage(input) {
281
+ const { appId, binaryName } = input;
282
+ if (input.sources.length === 0)
283
+ throw new Error('gjsify flatpark: no sources to pin.');
284
+ return [
285
+ { path: `${appId}.yml`, mode: 0o644, data: renderManifest(input) },
286
+ { path: 'apply_extra.sh', mode: 0o755, data: renderApplyExtra(binaryName) },
287
+ { path: `${binaryName}-wrapper`, mode: 0o755, data: renderWrapper(binaryName) },
288
+ { path: `${appId}.desktop`, mode: 0o644, data: input.desktopEntry },
289
+ {
290
+ path: `${appId}.metainfo.xml`,
291
+ mode: 0o644,
292
+ data: withRelease(input.metainfo, input.version, input.releaseDate),
293
+ },
294
+ { path: `${appId}.png`, mode: 0o644, data: input.icon.bytes },
295
+ { path: 'flatpark.yml', mode: 0o644, data: renderDescriptor(input) },
296
+ { path: 'resolve-update.sh', mode: 0o755, data: renderResolveUpdate(input) },
297
+ ];
298
+ }
@@ -0,0 +1,2 @@
1
+ import { type StoreBackend, type StoreBackendOptions, type StoreCredentials } from './index.js';
2
+ export declare function createChromeBackend(credentials: StoreCredentials, options?: StoreBackendOptions): StoreBackend;