Xdelta patching (#71)
Some checks failed
Deploy Supabase Migrations to Production / migrate (push) Has been cancelled

* Add xdelta patch support

* Fix potential race on reupload to new format + update typings

* Fix waiting too long to call showSaveFilePicker

* Allow seeing patch format in version history
This commit is contained in:
Jared Schoeny
2026-08-03 10:56:45 -06:00
committed by GitHub
parent 30ab839d0f
commit c7c88d1840
25 changed files with 1139 additions and 136 deletions

View File

@@ -16,8 +16,8 @@ Hackdex is a community hub for discovering and sharing Pokémon romhack patches.
## Core features
- **Discover**: curated hacks with screenshots, tags, versions, and summaries
- **Submit**: metadata, screenshots, social links, and a BPS patch file
- **Patch in the browser**: Powered by [RomPatcher.js](https://github.com/marcrobledo/RomPatcher.js); linked base roms stay on the user's device
- **Submit**: metadata, screenshots, social links, and a `.bps` or `.xdelta` patch file
- **Patch in the browser**: BPS via [RomPatcher.js](https://github.com/marcrobledo/RomPatcher.js); xdelta (VCDIFF) via a WASM build of [xdelta3](https://github.com/jmacd/xdelta) with glue from the Hackdex fork of [xdelta-wasm](https://github.com/Hackdex-App/xdelta-wasm) (forked from [kotcrab/xdelta-wasm](https://github.com/kotcrab/xdelta-wasm); statically linked [XZ Utils](https://tukaani.org/xz/) liblzma); linked base roms stay on the user's device
- **Safe delivery**: public urls for cover images, short-lived signed URLs for patch downloads and other assets; no rom storage required
## Tech stack
@@ -25,7 +25,7 @@ Hackdex is a community hub for discovering and sharing Pokémon romhack patches.
- Next.js 15 (App Router), TypeScript, React 19, Tailwind CSS 4
- Supabase (Postgres, Auth, Storage) for data, auth, and cover images
- S3-compatible object storage (Minio locally or preferred provider) for patch files (`patches` bucket)
- In-browser patching with RomPatcher.js; local persistence with IndexedDB and the File System Access API
- In-browser patching with RomPatcher.js and xdelta3 WASM; local persistence with IndexedDB and the File System Access API
## High-level architecture

69
docs/xdelta-wasm.md Normal file
View File

@@ -0,0 +1,69 @@
# Building and vendoring xdelta WASM
Hackdex patches xdelta (VCDIFF) files in the browser using a WebAssembly build of [xdelta3](https://github.com/jmacd/xdelta). That binary is **not** built inside this repo. You build it from a local checkout of the Hackdex fork of [xdelta-wasm](https://github.com/Hackdex-App/xdelta-wasm) (forked from [kotcrab/xdelta-wasm](https://github.com/kotcrab/xdelta-wasm)), then copy two artifacts into `public/xdelta/`.
Use this guide when you need to rebuild or update those artifacts.
---
## Prerequisites
- A local checkout of [Hackdex-App/xdelta-wasm](https://github.com/Hackdex-App/xdelta-wasm).
- [Emscripten](https://emscripten.org) (`emcc` 6.x tested). On macOS: `brew install emscripten`. Otherwise follow the [emsdk install docs](https://emscripten.org/docs/getting_started/downloads.html).
- After cloning xdelta-wasm, initialize the jmacd/xdelta submodule:
```bash
git submodule update --init
```
This populates `native/xdelta`.
---
## One-time setup (XZ / liblzma)
Secondary LZMA compression (`xdelta3 -S lzma`) needs static liblzma. Run this if `native/xz/` is missing:
```bash
./native/build-xz.sh
```
That downloads XZ Utils and builds it with `emconfigure` / `emmake`.
---
## Building
From the xdelta-wasm checkout root:
```bash
./native/build.sh
```
This compiles `native/xdelta/xdelta3/xdelta3.c` and `native/xdelta3-wasm.c`, links liblzma, and writes:
- `public/xdelta3.js` (ES6 module)
- `public/xdelta3.wasm` (Companion WASM binary)
---
## Vendoring into Hackdex
Copy **only** those two files into this repo (overwrite existing):
```bash
cp public/xdelta3.js public/xdelta3.wasm \
/path/to/hackdex-website/public/xdelta/
```
Do **not** overwrite these Hackdex-owned files in `public/xdelta/`:
- `xdelta3.worker.js`: Hackdex worker (protocol differs from upstream)
- `LICENSE-xdelta3.txt`
- `NOTICE.txt`
---
## Licensing
See `public/xdelta/LICENSE-xdelta3.txt` and `public/xdelta/NOTICE.txt`.

View File

@@ -0,0 +1,176 @@
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

17
public/xdelta/NOTICE.txt Normal file
View File

@@ -0,0 +1,17 @@
xdelta3.wasm and xdelta3.js
===========================
These artifacts are built from xdelta3
(https://github.com/jmacd/xdelta), Copyright Joshua MacDonald,
licensed under the Apache License, Version 2.0. See LICENSE-xdelta3.txt.
They include glue code from the Hackdex fork of xdelta-wasm
(https://github.com/Hackdex-App/xdelta-wasm), forked from
kotcrab/xdelta-wasm (https://github.com/kotcrab/xdelta-wasm), also
licensed under Apache-2.0. That glue code has been modified for
Hackdex (encoder support and checksum-presence reporting). Per
Apache-2.0 section 4(b), this NOTICE states that modifications were
made.
The build statically links liblzma from XZ Utils
(https://tukaani.org/xz/), which is 0BSD / public domain.

2
public/xdelta/xdelta3.js Normal file

File diff suppressed because one or more lines are too long

BIN
public/xdelta/xdelta3.wasm Executable file

Binary file not shown.

View File

@@ -0,0 +1,133 @@
import createXdelta3Module from './xdelta3.js'
const bufferSize = 4 * 1024 * 1024
const cacheSize = 32
const PROGRESS_INTERVAL = 8 * 1024 * 1024
let module = undefined
const state = {
sourceFile: undefined,
inputFile: undefined,
errorMessage: undefined,
hasChecksums: null,
discardOutput: false,
bytesOut: 0,
bytesIn: 0,
lastProgressAt: 0,
}
// eslint-disable-next-line no-undef
const reader = new FileReaderSync()
function readSource(buffer, offset, size) {
return readFile(state.sourceFile, buffer, Number(offset), size)
}
function readInput(buffer, offset, size) {
const read = readFile(state.inputFile, buffer, Number(offset), size)
state.bytesIn += read
return read
}
function reportChecksums(hasChecksums) {
state.hasChecksums = hasChecksums ? true : false
}
function readFile(file, buffer, offset, size) {
const end = Math.min(file.size, offset + size)
const blob = file.slice(offset, end)
const read = end - offset
const data = reader.readAsArrayBuffer(blob)
module.HEAP8.set(new Uint8Array(data), buffer)
return read
}
function maybeProgress() {
if (state.bytesOut - state.lastProgressAt >= PROGRESS_INTERVAL) {
postMessage({
type: 'progress',
bytesOut: state.bytesOut,
bytesIn: state.bytesIn,
})
state.lastProgressAt = state.bytesOut
}
}
function outputFile(buffer, size) {
state.bytesOut += size
if (!state.discardOutput) {
const dataView = new Uint8Array(module.HEAP8.buffer, buffer, size)
const data = new Uint8Array(dataView)
postMessage({ type: 'chunk', bytes: data }, [data.buffer])
}
maybeProgress()
}
function reportError(msgPtr) {
state.errorMessage = module.UTF8ToString(msgPtr)
}
function postDone(ok, errorCode) {
const msg = {
type: 'done',
ok,
hasChecksums: state.hasChecksums,
}
if (errorCode !== undefined) {
msg.errorCode = errorCode
}
if (state.errorMessage) {
msg.errorMessage = state.errorMessage
}
postMessage(msg)
}
onmessage = async function (event) {
if (!event.data) {
return
}
const { command, mode, sourceFile, inputFile, disableChecksum, discardOutput } = event.data
if (command !== 'start') {
return
}
state.sourceFile = sourceFile
state.inputFile = inputFile
state.errorMessage = undefined
state.hasChecksums = null
state.discardOutput = !!discardOutput
state.bytesOut = 0
state.bytesIn = 0
state.lastProgressAt = 0
try {
module = await createXdelta3Module()
module.readInput = readInput
module.readSource = readSource
module.outputFile = outputFile
module.reportError = reportError
module.reportChecksums = reportChecksums
const result = module.callMain([
mode,
bufferSize.toString(),
cacheSize.toString(),
(!!disableChecksum).toString(),
// Known source size lets the encoder search the whole source for matches.
sourceFile.size.toString(),
])
if (result !== 0) {
postDone(false, result)
} else {
postDone(true)
}
} catch (e) {
console.error(e)
if (!state.errorMessage && e && typeof e.message === 'string') {
state.errorMessage = e.message
}
postDone(false)
}
module = undefined
}

View File

@@ -79,14 +79,12 @@ Only the original creator or a member of their team can submit the hack to Hackd
Account creation is required for submissions to preserve author control and attribution. This ensures your work is properly credited and you maintain control over your hack's listing. This also allows you to update your hack after submission.
### What format should I submit my hack in?
We only accept BPS patch files, not complete ROMs. Hackdex utilizes a built-in patcher that users apply to their own legally obtained base ROMs. This helps keep the platform safer from potential legal issues.
We accept `.bps` and `.xdelta` patch files, not complete ROMs. Hackdex utilizes a built-in patcher that users apply to their own legally obtained base ROMs. This helps keep the platform safer from potential legal issues. xdelta is the preferred format going forward; legacy BPS patches continue to work.
A built-in patcher is also included in the submission form, so you also have the option to provide your modified ROM and the base ROM to generate the patch file automatically.
A built-in patcher is also included in the submission form, so you also have the option to provide your modified ROM and the base ROM to generate a `.xdelta` patch file automatically.
### Why only BPS patch files?
The BPS format is the successor to the IPS and UPS formats, with the added benefit of including hash checksums for verification. This helps ensure that the patch file is linked to the correct base ROM. An incorrect base ROM will result in a corrupted game.
There are also plans to add Xdelta support for NDS hacks in the future.
### Why only BPS and Xdelta patch files?
Both formats support checksum verification so the patch is linked to the correct base ROM. An incorrect base ROM will result in a corrupted game. BPS remains supported for existing hacks; new in-browser patch creation produces Xdelta files, which is the preferred format going forward.
### How does my hack gain visibility?
We highly recommend linking to your romhack's Hackdex page from PokéCommunity, Reddit, or other social media platforms. Doing so can help boost your hack's visibility and outrank those sketchy ROM sharing sites that steal many creators' hard work.

View File

@@ -229,12 +229,21 @@ export async function getHackDownloads(slug: string): Promise<number | null> {
return runner();
}
type GetSignedPatchUrlResult = {
ok: true;
url: string;
format: Database["public"]["Enums"]["Patch Format"];
} | {
ok: false;
error: string;
};
export async function getSignedPatchUrl(
slug: string,
options?: {
patchId?: number;
}
): Promise<{ ok: true; url: string } | { ok: false; error: string }> {
): Promise<GetSignedPatchUrlResult> {
const supabase = await createClient();
// Get user for permission check
@@ -282,7 +291,7 @@ export async function getSignedPatchUrl(
// Fetch patch info
const { data: patch, error: patchError } = await supabase
.from("patches")
.select("id, bucket, filename, parent_hack, published, archived")
.select("id, bucket, filename, parent_hack, published, archived, format")
.eq("id", selectedPatchId)
.maybeSingle();
@@ -297,12 +306,12 @@ export async function getSignedPatchUrl(
try {
const workerUrl = buildPatchDownloadUrl(patch.filename);
if (workerUrl) {
return { ok: true, url: workerUrl };
return { ok: true, url: workerUrl, format: patch.format };
}
const client = getMinioClient();
const bucket = patch.bucket || PATCHES_BUCKET;
const signedUrl = await client.presignedGetObject(bucket, patch.filename, 60 * 5);
return { ok: true, url: signedUrl };
return { ok: true, url: signedUrl, format: patch.format };
} catch (error) {
console.error("Error signing patch URL:", error);
return { ok: false, error: "Failed to generate download URL" };
@@ -1010,11 +1019,12 @@ export async function confirmReuploadPatchVersion(
return { ok: false, error: "Patch not found" };
}
// Update patch filename
// Update patch filename and format (derived from object key extension)
const format = objectKey.toLowerCase().endsWith(".xdelta") ? "xdelta" : "bps";
const serviceClient = await createServiceClient();
const { error: updateErr } = await serviceClient
.from("patches")
.update({ filename: objectKey, updated_at: new Date().toISOString() })
.update({ filename: objectKey, format, updated_at: new Date().toISOString() })
.eq("id", patchId);
if (updateErr) return { ok: false, error: updateErr.message };

View File

@@ -598,7 +598,7 @@ export default async function HackDetail({ params }: HackDetailProps) {
using our built-in patcher.
</p>
<p className="mt-2">
By pressing "Agree and Patch", your browser will download and apply the <span className="font-semibold">{hack.title}</span> .bps patch file to your legally-obtained <span className="font-semibold">{baseRom?.name}</span> ROM. The patched ROM will then be automatically downloaded.
By pressing "Agree and Patch", your browser will download and apply the <span className="font-semibold">{hack.title}</span> patch file to your legally-obtained <span className="font-semibold">{baseRom?.name}</span> ROM. The patched ROM will then be automatically downloaded.
</p>
<p className="mt-2">
No pre-patched ROMs or base ROMs are hosted or distributed on this site. All patching is done locally on your device.

View File

@@ -3,7 +3,7 @@ import { createClient } from "@/utils/supabase/server";
import { canEditAsCreator, canEditAsAdmin } from "@/utils/hack";
import VersionList from "@/components/Hack/VersionList";
import DownloadPermissionSettings from "@/components/Hack/DownloadPermissionSettings";
import PatcherVersionManager from "@/components/Hack/PatcherVersionManager";
import PatcherVersionManager, { type Patch } from "@/components/Hack/PatcherVersionManager";
import CollapsibleCard from "@/components/Primitives/CollapsibleCard";
import Link from "next/link";
import { FaChevronLeft, FaPlus, FaStar } from "react-icons/fa6";
@@ -33,7 +33,7 @@ export default async function VersionsPage({ params }: VersionsPageProps) {
// Fetch all published, non-archived patches
const { data: patches } = await supabase
.from("patches")
.select("id, version, created_at, updated_at, changelog, published, archived")
.select("id, version, created_at, updated_at, changelog, published, archived, format")
.eq("parent_hack", slug)
.eq("published", true)
.eq("archived", false)
@@ -44,7 +44,7 @@ export default async function VersionsPage({ params }: VersionsPageProps) {
if (canEdit) {
const { data: unpub } = await supabase
.from("patches")
.select("id, version, created_at, updated_at, changelog, published, archived")
.select("id, version, created_at, updated_at, changelog, published, archived, format")
.eq("parent_hack", slug)
.eq("published", false)
.eq("archived", false)
@@ -52,7 +52,7 @@ export default async function VersionsPage({ params }: VersionsPageProps) {
unpublishedPatches = unpub || [];
}
const allPatches = [...(patches || []), ...unpublishedPatches].sort((a, b) =>
const allPatches: Patch[] = [...(patches || []), ...unpublishedPatches].sort((a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
);
const patcherSelection = await getPatcherSelectablePatches(supabase, slug, hack.current_patch);

View File

@@ -8,9 +8,14 @@ import { APIEmbed } from "discord-api-types/v10";
import { slugify } from "@/utils/format";
import { checkEditPermission, checkPatchEditPermission } from "@/utils/hack";
import { getCachedTagsWithUsage, resolveTagIdsInOrder } from "@/data/tags";
import type { PatchFormat } from "@/utils/patching";
type HackInsert = TablesInsert<"hacks">;
function patchFormatFromObjectKey(objectKey: string): PatchFormat {
return objectKey.toLowerCase().endsWith(".xdelta") ? "xdelta" : "bps";
}
async function ensureUniqueSlug(base: string, supabase: Awaited<ReturnType<typeof createClient>>) {
let candidate = base;
let suffix = 2;
@@ -173,8 +178,7 @@ export async function presignPatchAndSaveCovers(args: {
slug: string;
version: string;
coverUrls: string[];
// desired object key; if omitted we build from slug+version
objectKey?: string;
objectKey: string;
}) {
const supabase = await createClient();
const {
@@ -207,15 +211,11 @@ export async function presignPatchAndSaveCovers(args: {
const { error: cErr } = await supabase.from("hack_covers").insert(rows);
if (cErr) return { ok: false, error: cErr.message } as const;
}
const safeVersion = args.version.replace(/[^a-zA-Z0-9._-]+/g, "-");
const objectKey = args.objectKey || `${args.slug}-${safeVersion}.bps`;
const client = getMinioClient();
// 10 minutes to upload
const url = await client.presignedPutObject(PATCHES_BUCKET, objectKey, 60 * 10);
const url = await client.presignedPutObject(PATCHES_BUCKET, args.objectKey, 60 * 10);
return { ok: true, presignedUrl: url, objectKey } as const;
return { ok: true, presignedUrl: url, objectKey: args.objectKey } as const;
}
export async function confirmPatchUpload(args: { slug: string; objectKey: string; version: string, firstUpload?: boolean; publishAutomatically?: boolean }) {
@@ -268,6 +268,7 @@ export async function confirmPatchUpload(args: { slug: string; objectKey: string
filename: args.objectKey,
version: args.version,
parent_hack: args.slug,
format: patchFormatFromObjectKey(args.objectKey),
};
// Set published status based on publishAutomatically flag

View File

@@ -5,8 +5,6 @@ import StickyActionBar from "@/components/Hack/StickyActionBar";
import BaseRomErrorModal, { type BaseRomErrorModalState } from "@/components/Hack/BaseRomErrorModal";
import { useBaseRoms } from "@/contexts/BaseRomContext";
import { baseRoms } from "@/data/baseRoms";
import BinFile from "rom-patcher-js/rom-patcher-js/modules/BinFile.js";
import BPS from "rom-patcher-js/rom-patcher-js/modules/RomPatcher.format.bps.js";
import type { DownloadEventDetail } from "@/types/util";
import { getSignedPatchUrl, updatePatchDownloadCount } from "@/app/hack/[slug]/actions";
import { sha1Hex } from "@/utils/hash";
@@ -16,6 +14,8 @@ import {
isAnyRomExtension,
} from "@/utils/romFile";
import type { SelectablePatch } from "@/types/patcher";
import { applyPatch, patchFormatFromFilename, type PatchFormat } from "@/utils/patching";
import { createOutputSink, SaveCancelledError, type OutputSink } from "@/utils/patching/save";
interface HackActionsProps {
title: string;
@@ -46,9 +46,11 @@ const HackActions: React.FC<HackActionsProps> = ({
const { isLinked, hasPermission, hasCached, importUploadedBlob, ensurePermission, linkRom, getFileBlob, supported } = useBaseRoms();
const [file, setFile] = React.useState<File | null>(null);
const [status, setStatus] = React.useState<"idle" | "ready" | "patching" | "done" | "downloading">("idle");
const [patchProgress, setPatchProgress] = React.useState<number | null>(null);
const [error, setError] = React.useState<string | null>(null);
const [patchBlob, setPatchBlob] = React.useState<Blob | null>(null);
const [patchUrl, setPatchUrl] = React.useState<string | null>(null);
const [patchFormat, setPatchFormat] = React.useState<PatchFormat | null>(null);
const [termsAgreed, setTermsAgreed] = React.useState(false);
const [romErrorModal, setRomErrorModal] = React.useState<BaseRomErrorModalState | null>(null);
const [isVerifyingRom, setIsVerifyingRom] = React.useState(false);
@@ -79,6 +81,7 @@ const HackActions: React.FC<HackActionsProps> = ({
setTermsAgreed(false);
setPatchUrl(null);
setPatchBlob(null);
setPatchFormat(null);
setStatus("idle");
}
@@ -126,19 +129,6 @@ const HackActions: React.FC<HackActionsProps> = ({
}
}, [error]);
// When patch URL is fetched and terms are agreed, automatically proceed with patching if ROM is ready
React.useEffect(() => {
if (termsAgreed && patchUrl && patchBlob && status === "idle") {
const romReady = isRomReadyForPatch();
if (romReady) {
const timeoutId = setTimeout(() => {
onPatch();
}, 0);
return () => clearTimeout(timeoutId);
}
}
}, [termsAgreed, patchUrl, patchBlob, file, baseRomId, isLinked, hasPermission, hasCached, status]);
async function onSelectFile(e: React.ChangeEvent<HTMLInputElement>) {
const f = e.target.files?.[0] ?? null;
setFile(null);
@@ -216,7 +206,7 @@ const HackActions: React.FC<HackActionsProps> = ({
}
}
async function onAgreeToTerms(): Promise<{ url: string; blob: Blob } | null> {
async function onAgreeToTerms(): Promise<{ url: string; blob: Blob; format: PatchFormat } | null> {
try {
setError(null);
setStatus("downloading");
@@ -232,6 +222,7 @@ const HackActions: React.FC<HackActionsProps> = ({
}
setPatchUrl(result.url);
setPatchFormat(result.format);
setTermsAgreed(true);
const res = await fetch(result.url);
@@ -244,7 +235,7 @@ const HackActions: React.FC<HackActionsProps> = ({
setStatus("idle");
}
return { url: result.url, blob };
return { url: result.url, blob, format: result.format };
} catch (e: any) {
setError(e?.message || "Failed to fetch patch URL");
setStatus("idle");
@@ -254,20 +245,63 @@ const HackActions: React.FC<HackActionsProps> = ({
}
async function onPatch() {
let outputSink: OutputSink | null = null;
const discardSink = async () => {
if (!outputSink) return;
const sink = outputSink;
outputSink = null;
try {
await sink.abort();
} catch {
// ignore abort failures when discarding an unused sink
}
};
try {
setError(null);
// Create xdelta sink during the click gesture, before any other awaits that
// would drop transient user activation (terms download, ROM permission, etc.).
const outExt = platform ? platform.toLowerCase() : "bin";
const outputName = `${title} (${selectedVersion}).${outExt}`;
const earlyFormat = patchFormat ?? patchFormatFromFilename(selectedFilename);
if (earlyFormat === "xdelta" && status !== "patching") {
try {
outputSink = await createOutputSink(outputName);
} catch (e: unknown) {
if (e instanceof SaveCancelledError) {
setStatus("idle");
setPatchProgress(null);
return;
}
throw e;
}
}
let url = patchUrl;
let blob = patchBlob;
let format = patchFormat;
if (!termsAgreed || !url || !blob) {
if (!termsAgreed || !url || !blob || !format) {
const downloaded = await onAgreeToTerms();
if (!downloaded) return;
if (!downloaded) {
await discardSink();
return;
}
url = downloaded.url;
blob = downloaded.blob;
format = downloaded.format;
const romReady = isRomReadyForPatch();
if (!romReady) return;
if (!romReady) {
await discardSink();
return;
}
}
// BPS uses rom-patcher save; drop any unused early sink.
if (format !== "xdelta") {
await discardSink();
}
if (status === "patching") {
@@ -276,39 +310,56 @@ const HackActions: React.FC<HackActionsProps> = ({
let baseFile = file;
if (!baseFile) {
if (!isLinked(baseRomId) && !hasCached(baseRomId)) return;
if (!isLinked(baseRomId) && !hasCached(baseRomId)) {
await discardSink();
return;
}
if (!hasCached(baseRomId)) {
const perm = await ensurePermission(baseRomId, true);
if (perm !== "granted") return;
if (perm !== "granted") {
await discardSink();
return;
}
}
const linkedFile = await getFileBlob(baseRomId);
if (!linkedFile) return;
if (!linkedFile) {
await discardSink();
return;
}
baseFile = linkedFile;
}
setStatus("patching");
setPatchProgress(null);
await Promise.all([
new Promise((r) => setTimeout(r, 1000)),
(async () => {
const [romBuf, patchBuf] = await Promise.all([
baseFile.arrayBuffer(),
blob.arrayBuffer(),
]);
const romBin = new BinFile(romBuf);
romBin.fileName = baseFile.name + (platform ? `.${platform.toLowerCase()}` : "");
const patchBin = new BinFile(patchBuf);
const patch = BPS.fromFile(patchBin);
const patchedRom = patch.apply(romBin);
const outExt = platform ? platform.toLowerCase() : 'bin';
const outputName = `${title} (${selectedVersion}).${outExt}`;
patchedRom.fileName = outputName;
patchedRom.save();
})(),
]);
try {
await Promise.all([
new Promise((r) => setTimeout(r, 1000)),
(async () => {
// BPS ignores outputSink; xdelta uses the gesture-created sink.
const sink = outputSink;
outputSink = null;
await applyPatch({
format,
baseFile,
patchBlob: blob,
outputName,
sourceName: baseFile.name + (platform ? `.${platform.toLowerCase()}` : ""),
outputSink: sink ?? undefined,
onProgress: ({ bytesOut }) => setPatchProgress(bytesOut),
});
})(),
]);
} catch (e: unknown) {
if (e instanceof SaveCancelledError) {
setStatus("idle");
setPatchProgress(null);
return;
}
throw e;
} finally {
setPatchProgress(null);
}
setStatus("done");
@@ -337,8 +388,10 @@ const HackActions: React.FC<HackActionsProps> = ({
console.error(e);
}
} catch (e: any) {
await discardSink();
setError(e?.message || "Failed to patch ROM");
setStatus("idle");
setPatchProgress(null);
console.error(e);
}
}
@@ -365,6 +418,7 @@ const HackActions: React.FC<HackActionsProps> = ({
onUploadChange={onSelectFile}
termsAgreed={termsAgreed}
isVerifyingRom={isVerifyingRom}
patchProgress={patchProgress}
/>
{romErrorModal && (
<BaseRomErrorModal

View File

@@ -1,7 +1,6 @@
"use client";
import React from "react";
import { createClient } from "@/utils/supabase/client";
import { useBaseRoms } from "@/contexts/BaseRomContext";
import { baseRoms } from "@/data/baseRoms";
import { platformAccept } from "@/utils/idb";
@@ -11,6 +10,8 @@ import BPS from "rom-patcher-js/rom-patcher-js/modules/RomPatcher.format.bps.js"
import { presignNewPatchVersion } from "@/app/hack/actions";
import { confirmPatchUpload } from "@/app/submit/actions";
import { FaInfoCircle } from "react-icons/fa";
import { patchFormatFromFilename } from "@/utils/patching";
import { encodeXdelta, trialDecodeXdelta, friendlyXdeltaError } from "@/utils/patching/xdelta";
export interface HackPatchFormProps {
slug: string;
@@ -22,12 +23,14 @@ export interface HackPatchFormProps {
}
export default function HackPatchForm(props: HackPatchFormProps) {
const { slug, baseRomId, existingVersions, isCustomPatcherActive, customVersionName, currentVersion } = props;
const { slug, baseRomId, existingVersions, isCustomPatcherActive, currentVersion } = props;
const [version, setVersion] = React.useState("");
const [patchMode, setPatchMode] = React.useState<"bps" | "rom">("bps");
const [patchFile, setPatchFile] = React.useState<File | null>(null);
const [genStatus, setGenStatus] = React.useState<"idle" | "generating" | "ready" | "error">("idle");
const [genError, setGenError] = React.useState<string>("");
const [checksumStatus, setChecksumStatus] = React.useState<"idle" | "validating" | "valid" | "invalid" | "unknown">("idle");
const [checksumError, setChecksumError] = React.useState<string>("");
const [submitting, setSubmitting] = React.useState(false);
const [error, setError] = React.useState<string>("");
const [publishAutomatically, setPublishAutomatically] = React.useState(false);
@@ -36,7 +39,6 @@ export default function HackPatchForm(props: HackPatchFormProps) {
const patchInputRef = React.useRef<HTMLInputElement | null>(null);
const modifiedRomInputRef = React.useRef<HTMLInputElement | null>(null);
const supabase = createClient();
const baseRomEntry = React.useMemo(() => baseRoms.find(r => r.id === baseRomId) || null, [baseRomId]);
const baseRomPlatform = baseRomEntry?.platform;
const baseRomName = baseRomEntry?.name;
@@ -48,8 +50,13 @@ export default function HackPatchForm(props: HackPatchFormProps) {
const isVersionTaken = version.trim() && existingVersions.includes(version.trim());
const canSubmit = React.useMemo(() => {
return !!version.trim() && ((!!patchFile && patchMode === "bps") || (patchMode === "rom" && genStatus === "ready")) && !isVersionTaken && !submitting;
}, [version, patchFile, patchMode, genStatus, isVersionTaken, submitting]);
return !!version.trim()
&& ((!!patchFile && patchMode === "bps") || (patchMode === "rom" && genStatus === "ready"))
&& !isVersionTaken
&& !submitting
&& checksumStatus !== "invalid"
&& checksumStatus !== "validating";
}, [version, patchFile, patchMode, genStatus, isVersionTaken, submitting, checksumStatus]);
React.useEffect(() => {
versionInputRef.current?.focus();
@@ -76,6 +83,8 @@ export default function HackPatchForm(props: HackPatchFormProps) {
setPatchFile(null);
setGenStatus("idle");
setGenError("");
setChecksumStatus("idle");
setChecksumError("");
patchInputRef.current && (patchInputRef.current.value = "");
modifiedRomInputRef.current && (modifiedRomInputRef.current.value = "");
}, [patchMode]);
@@ -127,14 +136,14 @@ export default function HackPatchForm(props: HackPatchFormProps) {
return;
}
}
const [origBuf, modBuf] = await Promise.all([baseFile.arrayBuffer(), mod.arrayBuffer()]);
const origBin = new BinFile(origBuf);
const modBin = new BinFile(modBuf);
const deltaMode = origBin.fileSize <= 4194304;
const patch = BPS.buildFromRoms(origBin, modBin, deltaMode);
const fname = `${slug}-${(version || "patch").replace(/[^a-zA-Z0-9._-]+/g, "-")}`;
const patchBin = patch.export(fname);
const out = new File([patchBin._u8array], `${fname}.bps`, { type: 'application/octet-stream' });
const { result, patch } = await encodeXdelta({ sourceFile: baseFile, targetFile: mod });
if (!result.ok || !patch) {
setGenStatus("error");
setGenError(friendlyXdeltaError(result));
return;
}
const out = new File([patch], `${fname}.xdelta`, { type: 'application/octet-stream' });
setPatchFile(out);
setGenStatus("ready");
} catch (err: any) {
@@ -143,12 +152,93 @@ export default function HackPatchForm(props: HackPatchFormProps) {
}
}
async function onUploadPatch(e: React.ChangeEvent<HTMLInputElement>) {
try {
setChecksumStatus("validating");
setChecksumError("");
const patch = e.target.files?.[0] || null;
if (!patch) {
setChecksumStatus("idle");
setChecksumError("");
setPatchFile(null);
return;
}
if (patchFormatFromFilename(patch.name) === "xdelta") {
const baseFile = baseRomId ? await getFileBlob(baseRomId) : null;
if (!baseFile) {
setChecksumStatus("unknown");
setChecksumError("Cannot validate without the base ROM on this device. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
const result = await trialDecodeXdelta({ sourceFile: baseFile, patchBlob: patch });
if (result.ok && result.hasChecksums === true) {
setChecksumStatus("valid");
setChecksumError("");
setPatchFile(patch);
return;
}
if (!result.ok) {
const msg = (result.errorMessage ?? "").toLowerCase();
setChecksumStatus("invalid");
setChecksumError(
msg.includes("checksum")
? "Checksum validation failed. The patch file is not compatible with the selected base ROM."
: friendlyXdeltaError(result)
);
setPatchFile(null);
return;
}
setChecksumStatus("unknown");
setChecksumError("This patch has no embedded checksums. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
if (!baseRomEntry) {
setChecksumStatus("unknown");
setChecksumError("A checksum is not available to validate this patch file. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
const bps = BPS.fromFile(new BinFile(await patch.arrayBuffer()));
if (bps.sourceChecksum === 0 || bps.sourceChecksum === undefined) {
setChecksumStatus("unknown");
setChecksumError("A checksum is not available to validate this patch file. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
const baseRomChecksum = parseInt(baseRomEntry.crc32, 16);
if (bps.sourceChecksum !== baseRomChecksum) {
setChecksumStatus("invalid");
setChecksumError("Checksum validation failed. The patch file is not compatible with the selected base ROM.");
setPatchFile(null);
return;
}
setChecksumStatus("valid");
setChecksumError("");
setPatchFile(patch);
} catch (err: any) {
setChecksumStatus("unknown");
setChecksumError(err?.message || "Failed to validate patch file.");
setPatchFile(e.target.files?.[0] || null);
}
}
const onSubmit = async () => {
if (!canSubmit) return;
setSubmitting(true);
setError("");
try {
const presigned = await presignNewPatchVersion({ slug, version: version.trim() });
const safeVersion = version.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
const patchExt = patchFormatFromFilename(patchFile?.name) === "xdelta" ? "xdelta" : "bps";
const objectKey = `${slug}-${safeVersion}.${patchExt}`;
const presigned = await presignNewPatchVersion({ slug, version: version.trim(), objectKey });
if (!presigned.ok) throw new Error(presigned.error || 'Failed to presign');
await fetch(presigned.presignedUrl!, { method: 'PUT', body: patchFile!, headers: { 'Content-Type': 'application/octet-stream' } });
const finalized = await confirmPatchUpload({ slug, objectKey: presigned.objectKey!, version: version.trim(), publishAutomatically });
@@ -206,14 +296,14 @@ export default function HackPatchForm(props: HackPatchFormProps) {
onClick={() => setPatchMode("bps")}
className={`rounded-md rounded-r-none px-3 py-1.5 text-xs border-l-1 border-y-1 ${patchMode === "bps" ? "bg-[var(--surface-2)] border-[var(--border)]" : "text-foreground/70 border-[var(--border)]"}`}
>
Upload .bps
Upload .bps/.xdelta
</button>
<button
type="button"
onClick={() => setPatchMode("rom")}
className={`rounded-md rounded-l-none px-3 py-1.5 text-xs border-1 ${patchMode === "rom" ? "bg-[var(--surface-2)] border-[var(--border)]" : "text-foreground/70 border-[var(--border)]"}`}
>
Upload modified ROM (auto-generate .bps)
Upload modified ROM (auto-generate .xdelta)
</button>
</div>
@@ -221,12 +311,16 @@ export default function HackPatchForm(props: HackPatchFormProps) {
<div className="grid gap-2">
<input
ref={patchInputRef}
onChange={(e) => setPatchFile(e.target.files?.[0] || null)}
onChange={onUploadPatch}
type="file"
accept=".bps"
accept=".bps,.xdelta"
className="rounded-md bg-[var(--surface-2)] px-3 py-2 text-sm italic text-foreground/50 ring-1 ring-inset ring-[var(--border)] file:bg-black/10 dark:file:bg-[var(--surface-2)] file:text-foreground/80 file:text-sm file:font-medium file:not-italic file:rounded-md file:border-0 file:px-3 file:py-2 file:mr-2 file:cursor-pointer"
/>
<p className="text-xs text-foreground/60">Upload a BPS patch file.</p>
<p className="text-xs text-foreground/60">Upload a .bps or .xdelta patch file.</p>
{checksumStatus === "validating" && <div className="text-xs text-foreground/70">Validating checksum</div>}
{checksumStatus === "valid" && <div className="text-xs text-emerald-400/90">Checksum valid.</div>}
{checksumStatus === "invalid" && !!checksumError && <div className="text-xs text-red-400">{checksumError}</div>}
{checksumStatus === "unknown" && !!checksumError && <div className="text-xs text-amber-400/90">{checksumError}</div>}
</div>
)}
@@ -262,7 +356,7 @@ export default function HackPatchForm(props: HackPatchFormProps) {
onChange={onUploadModifiedRom}
className="rounded-md bg-[var(--surface-2)] px-3 py-2 text-sm ring-1 ring-inset ring-[var(--border)] disabled:opacity-50 disabled:cursor-not-allowed"
/>
<p className="text-xs text-foreground/60">We'll generate a .bps patch on-device. No ROMs are uploaded.</p>
<p className="text-xs text-foreground/60">We'll generate a .xdelta patch on-device. No ROMs are uploaded.</p>
{genStatus === "generating" && <div className="text-xs text-foreground/70">Generating patch…</div>}
{genStatus === "ready" && patchFile && <div className="text-xs text-emerald-400/90">Patch ready: {patchFile.name}</div>}
{genStatus === "error" && !!genError && <div className="text-xs text-red-400">{genError}</div>}
@@ -315,5 +409,3 @@ export default function HackPatchForm(props: HackPatchFormProps) {
</div>
);
}

View File

@@ -25,6 +25,8 @@ import BPS from "rom-patcher-js/rom-patcher-js/modules/RomPatcher.format.bps.js"
import { sha1Hex } from "@/utils/hash";
import { platformAccept, setDraftCovers, getDraftCovers, deleteDraftCovers } from "@/utils/idb";
import { slugify, sortOrderedTags } from "@/utils/format";
import { patchFormatFromFilename } from "@/utils/patching";
import { encodeXdelta, trialDecodeXdelta, friendlyXdeltaError } from "@/utils/patching/xdelta";
import type { CatalogTagRow } from "@/types/catalogTag";
import { HACK_FORM_DESCRIPTION_PLACEHOLDER } from "./hackFormConstants";
@@ -179,6 +181,8 @@ export default function HackSubmitForm({
setPatchFile(null);
setGenStatus("idle");
setGenError("");
setChecksumStatus("idle");
setChecksumError("");
patchInputRef.current && (patchInputRef.current.value = "");
modifiedRomInputRef.current && (modifiedRomInputRef.current.value = "");
}, [patchMode]);
@@ -431,7 +435,7 @@ export default function HackSubmitForm({
const step1Valid = !!title.trim() && !!platform && !!baseRom.trim() && !!language.trim() && !!completionStatus.trim() && (isArchive ? !!originalAuthor.trim() : true);
const step2Valid = (isArchive ? true : !!version.trim()) && !!summary.trim() && !summaryTooLong && !!description.trim() && tags.length > 0;
const step3Valid = (newCoverFiles.length > 0) && !overLimit && coverErrors.length === 0 && (!boxArt.trim() || urlLike(boxArt)) && allSocialValid;
const isValid = step1Valid && step2Valid && step3Valid && (isArchive ? true : !!patchFile);
const isValid = step1Valid && step2Valid && step3Valid && (isArchive ? true : !!patchFile) && checksumStatus !== "invalid" && checksumStatus !== "validating";
const onSubmit = async () => {
if (!isValid || submitting) return;
@@ -484,7 +488,10 @@ export default function HackSubmitForm({
window.location.href = `/hack/${prepared.slug}`;
} else {
console.log('[HackSubmitForm] Getting patch upload URL...');
const presigned = await presignPatchAndSaveCovers({ slug: prepared.slug, version, coverUrls: uploadedCoverUrls });
const safeVersion = version.replace(/[^a-zA-Z0-9._-]+/g, "-");
const patchExt = patchFormatFromFilename(patchFile?.name) === "xdelta" ? "xdelta" : "bps";
const objectKey = `${prepared.slug}-${safeVersion}.${patchExt}`;
const presigned = await presignPatchAndSaveCovers({ slug: prepared.slug, version, coverUrls: uploadedCoverUrls, objectKey });
if (!presigned.ok) throw new Error(presigned.error || 'Failed to presign');
if (patchFile) {
@@ -567,14 +574,14 @@ export default function HackSubmitForm({
return;
}
}
const [origBuf, modBuf] = await Promise.all([baseFile.arrayBuffer(), mod.arrayBuffer()]);
const origBin = new BinFile(origBuf);
const modBin = new BinFile(modBuf);
const deltaMode = origBin.fileSize <= 4194304;
const patch = BPS.buildFromRoms(origBin, modBin, deltaMode);
const fileName = slug || title || "patch";
const patchBin = patch.export(fileName);
const out = new File([patchBin._u8array], `${fileName}.bps`, { type: 'application/octet-stream' });
const { result, patch } = await encodeXdelta({ sourceFile: baseFile, targetFile: mod });
if (!result.ok || !patch) {
setGenStatus("error");
setGenError(friendlyXdeltaError(result));
return;
}
const out = new File([patch], `${fileName}.xdelta`, { type: 'application/octet-stream' });
setPatchFile(out);
setGenStatus("ready");
} catch (err: any) {
@@ -596,9 +603,42 @@ export default function HackSubmitForm({
return;
}
if (patchFormatFromFilename(patch.name) === "xdelta") {
const baseFile = baseRom ? await getFileBlob(baseRom) : null;
if (!baseFile) {
setChecksumStatus("unknown");
setChecksumError("Cannot validate without the base ROM on this device. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
const result = await trialDecodeXdelta({ sourceFile: baseFile, patchBlob: patch });
if (result.ok && result.hasChecksums === true) {
setChecksumStatus("valid");
setChecksumError("");
setPatchFile(patch);
return;
}
if (!result.ok) {
const msg = (result.errorMessage ?? "").toLowerCase();
setChecksumStatus("invalid");
setChecksumError(
msg.includes("checksum")
? "Checksum validation failed. The patch file is not compatible with the selected base ROM."
: friendlyXdeltaError(result)
);
setPatchFile(null);
return;
}
setChecksumStatus("unknown");
setChecksumError("This patch has no embedded checksums. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
if (!baseRomEntry) {
setChecksumStatus("unknown");
setChecksumError("A checksum is not available to validate this patch file. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
@@ -607,6 +647,7 @@ export default function HackSubmitForm({
if (bps.sourceChecksum === 0 || bps.sourceChecksum === undefined) {
setChecksumStatus("unknown");
setChecksumError("A checksum is not available to validate this patch file. Proceed at your own risk, or upload your modified ROM instead.");
setPatchFile(patch);
return;
}
@@ -614,18 +655,19 @@ export default function HackSubmitForm({
if (bps.sourceChecksum !== baseRomChecksum) {
setChecksumStatus("invalid");
setChecksumError("Checksum validation failed. The patch file is not compatible with the selected base ROM.");
setPatchFile(null);
return;
}
// All checks passed, set the checksum status to valid
setChecksumStatus("valid");
setChecksumError("");
setPatchFile(patch);
}
catch (err: any) {
setChecksumStatus("unknown");
setChecksumError(err?.message || "Failed to validate patch file.");
setPatchFile(e.target.files?.[0] || null);
}
}
@@ -1205,14 +1247,14 @@ https://discord.gg/example`}
onClick={() => setPatchMode("bps")}
className={`rounded-md rounded-r-none px-3 py-1.5 text-xs border-l-1 border-y-1 ${patchMode === "bps" ? "bg-[var(--surface-2)] border-[var(--border)]" : "text-foreground/70 border-[var(--border)]"}`}
>
Upload .bps
Upload .bps/.xdelta
</button>
<button
type="button"
onClick={() => setPatchMode("rom")}
className={`rounded-md rounded-l-none px-3 py-1.5 text-xs border-1 ${patchMode === "rom" ? "bg-[var(--surface-2)] border-[var(--border)]" : "text-foreground/70 border-[var(--border)]"}`}
>
Upload modified ROM (auto-generate .bps)
Upload modified ROM (auto-generate .xdelta)
</button>
</div>
@@ -1222,10 +1264,10 @@ https://discord.gg/example`}
ref={patchInputRef}
onChange={onUploadPatch}
type="file"
accept=".bps"
accept=".bps,.xdelta"
className="rounded-md bg-[var(--surface-2)] px-3 py-2 text-sm italic text-foreground/50 ring-1 ring-inset ring-[var(--border)] file:bg-black/10 dark:file:bg-[var(--surface-2)] file:text-foreground/80 file:text-sm file:font-medium file:not-italic file:rounded-md file:border-0 file:px-3 file:py-2 file:mr-2 file:cursor-pointer"
/>
<p className="text-xs text-foreground/60">Upload a BPS patch file.</p>
<p className="text-xs text-foreground/60">Upload a .bps or .xdelta patch file.</p>
{checksumStatus === "validating" && <div className="text-xs text-foreground/70">Validating checksum…</div>}
{checksumStatus === "valid" && <div className="text-xs text-emerald-400/90">Checksum valid.</div>}
{checksumStatus === "invalid" && !!checksumError && <div className="text-xs text-red-400">{checksumError}</div>}
@@ -1265,7 +1307,7 @@ https://discord.gg/example`}
onChange={onUploadModifiedRom}
className="rounded-md bg-[var(--surface-2)] px-3 py-2 text-sm ring-1 ring-inset ring-[var(--border)] disabled:opacity-50 disabled:cursor-not-allowed"
/>
<p className="text-xs text-foreground/60">We'll generate a .bps patch on-device. No ROMs are uploaded.</p>
<p className="text-xs text-foreground/60">We'll generate a .xdelta patch on-device. No ROMs are uploaded.</p>
{genStatus === "generating" && <div className="text-xs text-foreground/70">Generating patch</div>}
{genStatus === "ready" && patchFile && <div className="text-xs text-emerald-400/90">Patch ready: {patchFile.name}</div>}
{genStatus === "error" && !!genError && <div className="text-xs text-red-400">{genError}</div>}

View File

@@ -8,10 +8,11 @@ import PatcherVersionSettings from "@/components/Hack/PatcherVersionSettings";
import VersionList from "@/components/Hack/VersionList";
import { CUSTOM_VERSION_NAME_MAX_LENGTH, suggestCustomVersionName } from "@/utils/patches/hack-display-version";
import type { PatchesDownloadPermission } from "@/components/Hack/DownloadPermissionSettings";
import type { PatchFormat } from "@/utils/patching";
type PatcherOption = "latest" | "custom";
interface Patch {
export interface Patch {
id: number;
version: string;
created_at: string;
@@ -19,6 +20,7 @@ interface Patch {
changelog: string | null;
published: boolean;
archived: boolean;
format: PatchFormat;
}
interface PatcherVersionManagerProps {

View File

@@ -27,6 +27,7 @@ interface StickyActionBarProps {
onUploadChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
termsAgreed: boolean;
isVerifyingRom?: boolean;
patchProgress?: number | null;
}
export default function StickyActionBar({
@@ -49,6 +50,7 @@ export default function StickyActionBar({
onUploadChange,
termsAgreed,
isVerifyingRom = false,
patchProgress = null,
}: StickyActionBarProps) {
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => setMounted(true), []);
@@ -159,7 +161,7 @@ export default function StickyActionBar({
? "bg-amber-600/60 text-white ring-amber-700/80 dark:bg-amber-500/50 dark:text-amber-100 dark:ring-amber-400/90"
: "bg-red-600/60 text-white ring-red-700/80 dark:bg-red-500/50 dark:text-red-100 dark:ring-red-400/90"
}`}>
{romReady ? (filename ?? ".bps file ready") : isLinked ? "Permission needed" : "Base ROM needed"}
{romReady ? (filename ?? "patch file ready") : isLinked ? "Permission needed" : "Base ROM needed"}
</span>
)}
{!baseRomsLoading && !romReady && !isLinked && (
@@ -207,7 +209,11 @@ export default function StickyActionBar({
className={`shine-wrap btn-premium data-[ready=false]:hidden! h-11 md:h-9 w-full md:min-w-46 ${!termsAgreed || status === 'downloading' ? "md:w-32" : "md:w-auto"} text-base md:text-sm font-semibold cursor-pointer disabled:cursor-not-allowed disabled:opacity-70 ${romReady && status !== 'downloading' && status !== 'ready' && termsAgreed ? "mt-6 md:mt-0" : ""}`}
>
<span>{
status === "patching" ? "Patching…" :
status === "patching" ? (
patchProgress != null && patchProgress > 0
? `Patching… (${(patchProgress / (1024 * 1024)).toFixed(0)} MB)`
: "Patching…"
) :
status === "downloading" ? "Downloading…" :
status === "done" ? (
patchAgainReady ? "Patch Again" : "Patched"

View File

@@ -26,6 +26,8 @@ import { sha1Hex } from "@/utils/hash";
import { baseRoms, type BaseRom } from "@/data/baseRoms";
import { platformAccept } from "@/utils/idb";
import { useBaseRoms } from "@/contexts/BaseRomContext";
import { patchFormatFromFilename } from "@/utils/patching";
import { encodeXdelta, trialDecodeXdelta, friendlyXdeltaError } from "@/utils/patching/xdelta";
interface Patch {
id: number;
@@ -116,6 +118,16 @@ export default function VersionActions({
}
}, [showDeleteModal, showRestoreModal, showRollbackModal, showPublishModal, showReuploadModal]);
useEffect(() => {
setReuploadFile(null);
setChecksumStatus("idle");
setChecksumError("");
setGenStatus("idle");
setGenError("");
if (patchInputRef.current) patchInputRef.current.value = "";
if (modifiedRomInputRef.current) modifiedRomInputRef.current.value = "";
}, [patchMode]);
const handleDownload = async () => {
try {
const result = await getPatchDownloadUrl(patch.id);
@@ -210,6 +222,38 @@ export default function VersionActions({
return;
}
if (patchFormatFromFilename(patchFile.name) === "xdelta") {
const baseFile = baseRom ? await getFileBlob(baseRom) : null;
if (!baseFile) {
setChecksumStatus("unknown");
setChecksumError("Cannot validate without the base ROM on this device. Proceed at your own risk, or upload your modified ROM instead.");
setReuploadFile(patchFile);
return;
}
const result = await trialDecodeXdelta({ sourceFile: baseFile, patchBlob: patchFile });
if (result.ok && result.hasChecksums === true) {
setChecksumStatus("valid");
setChecksumError("");
setReuploadFile(patchFile);
return;
}
if (!result.ok) {
const msg = (result.errorMessage ?? "").toLowerCase();
setChecksumStatus("invalid");
setChecksumError(
msg.includes("checksum")
? "Checksum validation failed. The patch file is not compatible with the selected base ROM."
: friendlyXdeltaError(result)
);
setReuploadFile(null);
return;
}
setChecksumStatus("unknown");
setChecksumError("This patch has no embedded checksums. Proceed at your own risk, or upload your modified ROM instead.");
setReuploadFile(patchFile);
return;
}
if (!baseRomEntry) {
setChecksumStatus("unknown");
setChecksumError("A checksum is not available to validate this patch file. Proceed at your own risk, or upload your modified ROM instead.");
@@ -241,7 +285,7 @@ export default function VersionActions({
} catch (err: any) {
setChecksumStatus("unknown");
setChecksumError(err?.message || "Failed to validate patch file.");
setReuploadFile(null);
setReuploadFile(e.target.files?.[0] || null);
}
}
@@ -303,14 +347,14 @@ export default function VersionActions({
}
}
const [origBuf, modBuf] = await Promise.all([baseFile.arrayBuffer(), mod.arrayBuffer()]);
const origBin = new BinFile(origBuf);
const modBin = new BinFile(modBuf);
const deltaMode = origBin.fileSize <= 4194304;
const patch = BPS.buildFromRoms(origBin, modBin, deltaMode);
const fileName = hackSlug || "patch";
const patchBin = patch.export(fileName);
const out = new File([patchBin._u8array], `${fileName}.bps`, { type: 'application/octet-stream' });
const { result, patch } = await encodeXdelta({ sourceFile: baseFile, targetFile: mod });
if (!result.ok || !patch) {
setGenStatus("error");
setGenError(friendlyXdeltaError(result));
return;
}
const out = new File([patch], `${fileName}.xdelta`, { type: 'application/octet-stream' });
setReuploadFile(out);
setGenStatus("ready");
} catch (err: any) {
@@ -329,7 +373,8 @@ export default function VersionActions({
setReuploadError(null);
try {
const safeVersion = patch.version.replace(/[^a-zA-Z0-9._-]+/g, "-");
const objectKey = `${hackSlug}-${safeVersion}-reupload-${Date.now()}.bps`;
const patchExt = patchFormatFromFilename(reuploadFile.name) === "xdelta" ? "xdelta" : "bps";
const objectKey = `${hackSlug}-${safeVersion}-reupload-${Date.now()}.${patchExt}`;
const presignResult = await reuploadPatchVersion(hackSlug, patch.id, objectKey);
if (!presignResult.ok) {
@@ -710,14 +755,14 @@ export default function VersionActions({
onClick={() => setPatchMode("bps")}
className={`rounded-md rounded-r-none px-3 py-1.5 text-xs border-l-1 border-y-1 ${patchMode === "bps" ? "bg-[var(--surface-2)] border-[var(--border)]" : "text-foreground/70 border-[var(--border)]"}`}
>
Upload .bps
Upload .bps/.xdelta
</button>
<button
type="button"
onClick={() => setPatchMode("rom")}
className={`rounded-md rounded-l-none px-3 py-1.5 text-xs border-1 ${patchMode === "rom" ? "bg-[var(--surface-2)] border-[var(--border)]" : "text-foreground/70 border-[var(--border)]"}`}
>
Upload modified ROM (auto-generate .bps)
Upload modified ROM (auto-generate .xdelta)
</button>
</div>
@@ -727,10 +772,10 @@ export default function VersionActions({
ref={patchInputRef}
onChange={onUploadPatch}
type="file"
accept=".bps"
accept=".bps,.xdelta"
className="rounded-md bg-[var(--surface-2)] px-3 py-2 text-sm italic text-foreground/50 ring-1 ring-inset ring-[var(--border)] file:bg-black/10 dark:file:bg-[var(--surface-2)] file:text-foreground/80 file:text-sm file:font-medium file:not-italic file:rounded-md file:border-0 file:px-3 file:py-2 file:mr-2 file:cursor-pointer"
/>
<p className="text-xs text-foreground/60">Upload a BPS patch file.</p>
<p className="text-xs text-foreground/60">Upload a .bps or .xdelta patch file.</p>
{checksumStatus === "validating" && <div className="text-xs text-foreground/70">Validating checksum</div>}
{checksumStatus === "valid" && <div className="text-xs text-emerald-400/90">Checksum valid.</div>}
{checksumStatus === "invalid" && !!checksumError && <div className="text-xs text-red-400">{checksumError}</div>}
@@ -776,7 +821,7 @@ export default function VersionActions({
onChange={onUploadModifiedRom}
className="rounded-md bg-[var(--surface-2)] px-3 py-2 text-sm ring-1 ring-inset ring-[var(--border)] disabled:opacity-50 disabled:cursor-not-allowed"
/>
<p className="text-xs text-foreground/60">We'll generate a .bps patch on-device. No ROMs are uploaded.</p>
<p className="text-xs text-foreground/60">We'll generate a .xdelta patch on-device. No ROMs are uploaded.</p>
{genStatus === "generating" && <div className="text-xs text-foreground/70">Generating patch</div>}
{genStatus === "ready" && reuploadFile && <div className="text-xs text-emerald-400/90">Patch ready: {reuploadFile.name}</div>}
{genStatus === "error" && !!genError && <div className="text-xs text-red-400">{genError}</div>}
@@ -791,7 +836,7 @@ export default function VersionActions({
<div className="flex gap-2">
<button
onClick={handleReupload}
disabled={actionLoading || !reuploadFile || checksumStatus === "invalid"}
disabled={actionLoading || !reuploadFile || checksumStatus === "invalid" || checksumStatus === "validating"}
className="flex-1 rounded-md bg-emerald-600 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
{actionLoading ? "Uploading..." : "Upload"}

View File

@@ -9,16 +9,7 @@ import type { PatchesDownloadPermission } from "@/components/Hack/DownloadPermis
import { updatePatchChangelog, updatePatchVersion, getPatchDownloadUrl, updatePatchDownloadCount } from "@/app/hack/[slug]/actions";
import { useRouter } from "next/navigation";
import { createClient } from "@/utils/supabase/client";
interface Patch {
id: number;
version: string;
created_at: string;
updated_at: string | null;
changelog: string | null;
published: boolean;
archived: boolean;
}
import type { Patch } from "@/components/Hack/PatcherVersionManager";
function shouldShowPublicPatchDownload(
permission: PatchesDownloadPermission,
@@ -277,6 +268,9 @@ export default function VersionList({
Archived
</span>
)}
<span className="inline-flex items-center rounded-full bg-gray-500/20 px-2 py-0.5 text-xs font-medium text-gray-600 dark:text-gray-400">
.{patch.format}
</span>
</div>
);

View File

@@ -390,6 +390,7 @@ export type Database = {
changelog: string | null
created_at: string
filename: string
format: Database["public"]["Enums"]["Patch Format"]
id: number
parent_hack: string | null
published: boolean
@@ -405,6 +406,7 @@ export type Database = {
changelog?: string | null
created_at?: string
filename: string
format?: Database["public"]["Enums"]["Patch Format"]
id?: number
parent_hack?: string | null
published?: boolean
@@ -420,6 +422,7 @@ export type Database = {
changelog?: string | null
created_at?: string
filename?: string
format?: Database["public"]["Enums"]["Patch Format"]
id?: number
parent_hack?: string | null
published?: boolean
@@ -522,6 +525,7 @@ export type Database = {
}
Enums: {
"Completion Status": "Complete" | "Demo" | "Alpha" | "Beta"
"Patch Format": "bps" | "xdelta"
"Patches Download Permission": "None" | "Current" | "All"
"Tag Categories":
| "Pokédex"
@@ -665,6 +669,7 @@ export const Constants = {
public: {
Enums: {
"Completion Status": ["Complete", "Demo", "Alpha", "Beta"],
"Patch Format": ["bps", "xdelta"],
"Patches Download Permission": ["None", "Current", "All"],
"Tag Categories": [
"Pokédex",

23
src/types/file-system-access.d.ts vendored Normal file
View File

@@ -0,0 +1,23 @@
/** Minimal File System Access API typings (not in TypeScript's default DOM lib). */
interface FileSystemWritableFileStream extends WritableStream {
write(data: BufferSource | Blob | string): Promise<void>;
close(): Promise<void>;
abort(): Promise<void>;
}
interface FileSystemFileHandle {
createWritable(options?: { keepExistingData?: boolean }): Promise<FileSystemWritableFileStream>;
}
interface SaveFilePickerOptions {
suggestedName?: string;
types?: Array<{
description?: string;
accept: Record<string, string[]>;
}>;
}
interface Window {
showSaveFilePicker?(options?: SaveFilePickerOptions): Promise<FileSystemFileHandle>;
}

View File

@@ -0,0 +1,76 @@
import BinFile from "rom-patcher-js/rom-patcher-js/modules/BinFile.js";
import BPS from "rom-patcher-js/rom-patcher-js/modules/RomPatcher.format.bps.js";
import { createOutputSink, SaveCancelledError, type OutputSink } from "@/utils/patching/save";
import { decodeXdelta, friendlyXdeltaError } from "@/utils/patching/xdelta";
import type { Database } from "@/types/db";
export type PatchFormat = Database["public"]["Enums"]["Patch Format"];
export function patchFormatFromFilename(filename: string | null | undefined): PatchFormat {
if (filename && filename.toLowerCase().endsWith(".xdelta")) {
return "xdelta";
}
return "bps";
}
export async function applyPatch(opts: {
format: PatchFormat;
baseFile: File;
patchBlob: Blob;
outputName: string;
sourceName?: string;
/** Pre-created sink (xdelta). Prefer creating during the user-gesture before other awaits. */
outputSink?: OutputSink;
onProgress?: (p: { bytesOut: number }) => void;
}): Promise<void> {
const { format, baseFile, patchBlob, outputName, sourceName, outputSink, onProgress } = opts;
if (format === "bps") {
const [romBuf, patchBuf] = await Promise.all([
baseFile.arrayBuffer(),
patchBlob.arrayBuffer(),
]);
const romBin = new BinFile(romBuf);
romBin.fileName = sourceName ?? baseFile.name;
const patchBin = new BinFile(patchBuf);
const patch = BPS.fromFile(patchBin);
const patchedRom = patch.apply(romBin);
patchedRom.fileName = outputName;
patchedRom.save();
return;
}
// format === "xdelta"
const sink = outputSink ?? await createOutputSink(outputName);
try {
const result = await decodeXdelta({
sourceFile: baseFile,
patchBlob,
onChunk: (bytes) => sink.write(bytes),
onProgress: onProgress
? (p) => {
onProgress({ bytesOut: p.bytesOut });
}
: undefined,
});
if (!result.ok) {
await sink.abort();
throw new Error(friendlyXdeltaError(result));
}
await sink.close();
} catch (error) {
if (error instanceof SaveCancelledError) {
throw error;
}
try {
await sink.abort();
} catch {
// ignore abort failures after a prior error
}
throw error;
}
}

View File

@@ -0,0 +1,92 @@
export class SaveCancelledError extends Error {
constructor(message = "Save cancelled") {
super(message);
this.name = "SaveCancelledError";
}
}
export type OutputSink = {
write(bytes: Uint8Array): Promise<void>;
close(): Promise<void>;
abort(): Promise<void>;
streaming: boolean;
};
function isAbortError(error: unknown): boolean {
return (
(error instanceof DOMException && error.name === "AbortError") ||
(error instanceof Error && error.name === "AbortError")
);
}
function triggerBlobDownload(blob: Blob, fileName: string): void {
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = blobUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
// Defer cleanup so the browser can start the download before the URL is revoked.
setTimeout(() => {
URL.revokeObjectURL(blobUrl);
a.remove();
}, 1000);
}
/** Normalize worker-transferred views for BlobPart / BufferSource (TS 5.9 ArrayBuffer typing). */
function asArrayBufferView(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
return bytes.buffer instanceof ArrayBuffer
? (bytes as Uint8Array<ArrayBuffer>)
: new Uint8Array(bytes);
}
function createBlobSink(fileName: string): OutputSink {
const chunks: BlobPart[] = [];
return {
streaming: false,
async write(bytes) {
chunks.push(asArrayBufferView(bytes));
},
async close() {
triggerBlobDownload(new Blob(chunks), fileName);
},
async abort() {
chunks.length = 0;
},
};
}
async function tryCreateStreamingSink(fileName: string): Promise<OutputSink | null> {
if (typeof window.showSaveFilePicker !== "function") {
return null;
}
try {
const handle = await window.showSaveFilePicker({ suggestedName: fileName });
const writable = await handle.createWritable();
return {
streaming: true,
async write(bytes) {
await writable.write(asArrayBufferView(bytes));
},
async close() {
await writable.close();
},
async abort() {
await writable.abort();
},
};
} catch (error) {
if (isAbortError(error)) {
throw new SaveCancelledError();
}
// No user activation, unsupported, or other picker/writable failure → Blob sink.
return null;
}
}
export async function createOutputSink(fileName: string): Promise<OutputSink> {
const streaming = await tryCreateStreamingSink(fileName);
if (streaming) return streaming;
return createBlobSink(fileName);
}

View File

@@ -0,0 +1,162 @@
export interface XdeltaResult {
ok: boolean;
hasChecksums: boolean | null;
errorCode?: number;
errorMessage?: string;
}
type WorkerChunkMessage = { type: "chunk"; bytes: Uint8Array };
type WorkerProgressMessage = { type: "progress"; bytesOut: number; bytesIn: number };
type WorkerDoneMessage = {
type: "done";
ok: boolean;
hasChecksums: boolean | null;
errorCode?: number;
errorMessage?: string;
};
type WorkerMessage = WorkerChunkMessage | WorkerProgressMessage | WorkerDoneMessage;
function isWorkerMessage(data: unknown): data is WorkerMessage {
return (
typeof data === "object" &&
data !== null &&
"type" in data &&
(data.type === "chunk" || data.type === "progress" || data.type === "done")
);
}
export function friendlyXdeltaError(result: XdeltaResult): string {
const msg = result.errorMessage ?? "";
if (msg.toLowerCase().includes("checksum")) {
return "This patch does not match the selected base ROM.";
}
return msg || "xdelta patch failed";
}
export async function runXdelta(opts: {
mode: "decode" | "encode";
sourceFile: Blob;
inputFile: Blob;
disableChecksum?: boolean;
discardOutput?: boolean;
onChunk?: (bytes: Uint8Array) => void | Promise<void>;
onProgress?: (p: { bytesOut: number; bytesIn: number }) => void;
}): Promise<XdeltaResult> {
const worker = new Worker("/xdelta/xdelta3.worker.js", { type: "module" });
return new Promise<XdeltaResult>((resolve, reject) => {
let settled = false;
let chunkQueue: Promise<void> = Promise.resolve();
const finish = (settle: () => void) => {
if (settled) return;
settled = true;
worker.terminate();
settle();
};
worker.onmessage = (event: MessageEvent) => {
if (!isWorkerMessage(event.data)) {
finish(() => reject(new Error("Unexpected xdelta worker message")));
return;
}
const data = event.data;
if (data.type === "chunk") {
const bytes = data.bytes;
chunkQueue = chunkQueue.then(async () => {
if (opts.onChunk) await opts.onChunk(bytes);
});
return;
}
if (data.type === "progress") {
opts.onProgress?.({ bytesOut: data.bytesOut, bytesIn: data.bytesIn });
return;
}
// type === "done"
const result: XdeltaResult = {
ok: data.ok,
hasChecksums: data.hasChecksums ?? null,
...(data.errorCode !== undefined ? { errorCode: data.errorCode } : {}),
...(data.errorMessage !== undefined ? { errorMessage: data.errorMessage } : {}),
};
void chunkQueue
.then(() => {
finish(() => resolve(result));
})
.catch((err: unknown) => {
finish(() => reject(err));
});
};
worker.onerror = (event) => {
finish(() =>
reject(event.error instanceof Error ? event.error : new Error(event.message || "xdelta worker error")),
);
};
worker.postMessage({
command: "start",
mode: opts.mode,
sourceFile: opts.sourceFile,
inputFile: opts.inputFile,
disableChecksum: opts.disableChecksum ?? false,
discardOutput: opts.discardOutput ?? false,
});
});
}
export async function decodeXdelta(opts: {
sourceFile: Blob;
patchBlob: Blob;
onChunk: (bytes: Uint8Array) => void | Promise<void>;
onProgress?: (p: { bytesOut: number; bytesIn: number }) => void;
}): Promise<XdeltaResult> {
return runXdelta({
mode: "decode",
sourceFile: opts.sourceFile,
inputFile: opts.patchBlob,
onChunk: opts.onChunk,
onProgress: opts.onProgress,
});
}
export async function encodeXdelta(opts: {
sourceFile: Blob;
targetFile: Blob;
}): Promise<{ result: XdeltaResult; patch: Blob | null }> {
const chunks: BlobPart[] = [];
const result = await runXdelta({
mode: "encode",
sourceFile: opts.sourceFile,
inputFile: opts.targetFile,
onChunk: (bytes) => {
chunks.push(
bytes.buffer instanceof ArrayBuffer
? (bytes as Uint8Array<ArrayBuffer>)
: new Uint8Array(bytes),
);
},
});
return {
result,
patch: result.ok ? new Blob(chunks) : null,
};
}
export async function trialDecodeXdelta(opts: {
sourceFile: Blob;
patchBlob: Blob;
}): Promise<XdeltaResult> {
return runXdelta({
mode: "decode",
sourceFile: opts.sourceFile,
inputFile: opts.patchBlob,
discardOutput: true,
disableChecksum: false,
});
}

View File

@@ -0,0 +1,4 @@
create type public."Patch Format" as enum ('bps', 'xdelta');
alter table if exists public.patches
add column if not exists format "Patch Format" not null default 'bps';