touch-coop 1.0.0

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.
@@ -0,0 +1,31 @@
1
+ export interface BasePlayerEvent {
2
+ playerId: string;
3
+ timestamp: number;
4
+ }
5
+ export interface JoinLeaveEvent {
6
+ action: "JOIN" | "LEAVE";
7
+ }
8
+ export interface MoveEvent {
9
+ action: "MOVE";
10
+ button: string;
11
+ }
12
+ export type PlayerEvent = (JoinLeaveEvent | MoveEvent) & BasePlayerEvent;
13
+ type OnPlayerEventHandler = (data: PlayerEvent) => void;
14
+ export declare class Match {
15
+ private _playerConnections;
16
+ private _playerChannels;
17
+ private _invitationAccepted;
18
+ private _onPlayerEvent;
19
+ private _gamepadUiUrl;
20
+ constructor(gamepadUiUrl: string, onPlayerEvent: OnPlayerEventHandler);
21
+ private _UUIID;
22
+ requestNewPlayerToJoin(): Promise<{
23
+ dataUrl: string;
24
+ playerId: string;
25
+ shareURL: string;
26
+ }>;
27
+ getInvitationStatus(playerId: string): boolean | undefined;
28
+ acceptPlayerAnswer(playerId: string, base64Answer: string): Promise<void>;
29
+ }
30
+ export {};
31
+ //# sourceMappingURL=match.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"match.d.ts","sourceRoot":"","sources":["../src/match.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,WAAW,GAAG,CAAC,cAAc,GAAG,SAAS,CAAC,GAAG,eAAe,CAAC;AAEzE,KAAK,oBAAoB,GAAG,CAAC,IAAI,EAAE,WAAW,KAAK,IAAI,CAAC;AAExD,qBAAa,KAAK;IAChB,OAAO,CAAC,kBAAkB,CAA6C;IACvE,OAAO,CAAC,eAAe,CAA0C;IACjE,OAAO,CAAC,mBAAmB,CAAmC;IAC9D,OAAO,CAAC,cAAc,CAAqC;IAC3D,OAAO,CAAC,aAAa,CAAS;gBAClB,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,oBAAoB;IAyBrE,OAAO,CAAC,MAAM;IAOR,sBAAsB;iBACI,MAAM;kBAAY,MAAM;kBAAY,MAAM;;IAqD1E,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAGpD,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;CAChE"}
@@ -0,0 +1,9 @@
1
+ export declare class Player {
2
+ private _pc;
3
+ private _playerId;
4
+ private _dataChannel;
5
+ constructor();
6
+ joinMatch(): Promise<void>;
7
+ sendMove(button: string): Promise<void>;
8
+ }
9
+ //# sourceMappingURL=player.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"player.d.ts","sourceRoot":"","sources":["../src/player.ts"],"names":[],"mappings":"AAGA,qBAAa,MAAM;IACjB,OAAO,CAAC,GAAG,CAAoB;IAC/B,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,YAAY,CAA+B;;IAkC7C,SAAS;IAqCT,QAAQ,CAAC,MAAM,EAAE,MAAM;CAiB9B"}
package/media/demo.png ADDED
Binary file
package/media/logo.png ADDED
Binary file
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "touch-coop",
3
+ "version": "1.0.0",
4
+ "description": "Allow players to play couch co-op in your game using their mobile devices as controllers.",
5
+ "main": "dist/index.cjs",
6
+ "typings": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "require": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "start": "vite",
16
+ "lint": "npx @biomejs/biome check",
17
+ "lint-and-format": "npx @biomejs/biome check --write --unsafe",
18
+ "build": "vite build && tsc --emitDeclarationOnly"
19
+ },
20
+ "devDependencies": {
21
+ "@biomejs/biome": "^1.9.4",
22
+ "@types/qrcode": "^1.5.6",
23
+ "typescript": "^5.9.3",
24
+ "vite": "^7.3.1"
25
+ },
26
+ "dependencies": {
27
+ "qrcode": "^1.5.4"
28
+ }
29
+ }
@@ -0,0 +1,42 @@
1
+ export async function compressOfferData(originalText: string) {
2
+ const encoder = new TextEncoder();
3
+ const stream = new CompressionStream("gzip");
4
+ const writer = stream.writable.getWriter();
5
+ writer.write(encoder.encode(originalText));
6
+ writer.close();
7
+ const reader = stream.readable.getReader();
8
+ const chunks = [];
9
+ while (true) {
10
+ const { done, value } = await reader.read();
11
+ if (done) break;
12
+ chunks.push(value);
13
+ }
14
+ const compressed = new Uint8Array(await new Blob(chunks).arrayBuffer());
15
+ const base64 = btoa(String.fromCharCode(...compressed));
16
+ const safeBase64 = base64
17
+ .replace(/\+/g, "-")
18
+ .replace(/\//g, "_")
19
+ .replace(/=+$/, "");
20
+ return safeBase64;
21
+ }
22
+
23
+ export async function decompressOfferData(
24
+ base64Input: string,
25
+ ): Promise<string> {
26
+ let base64 = (base64Input || "").trim();
27
+ base64 = base64.replace(/\s+/g, "");
28
+ base64 = base64.replace(/-/g, "+").replace(/_/g, "/");
29
+ const mod = base64.length % 4;
30
+ if (mod === 2) {
31
+ base64 += "==";
32
+ } else if (mod === 3) {
33
+ base64 += "=";
34
+ }
35
+ const binaryString = atob(base64);
36
+ const bytes = Uint8Array.from(binaryString, (c) => c.charCodeAt(0));
37
+ const decompressedStream = new Blob([bytes])
38
+ .stream()
39
+ .pipeThrough(new DecompressionStream("gzip"));
40
+ const text = await new Response(decompressedStream).text();
41
+ return text;
42
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./player";
2
+ export * from "./match";
package/src/match.ts ADDED
@@ -0,0 +1,118 @@
1
+ import QRCode from "qrcode";
2
+ import { compressOfferData } from "./encoding";
3
+
4
+ export interface BasePlayerEvent {
5
+ playerId: string;
6
+ timestamp: number;
7
+ }
8
+
9
+ export interface JoinLeaveEvent {
10
+ action: "JOIN" | "LEAVE";
11
+ }
12
+
13
+ export interface MoveEvent {
14
+ action: "MOVE";
15
+ button: string;
16
+ }
17
+
18
+ export type PlayerEvent = (JoinLeaveEvent | MoveEvent) & BasePlayerEvent;
19
+
20
+ type OnPlayerEventHandler = (data: PlayerEvent) => void;
21
+
22
+ export class Match {
23
+ private _playerConnections: Map<string, RTCPeerConnection> = new Map();
24
+ private _playerChannels: Map<string, RTCDataChannel> = new Map();
25
+ private _invitationAccepted: Map<string, boolean> = new Map();
26
+ private _onPlayerEvent: OnPlayerEventHandler | null = null;
27
+ private _gamepadUiUrl: string;
28
+ constructor(gamepadUiUrl: string, onPlayerEvent: OnPlayerEventHandler) {
29
+ this._onPlayerEvent = onPlayerEvent;
30
+ this._gamepadUiUrl = gamepadUiUrl;
31
+ const channel = new BroadcastChannel("touch-coop-signaling");
32
+ channel.onmessage = async (event) => {
33
+ const data = event.data;
34
+ if (
35
+ data &&
36
+ data.type === "answer" &&
37
+ data.playerId &&
38
+ data.base64Answer
39
+ ) {
40
+ try {
41
+ const pc = this._playerConnections.get(data.playerId);
42
+ if (!pc) {
43
+ throw new Error(`No peer connection for player: ${data.playerId}`);
44
+ }
45
+ const answerObject = JSON.parse(atob(data.base64Answer));
46
+ await pc.setRemoteDescription(answerObject.sdp);
47
+ // Mark invitation as accepted
48
+ this._invitationAccepted.set(data.playerId, true);
49
+ } catch (err) {}
50
+ }
51
+ };
52
+ }
53
+ private _UUIID() {
54
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
55
+ const r = (Math.random() * 16) | 0;
56
+ const v = c === "x" ? r : (r & 0x3) | 0x8;
57
+ return v.toString(16);
58
+ });
59
+ }
60
+ async requestNewPlayerToJoin() {
61
+ return new Promise<{ dataUrl: string; playerId: string; shareURL: string }>(
62
+ (resolve, reject) => {
63
+ (async () => {
64
+ const newPlayer = this._UUIID();
65
+ const pc = new RTCPeerConnection();
66
+ const dataChannel = pc.createDataChannel("player");
67
+ this._playerConnections.set(newPlayer, pc);
68
+ this._playerChannels.set(newPlayer, dataChannel);
69
+ this._invitationAccepted.set(newPlayer, false);
70
+ dataChannel.onmessage = (msg) => {
71
+ if (this._onPlayerEvent) {
72
+ let eventData = msg.data;
73
+ eventData = JSON.parse(msg.data);
74
+ this._onPlayerEvent(eventData);
75
+ }
76
+ };
77
+ const offer = await pc.createOffer();
78
+ await pc.setLocalDescription(offer);
79
+ await new Promise((resolveIce) => {
80
+ pc.onicecandidate = (event) => {
81
+ if (!event.candidate) {
82
+ resolveIce(void 0);
83
+ }
84
+ };
85
+ });
86
+ const offerObject = {
87
+ playerId: newPlayer,
88
+ sdp: pc.localDescription,
89
+ };
90
+ const offerJSON = JSON.stringify(offerObject);
91
+ const compressedBase64OfferObject =
92
+ await compressOfferData(offerJSON);
93
+ const shareURL = `${this._gamepadUiUrl}?remoteSDP=${compressedBase64OfferObject}`;
94
+ QRCode.toDataURL(
95
+ shareURL,
96
+ { errorCorrectionLevel: "M" },
97
+ (err, dataUrl) => {
98
+ if (err) {
99
+ return reject(err);
100
+ }
101
+ resolve({
102
+ dataUrl: dataUrl,
103
+ shareURL: shareURL,
104
+ playerId: newPlayer,
105
+ });
106
+ },
107
+ );
108
+ })();
109
+ },
110
+ );
111
+ }
112
+
113
+ // Returns true if invitation was accepted, false if still pending, undefined if not found
114
+ getInvitationStatus(playerId: string): boolean | undefined {
115
+ return this._invitationAccepted.get(playerId);
116
+ }
117
+ async acceptPlayerAnswer(playerId: string, base64Answer: string) {}
118
+ }
package/src/player.ts ADDED
@@ -0,0 +1,95 @@
1
+ import { decompressOfferData } from "./encoding";
2
+ import type { PlayerEvent } from "./match";
3
+
4
+ export class Player {
5
+ private _pc: RTCPeerConnection;
6
+ private _playerId: string | null = null;
7
+ private _dataChannel: RTCDataChannel | null = null;
8
+ constructor() {
9
+ this._pc = new RTCPeerConnection();
10
+ this._pc.ondatachannel = (event) => {
11
+ this._dataChannel = event.channel;
12
+ this._dataChannel.onopen = () => {
13
+ if (this._playerId && this._dataChannel) {
14
+ const joinEvent = {
15
+ playerId: this._playerId,
16
+ action: "JOIN",
17
+ timestamp: Date.now(),
18
+ };
19
+ this._dataChannel.send(JSON.stringify(joinEvent));
20
+ }
21
+ };
22
+ };
23
+ window.addEventListener("beforeunload", () => {
24
+ if (
25
+ this._dataChannel &&
26
+ this._dataChannel.readyState === "open" &&
27
+ this._playerId
28
+ ) {
29
+ const leaveEvent = {
30
+ playerId: this._playerId,
31
+ action: "LEAVE",
32
+ button: "",
33
+ timestamp: Date.now(),
34
+ };
35
+ try {
36
+ this._dataChannel.send(JSON.stringify(leaveEvent));
37
+ } catch {}
38
+ }
39
+ });
40
+ }
41
+ async joinMatch() {
42
+ const params = new URLSearchParams(window.location.search);
43
+ const remoteBase64 = params.get("remoteSDP");
44
+ if (!remoteBase64) {
45
+ throw new Error("No remoteSDP found in URL parameters.");
46
+ }
47
+ const decodedURL = await decompressOfferData(remoteBase64);
48
+ const remoteObject = JSON.parse(decodedURL);
49
+ this._playerId = remoteObject.playerId;
50
+ const remoteSDP = remoteObject.sdp;
51
+ await this._pc.setRemoteDescription(remoteSDP);
52
+ if (remoteSDP.type === "offer") {
53
+ const answer = await this._pc.createAnswer();
54
+ await this._pc.setLocalDescription(answer);
55
+ await new Promise((resolve) => {
56
+ this._pc.onicecandidate = (event) => {
57
+ if (!event.candidate) {
58
+ resolve(void 0);
59
+ }
60
+ };
61
+ });
62
+ const answerObject = {
63
+ playerId: this._playerId,
64
+ sdp: this._pc.localDescription,
65
+ };
66
+ const answerJSON = JSON.stringify(answerObject);
67
+ const base64AnswerObject = btoa(answerJSON);
68
+ const channel = new BroadcastChannel("touch-coop-signaling");
69
+ const msg = {
70
+ type: "answer",
71
+ playerId: this._playerId,
72
+ base64Answer: base64AnswerObject,
73
+ };
74
+ channel.postMessage(msg);
75
+ channel.close();
76
+ }
77
+ }
78
+ async sendMove(button: string) {
79
+ if (this._dataChannel && this._dataChannel.readyState === "open") {
80
+ if (!this._playerId) {
81
+ throw new Error("Player ID is not set. Cannot send data.");
82
+ }
83
+ const playerEvent: PlayerEvent = {
84
+ playerId: this._playerId,
85
+ action: "MOVE",
86
+ button: button,
87
+ timestamp: Date.now(),
88
+ };
89
+ const playerEventJSON = JSON.stringify(playerEvent);
90
+ this._dataChannel.send(playerEventJSON);
91
+ } else {
92
+ console.warn("Data channel is not open. Cannot send data.");
93
+ }
94
+ }
95
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,98 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "libReplacement": true, /* Enable lib replacement. */
18
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
+
28
+ /* Modules */
29
+ "module": "commonjs" /* Specify what module code is generated. */,
30
+ // "rootDir": "./", /* Specify the root folder within your source files. */
31
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
32
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
37
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
40
+ // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
41
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
42
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
43
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
44
+ // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
45
+ // "resolveJsonModule": true, /* Enable importing .json files. */
46
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
47
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
48
+
49
+ /* JavaScript Support */
50
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
51
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
52
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
53
+
54
+ /* Emit */
55
+ "declaration": true,
56
+ "declarationMap": true,
57
+ "outDir": "./dist",
58
+ "rootDir": "./src",
59
+
60
+ /* Interop Constraints */
61
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
62
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
63
+ // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
64
+ // "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
65
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
66
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
67
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
68
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
69
+
70
+ /* Type Checking */
71
+ "strict": true /* Enable all strict type-checking options. */,
72
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
73
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
74
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
75
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
76
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
77
+ // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
78
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
79
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
80
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
81
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
82
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
83
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
84
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
85
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
86
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
87
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
88
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
89
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
90
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
91
+
92
+ /* Completeness */
93
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
94
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
95
+ },
96
+ "include": ["src/**/*"],
97
+ "exclude": ["dist", "node_modules", "vite.config.ts"]
98
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { resolve } from "node:path";
2
+ import { defineConfig } from "vite";
3
+
4
+ export default defineConfig({
5
+ build: {
6
+ lib: {
7
+ entry: resolve(__dirname, "src/index.ts"),
8
+ name: "TouchCoop",
9
+ fileName: (format) => {
10
+ if (format === "es") return "index.mjs";
11
+ if (format === "cjs") return "index.cjs";
12
+ if (format === "iife") return "index.global.js";
13
+ return `index.${format}.js`;
14
+ },
15
+ formats: ["es", "cjs", "iife"],
16
+ },
17
+ outDir: "dist",
18
+ emptyOutDir: true,
19
+ rollupOptions: {
20
+ external: (id) => {
21
+ // For IIFE (browser), bundle all dependencies (including qrcode)
22
+ if (/qrcode/.test(id)) {
23
+ // Only externalize for es/cjs
24
+ const format = process.env.BUILD_FORMAT;
25
+ return format === "es" || format === "cjs";
26
+ }
27
+ return false;
28
+ },
29
+ output: {
30
+ globals: {
31
+ // No external globals needed for IIFE
32
+ },
33
+ },
34
+ },
35
+ },
36
+ });