vibedgames 0.8.0 → 0.9.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.
Files changed (40) hide show
  1. package/README.md +14 -6
  2. package/dist/THIRD_PARTY_NOTICES.txt +58 -6
  3. package/dist/{chunk-FNYBZNW2.js → chunk-25BAMW5X.js} +3 -1
  4. package/dist/{chunk-SAANBZ25.js → chunk-2VUUMXAQ.js} +4 -4
  5. package/dist/{chunk-XK5RZQMX.js → chunk-355VG7EO.js} +14 -13
  6. package/dist/{chunk-I6O4HIDY.js → chunk-3HUWAJQH.js} +76 -61
  7. package/dist/{chunk-2QBYTIMH.js → chunk-5535KDYI.js} +1 -1
  8. package/dist/chunk-56OY4TEP.js +20125 -0
  9. package/dist/{chunk-XDC7QGOF.js → chunk-6EWHKL7Z.js} +14 -6
  10. package/dist/{chunk-6FZPPUQH.js → chunk-7CXMMC5S.js} +1 -1
  11. package/dist/chunk-7QZSDU52.js +26 -0
  12. package/dist/{chunk-AZGENOOR.js → chunk-AXTLPJ2F.js} +5 -4
  13. package/dist/{chunk-IO6OM6WM.js → chunk-BMTHAVMS.js} +7 -33
  14. package/dist/{chunk-CU7UY5YJ.js → chunk-D2RF35HJ.js} +1 -1
  15. package/dist/chunk-FC233UKH.js +170 -0
  16. package/dist/{chunk-CAKBGDCY.js → chunk-GKDUYJ7R.js} +5 -0
  17. package/dist/{chunk-TYVYWBY6.js → chunk-H3IPLBXQ.js} +9 -8
  18. package/dist/{chunk-TMK6V5FV.js → chunk-HNRVSBRK.js} +7 -7
  19. package/dist/chunk-K2U7L4RU.js +183 -0
  20. package/dist/{chunk-PQDBCZRT.js → chunk-KZBZNTM4.js} +203 -153
  21. package/dist/{chunk-GUF6ADBF.js → chunk-LXS3NJYD.js} +8 -7
  22. package/dist/{chunk-W5XP4ZVU.js → chunk-LY2GQ32S.js} +11 -10
  23. package/dist/{chunk-K5SC6SXO.js → chunk-NDHXM4PL.js} +5 -5
  24. package/dist/{chunk-HASKWB6B.js → chunk-OD2MNYXD.js} +48 -22
  25. package/dist/{chunk-JT2AU24K.js → chunk-QARXJGI5.js} +1 -1
  26. package/dist/{chunk-RYFO3ZPO.js → chunk-RXHTGX7C.js} +9 -2
  27. package/dist/chunk-ST5FC2W3.js +95 -0
  28. package/dist/chunk-TBQ5BU3Q.js +39 -0
  29. package/dist/{chunk-RIGKOLNN.js → chunk-UFR6G6BL.js} +40 -65
  30. package/dist/{chunk-CZPKN32Z.js → chunk-US6QZICZ.js} +10 -10
  31. package/dist/{chunk-Y552BNFZ.js → chunk-UXCWSWWX.js} +7 -7
  32. package/dist/chunk-UZM6OSW5.js +113 -0
  33. package/dist/{chunk-FL6IFBUF.js → chunk-WSRIF6K4.js} +4 -4
  34. package/dist/chunk-X75Y7LUW.js +126 -0
  35. package/dist/chunk-Z5TFZQ5U.js +2478 -0
  36. package/dist/{chunk-H4NBRFBY.js → chunk-ZCYWDKYP.js} +30 -5
  37. package/dist/index.js +30 -19
  38. package/package.json +6 -5
  39. package/dist/chunk-RNBUX5VF.js +0 -68
  40. package/dist/chunk-X4ZABSCN.js +0 -415
@@ -0,0 +1,2478 @@
1
+ import { createRequire as __createRequire } from "node:module";
2
+ import { dirname as __pathDirname } from "node:path";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import {
8
+ run
9
+ } from "./chunk-TBQ5BU3Q.js";
10
+ import "./chunk-5535KDYI.js";
11
+ import {
12
+ buildManifest,
13
+ contentTypeForPath,
14
+ resolveBuildDir
15
+ } from "./chunk-X75Y7LUW.js";
16
+ import {
17
+ SLUG_RE,
18
+ findProjectRoot,
19
+ projectConfigPath
20
+ } from "./chunk-ZI6PKVXG.js";
21
+ import {
22
+ isJsonOutput,
23
+ outputArgs,
24
+ writeStructured
25
+ } from "./chunk-ZYCSYJWX.js";
26
+ import {
27
+ assertKnownFlags
28
+ } from "./chunk-RZ4DIJQW.js";
29
+ import {
30
+ consola
31
+ } from "./chunk-D2RF35HJ.js";
32
+ import {
33
+ isJsonNumber,
34
+ isJsonObject,
35
+ isJsonString
36
+ } from "./chunk-J6PKNPI2.js";
37
+ import {
38
+ defineCommand
39
+ } from "./chunk-MBXCVCC4.js";
40
+ import "./chunk-GKDUYJ7R.js";
41
+
42
+ // src/commands/distribute.ts
43
+ import { existsSync as existsSync4, readFileSync as readFileSync4, rmSync as rmSync2 } from "node:fs";
44
+ import path5 from "node:path";
45
+
46
+ // src/lib/distribute/audit.ts
47
+ var TEXT_EXTENSIONS = /\.(?:html?|css|m?js)$/iu;
48
+ var MARKUP_EXTENSIONS = /\.(?:html?)$/iu;
49
+ var SOURCE_MAP = /\.map$/iu;
50
+ var ROOT_ATTRIBUTE = /\b(?:src|href|poster|data|action)\s*=\s*["']\/(?!\/)(?<target>[^"'#?]*)/giu;
51
+ var ROOT_LITERAL = /(?:["'`]|url\()\/(?!\/)(?<target>[\w@.~-]+(?:\/[\w@.~-]+)*\.[a-z0-9]{2,5})(?=["'`)?#])/giu;
52
+ var REMOTE_HOST = /\bhttps?:\/\/(?<host>[a-z0-9-]+(?:\.[a-z0-9-]+)+)(?::\d+)?(?=[/"'`\s)]|$)/giu;
53
+ var INERT_HOSTS = /* @__PURE__ */ new Set([
54
+ "www.w3.org",
55
+ "github.com",
56
+ "raw.githubusercontent.com",
57
+ "reactjs.org",
58
+ "react.dev",
59
+ "threejs.org",
60
+ "phaser.io",
61
+ "developer.mozilla.org",
62
+ "fb.me",
63
+ "opensource.org",
64
+ "www.apache.org",
65
+ "creativecommons.org",
66
+ "feross.org",
67
+ "jquery.org",
68
+ "vite.dev",
69
+ "vitejs.dev"
70
+ ]);
71
+ var formatBytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
72
+ var unique = (values) => [...new Set(values)].toSorted();
73
+ var captures = (text, pattern, group) => {
74
+ const found = [];
75
+ for (const match of text.matchAll(pattern)) {
76
+ const value = match.groups?.[group];
77
+ if (value !== void 0 && value.length > 0) {
78
+ found.push(value);
79
+ }
80
+ }
81
+ return found;
82
+ };
83
+ var rootReferences = (input) => {
84
+ const shipped = new Set(input.files.map((file) => file.path));
85
+ const offenders = /* @__PURE__ */ new Map();
86
+ for (const file of input.files) {
87
+ if (!TEXT_EXTENSIONS.test(file.path)) {
88
+ continue;
89
+ }
90
+ const text = input.readText(file.path);
91
+ const targets = MARKUP_EXTENSIONS.test(file.path) ? captures(text, ROOT_ATTRIBUTE, "target") : captures(text, ROOT_LITERAL, "target").filter((target) => shipped.has(target));
92
+ if (targets.length > 0) {
93
+ offenders.set(file.path, unique(targets));
94
+ }
95
+ }
96
+ if (offenders.size === 0) {
97
+ return [];
98
+ }
99
+ const examples = [...offenders].flatMap(([file, targets]) => targets.map((target) => `/${target} (in ${file})`)).slice(0, 5);
100
+ return [
101
+ {
102
+ id: "root-relative-url",
103
+ level: "error",
104
+ message: `The build loads files from the site root (${examples.join(", ")}). A portal serves the game from a folder, where those 404. Build with a relative base (Vite: \`base: "./"\`) and reference files as \`./name\` or through an import.`,
105
+ paths: [...offenders.keys()].toSorted()
106
+ }
107
+ ];
108
+ };
109
+ var sizeFindings = ({ files, limits }) => {
110
+ const findings = [];
111
+ const total = files.reduce((sum, file) => sum + file.size, 0);
112
+ if (limits.maxFiles !== null && files.length > limits.maxFiles) {
113
+ findings.push({
114
+ id: "too-many-files",
115
+ level: "error",
116
+ message: `${files.length} files; the portal accepts ${limits.maxFiles}. Pack small assets into atlases or a single data file.`
117
+ });
118
+ }
119
+ if (limits.maxExtractedBytes !== null && total > limits.maxExtractedBytes) {
120
+ findings.push({
121
+ id: "build-too-large",
122
+ level: "error",
123
+ message: `The build is ${formatBytes(total)} unpacked; the portal accepts ${formatBytes(limits.maxExtractedBytes)}.`
124
+ });
125
+ }
126
+ const { maxFileBytes } = limits;
127
+ if (maxFileBytes !== null) {
128
+ const oversized = files.filter((file) => file.size > maxFileBytes).map((file) => file.path);
129
+ if (oversized.length > 0) {
130
+ findings.push({
131
+ id: "file-too-large",
132
+ level: "error",
133
+ message: `${oversized.length} file(s) exceed the portal's ${formatBytes(maxFileBytes)} per-file limit.`,
134
+ paths: oversized.toSorted()
135
+ });
136
+ }
137
+ }
138
+ return findings;
139
+ };
140
+ var pathFindings = ({ files, limits }) => {
141
+ const findings = [];
142
+ const { maxPathLength } = limits;
143
+ if (maxPathLength !== null) {
144
+ const long = files.filter((file) => file.path.length > maxPathLength).map((file) => file.path);
145
+ if (long.length > 0) {
146
+ findings.push({
147
+ id: "path-too-long",
148
+ level: "error",
149
+ message: `${long.length} path(s) are longer than the portal's ${maxPathLength} characters.`,
150
+ paths: long.toSorted()
151
+ });
152
+ }
153
+ }
154
+ const byFolded = /* @__PURE__ */ new Map();
155
+ for (const file of files) {
156
+ const folded = file.path.toLowerCase();
157
+ byFolded.set(folded, [...byFolded.get(folded) ?? [], file.path]);
158
+ }
159
+ const collisions = [...byFolded.values()].filter((paths) => paths.length > 1).flat();
160
+ if (collisions.length > 0) {
161
+ findings.push({
162
+ id: "case-collision",
163
+ level: "error",
164
+ message: "Paths differ only by letter case. They are one file on a case-insensitive host and two on a case-sensitive one, so one of them loads the wrong thing somewhere.",
165
+ paths: collisions.toSorted()
166
+ });
167
+ }
168
+ return findings;
169
+ };
170
+ var fileNameFinding = ({ files, limits }) => {
171
+ const { fileName } = limits;
172
+ if (fileName === null) {
173
+ return [];
174
+ }
175
+ const bad = files.filter((file) => file.path.split("/").some((segment) => !fileName.test(segment))).map((file) => file.path);
176
+ return bad.length === 0 ? [] : [
177
+ {
178
+ id: "bad-file-name",
179
+ level: "error",
180
+ message: `${bad.length} path(s) use characters the portal refuses. Rename to letters, digits, "_", "-" and "." only.`,
181
+ paths: bad.toSorted()
182
+ }
183
+ ];
184
+ };
185
+ var sdkFinding = ({ files, readText, sdk }) => {
186
+ if (sdk === null) {
187
+ return [];
188
+ }
189
+ const scripts = files.filter((file) => TEXT_EXTENSIONS.test(file.path)).map((file) => readText(file.path)).join("\n");
190
+ const missing = sdk.calls.filter((call) => !scripts.includes(`.${call}(`));
191
+ return missing.length === 0 ? [] : [
192
+ {
193
+ id: "sdk-not-called",
194
+ level: "error",
195
+ message: `The build never calls ${missing.join(", ")} from the portal's SDK, which it requires. The distribute skill shows each call.`
196
+ }
197
+ ];
198
+ };
199
+ var sourceMapFinding = ({ files }) => {
200
+ const maps = files.filter((file) => SOURCE_MAP.test(file.path)).map((file) => file.path);
201
+ return maps.length === 0 ? [] : [
202
+ {
203
+ id: "source-maps",
204
+ level: "warning",
205
+ message: "The build ships source maps: anyone who downloads the game can read its original source. Turn them off for the build you distribute.",
206
+ paths: maps.toSorted()
207
+ }
208
+ ];
209
+ };
210
+ var remoteHosts = (input) => unique(
211
+ input.files.filter((file) => TEXT_EXTENSIONS.test(file.path)).flatMap((file) => captures(input.readText(file.path), REMOTE_HOST, "host")).map((host) => host.toLowerCase()).filter((host) => !INERT_HOSTS.has(host))
212
+ );
213
+ var remoteHostFinding = (input) => {
214
+ if (input.limits.network === "open") {
215
+ return [];
216
+ }
217
+ const hosts = remoteHosts(input);
218
+ return hosts.length === 0 ? [] : [
219
+ {
220
+ id: "remote-hosts",
221
+ level: "warning",
222
+ message: `The build reaches ${hosts.join(", ")}. This portal restricts requests to other hosts: bundle what you can and make the rest optional, so the game still plays when a request is refused.`
223
+ }
224
+ ];
225
+ };
226
+ var auditBuild = (input) => {
227
+ if (!input.files.some((file) => file.path === "index.html")) {
228
+ return [
229
+ {
230
+ id: "no-index",
231
+ level: "error",
232
+ message: "No index.html at the build root. Point at the build output (dist/), not the project."
233
+ }
234
+ ];
235
+ }
236
+ return [
237
+ ...rootReferences(input),
238
+ ...sizeFindings(input),
239
+ ...pathFindings(input),
240
+ ...fileNameFinding(input),
241
+ ...sdkFinding(input),
242
+ ...sourceMapFinding(input),
243
+ ...remoteHostFinding(input)
244
+ ];
245
+ };
246
+
247
+ // src/lib/distribute/config.ts
248
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
249
+ import path from "node:path";
250
+ var ORIENTATIONS = ["any", "portrait", "landscape"];
251
+ var APP_ID_RE = /^[a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z][a-zA-Z0-9_]*)+$/u;
252
+ var VERSION_RE = /^\d+(?:\.\d+){0,2}$/u;
253
+ var COLOR_RE = /^#[0-9a-fA-F]{6}$/u;
254
+ var DEFAULT_ICON = "icon.png";
255
+ var isOrientation = (value) => ORIENTATIONS.some((orientation) => orientation === value);
256
+ var readJson = (file) => {
257
+ const parsed = JSON.parse(readFileSync(file, "utf-8"));
258
+ if (!isJsonObject(parsed)) {
259
+ throw new Error(`${file} must hold a JSON object.`);
260
+ }
261
+ return parsed;
262
+ };
263
+ var optionalString = (source, key, pattern, expected) => {
264
+ const value = source[key];
265
+ if (value === void 0) {
266
+ return void 0;
267
+ }
268
+ if (!isJsonString(value) || !pattern.test(value)) {
269
+ throw new Error(`vibedgames.json: distribute.${key} must be ${expected}.`);
270
+ }
271
+ return value;
272
+ };
273
+ var parsePermissions = (value) => {
274
+ if (value === void 0) {
275
+ return {};
276
+ }
277
+ if (!isJsonObject(value)) {
278
+ throw new Error("vibedgames.json: distribute.permissions must be an object.");
279
+ }
280
+ const permissions = {};
281
+ for (const device of ["camera", "microphone"]) {
282
+ const reason = value[device];
283
+ if (reason === void 0) {
284
+ continue;
285
+ }
286
+ if (!isJsonString(reason) || reason.trim().length === 0) {
287
+ throw new Error(
288
+ `vibedgames.json: distribute.permissions.${device} must be the sentence the OS shows when it asks, e.g. "Steer with your hand."`
289
+ );
290
+ }
291
+ permissions[device] = reason;
292
+ }
293
+ return permissions;
294
+ };
295
+ var parseBuild = (value) => {
296
+ if (value === void 0) {
297
+ return 1;
298
+ }
299
+ if (!isJsonNumber(value) || !Number.isInteger(value) || value < 1) {
300
+ throw new Error("vibedgames.json: distribute.build must be a whole number, 1 or more.");
301
+ }
302
+ return value;
303
+ };
304
+ var parseOrientation = (value) => {
305
+ if (value === void 0) {
306
+ return "any";
307
+ }
308
+ if (!isJsonString(value) || !isOrientation(value)) {
309
+ throw new Error(
310
+ `vibedgames.json: distribute.orientation must be one of ${ORIENTATIONS.join(", ")}.`
311
+ );
312
+ }
313
+ return value;
314
+ };
315
+ var parseNative = (root, block) => {
316
+ const appId = optionalString(
317
+ block,
318
+ "appId",
319
+ APP_ID_RE,
320
+ "a reverse-DNS id such as com.yourstudio.game"
321
+ );
322
+ if (appId === void 0) {
323
+ return null;
324
+ }
325
+ const { icon } = block;
326
+ if (icon !== void 0 && !isJsonString(icon)) {
327
+ throw new Error("vibedgames.json: distribute.icon must be a path to a square PNG.");
328
+ }
329
+ return {
330
+ appId,
331
+ backgroundColor: optionalString(block, "backgroundColor", COLOR_RE, "a #rrggbb colour") ?? "#000000",
332
+ build: parseBuild(block.build),
333
+ icon: icon ?? (existsSync(path.join(root, DEFAULT_ICON)) ? DEFAULT_ICON : null),
334
+ orientation: parseOrientation(block.orientation),
335
+ permissions: parsePermissions(block.permissions),
336
+ version: optionalString(block, "version", VERSION_RE, "a version such as 1.0.0") ?? "1.0.0"
337
+ };
338
+ };
339
+ var readDistributeProject = (dir) => {
340
+ const root = findProjectRoot(dir);
341
+ if (!root) {
342
+ throw new Error(
343
+ `No vibedgames.json at or above ${dir}. Create one: {"slug": "my-game", "name": "My Game"}`
344
+ );
345
+ }
346
+ const raw = readJson(projectConfigPath(root));
347
+ if (!isJsonString(raw.slug) || !SLUG_RE.test(raw.slug)) {
348
+ throw new Error('vibedgames.json needs a "slug": lowercase letters, digits and hyphens.');
349
+ }
350
+ const block = raw.distribute;
351
+ if (block !== void 0 && !isJsonObject(block)) {
352
+ throw new Error("vibedgames.json: distribute must be an object.");
353
+ }
354
+ return {
355
+ name: isJsonString(raw.name) && raw.name.length > 0 ? raw.name : raw.slug,
356
+ native: block ? parseNative(root, block) : null,
357
+ root,
358
+ slug: raw.slug
359
+ };
360
+ };
361
+ var writeDistributeFields = (root, fields) => {
362
+ const file = projectConfigPath(root);
363
+ const raw = readJson(file);
364
+ const block = isJsonObject(raw.distribute) ? raw.distribute : {};
365
+ writeFileSync(
366
+ file,
367
+ `${JSON.stringify({ ...raw, distribute: { ...block, ...fields } }, null, 2)}
368
+ `
369
+ );
370
+ };
371
+
372
+ // src/lib/distribute/native-shell.ts
373
+ import {
374
+ copyFileSync,
375
+ existsSync as existsSync2,
376
+ mkdirSync,
377
+ mkdtempSync,
378
+ readFileSync as readFileSync2,
379
+ rmSync,
380
+ writeFileSync as writeFileSync2
381
+ } from "node:fs";
382
+ import { tmpdir } from "node:os";
383
+ import path2 from "node:path";
384
+
385
+ // src/lib/distribute/android-shell.ts
386
+ var MANAGED_START = "<!-- vg:distribute -->";
387
+ var MANAGED_END = "<!-- /vg:distribute -->";
388
+ var ORIENTATION_ATTRIBUTE = {
389
+ any: null,
390
+ landscape: "sensorLandscape",
391
+ portrait: "sensorPortrait"
392
+ };
393
+ var manifestPermissions = (config) => {
394
+ const lines = [];
395
+ if (config.permissions.camera !== void 0) {
396
+ lines.push(
397
+ '<uses-permission android:name="android.permission.CAMERA" />',
398
+ '<uses-feature android:name="android.hardware.camera" android:required="false" />'
399
+ );
400
+ }
401
+ if (config.permissions.microphone !== void 0) {
402
+ lines.push(
403
+ '<uses-permission android:name="android.permission.RECORD_AUDIO" />',
404
+ '<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />',
405
+ '<uses-feature android:name="android.hardware.microphone" android:required="false" />'
406
+ );
407
+ }
408
+ return lines;
409
+ };
410
+ var setManifest = (manifest, config) => {
411
+ const managed = new RegExp(`\\s*${MANAGED_START}[\\s\\S]*?${MANAGED_END}`, "u");
412
+ let next = manifest.replace(managed, "").replace(/\s*android:screenOrientation="[^"]*"/u, "");
413
+ const orientation = ORIENTATION_ATTRIBUTE[config.orientation];
414
+ if (orientation !== null) {
415
+ next = next.replace(
416
+ 'android:name=".MainActivity"',
417
+ `android:name=".MainActivity"
418
+ android:screenOrientation="${orientation}"`
419
+ );
420
+ }
421
+ const permissions = manifestPermissions(config);
422
+ if (permissions.length === 0) {
423
+ return next;
424
+ }
425
+ const end = next.lastIndexOf("</manifest>");
426
+ if (end === -1) {
427
+ throw new Error("AndroidManifest.xml has no closing </manifest>.");
428
+ }
429
+ const block = [MANAGED_START, ...permissions, MANAGED_END].map((line) => ` ${line}`);
430
+ return `${next.slice(0, end).trimEnd()}
431
+ ${block.join("\n")}
432
+ ${next.slice(end)}`;
433
+ };
434
+ var readApplicationId = (buildGradle) => /applicationId\s+"(?<id>[^"]+)"/u.exec(buildGradle)?.groups?.id ?? null;
435
+ var setGradleVersion = (buildGradle, config) => buildGradle.replace(/versionCode\s+\d+/u, `versionCode ${config.build}`).replace(/versionName\s+"[^"]*"/u, `versionName "${config.version}"`);
436
+ var mainActivitySource = (appId) => `package ${appId};
437
+
438
+ import androidx.core.view.WindowCompat;
439
+ import androidx.core.view.WindowInsetsCompat;
440
+ import androidx.core.view.WindowInsetsControllerCompat;
441
+ import com.getcapacitor.BridgeActivity;
442
+
443
+ public class MainActivity extends BridgeActivity {
444
+
445
+ @Override
446
+ public void onWindowFocusChanged(boolean hasFocus) {
447
+ super.onWindowFocusChanged(hasFocus);
448
+ if (!hasFocus) {
449
+ return;
450
+ }
451
+ WindowInsetsControllerCompat bars =
452
+ WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
453
+ bars.setSystemBarsBehavior(
454
+ WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
455
+ );
456
+ bars.hide(WindowInsetsCompat.Type.systemBars());
457
+ }
458
+ }
459
+ `;
460
+
461
+ // src/lib/distribute/ios-shell.ts
462
+ var escapeXml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
463
+ var renderValue = (value) => {
464
+ if (value === true) {
465
+ return "<true/>";
466
+ }
467
+ if (value === false) {
468
+ return "<false/>";
469
+ }
470
+ if (Array.isArray(value)) {
471
+ const items = value.map((item) => ` <string>${escapeXml(item)}</string>`).join("\n");
472
+ return `<array>
473
+ ${items}
474
+ </array>`;
475
+ }
476
+ return `<string>${escapeXml(value)}</string>`;
477
+ };
478
+ var escapeRegExp = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
479
+ var setPlistEntries = (plist, entries) => {
480
+ let next = plist;
481
+ for (const key of Object.keys(entries)) {
482
+ const existing = new RegExp(
483
+ `\\s*<key>${escapeRegExp(key)}</key>\\s*(?:<string>[^<]*</string>|<true/>|<false/>|<array>[\\s\\S]*?</array>)`,
484
+ "u"
485
+ );
486
+ next = next.replace(existing, "");
487
+ }
488
+ const end = next.lastIndexOf("</dict>");
489
+ if (end === -1) {
490
+ throw new Error("Info.plist has no closing </dict>: not a property list this can edit.");
491
+ }
492
+ const added = Object.entries(entries).map(([key, value]) => ` <key>${key}</key>
493
+ ${renderValue(value)}
494
+ `).join("");
495
+ return `${next.slice(0, end).trimEnd()}
496
+ ${added}${next.slice(end)}`;
497
+ };
498
+ var PORTRAIT = ["UIInterfaceOrientationPortrait"];
499
+ var LANDSCAPE = ["UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight"];
500
+ var ORIENTATION_MASKS = {
501
+ any: [...PORTRAIT, ...LANDSCAPE],
502
+ landscape: LANDSCAPE,
503
+ portrait: PORTRAIT
504
+ };
505
+ var iosPlistEntries = (config) => {
506
+ const entries = {
507
+ // The shell speaks only HTTPS and WSS, which is the encryption Apple
508
+ // exempts; declared here so every upload does not stop to ask.
509
+ ITSAppUsesNonExemptEncryption: false,
510
+ // A game owns the whole screen. Without this an iPad build that does not
511
+ // offer all four orientations is refused at upload, since it could not
512
+ // take part in Split View.
513
+ UIRequiresFullScreen: true,
514
+ UIStatusBarHidden: true,
515
+ UISupportedInterfaceOrientations: ORIENTATION_MASKS[config.orientation],
516
+ "UISupportedInterfaceOrientations~ipad": ORIENTATION_MASKS[config.orientation],
517
+ UIViewControllerBasedStatusBarAppearance: false
518
+ };
519
+ if (config.permissions.camera !== void 0) {
520
+ entries.NSCameraUsageDescription = config.permissions.camera;
521
+ }
522
+ if (config.permissions.microphone !== void 0) {
523
+ entries.NSMicrophoneUsageDescription = config.permissions.microphone;
524
+ }
525
+ return entries;
526
+ };
527
+ var setXcodeBuildSettings = (pbxproj, config) => pbxproj.replaceAll(/MARKETING_VERSION = [^;]+;/gu, `MARKETING_VERSION = ${config.version};`).replaceAll(/CURRENT_PROJECT_VERSION = [^;]+;/gu, `CURRENT_PROJECT_VERSION = ${config.build};`).replaceAll(
528
+ /PRODUCT_BUNDLE_IDENTIFIER = [^;]+;/gu,
529
+ `PRODUCT_BUNDLE_IDENTIFIER = ${config.appId};`
530
+ );
531
+
532
+ // src/lib/distribute/png.ts
533
+ import { closeSync, openSync, readSync } from "node:fs";
534
+ var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
535
+ var HEADER_BYTES = 24;
536
+ var WIDTH_OFFSET = 16;
537
+ var HEIGHT_OFFSET = 20;
538
+ var readPngSize = (file) => {
539
+ const header = Buffer.alloc(HEADER_BYTES);
540
+ const fd2 = openSync(file, "r");
541
+ try {
542
+ if (readSync(fd2, header, 0, HEADER_BYTES, 0) < HEADER_BYTES) {
543
+ return null;
544
+ }
545
+ } finally {
546
+ closeSync(fd2);
547
+ }
548
+ if (!header.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
549
+ return null;
550
+ }
551
+ return { height: header.readUInt32BE(HEIGHT_OFFSET), width: header.readUInt32BE(WIDTH_OFFSET) };
552
+ };
553
+
554
+ // src/lib/distribute/native-shell.ts
555
+ var PLATFORMS = ["ios", "android"];
556
+ var CAPACITOR = "^8.0.0";
557
+ var ASSETS = "@capacitor/assets@^4.0.0";
558
+ var MIN_ICON = 1024;
559
+ var OUTPUT_TAIL = 2e3;
560
+ var LOCKFILES = [
561
+ ["pnpm-lock.yaml", { add: ["add", "-D"], bin: "pnpm" }],
562
+ ["yarn.lock", { add: ["add", "-D"], bin: "yarn" }],
563
+ ["bun.lock", { add: ["add", "-d"], bin: "bun" }],
564
+ ["bun.lockb", { add: ["add", "-d"], bin: "bun" }],
565
+ ["package-lock.json", { add: ["install", "-D"], bin: "npm" }]
566
+ ];
567
+ var projectPackageManager = (root) => {
568
+ let current = root;
569
+ while (true) {
570
+ for (const [lockfile, manager] of LOCKFILES) {
571
+ if (existsSync2(path2.join(current, lockfile))) {
572
+ return manager;
573
+ }
574
+ }
575
+ const parent = path2.dirname(current);
576
+ if (parent === current) {
577
+ return { add: ["install", "-D"], bin: "npm" };
578
+ }
579
+ current = parent;
580
+ }
581
+ };
582
+ var readJsonObject = (file) => {
583
+ const parsed = JSON.parse(readFileSync2(file, "utf-8"));
584
+ if (!isJsonObject(parsed)) {
585
+ throw new Error(`${file} must hold a JSON object.`);
586
+ }
587
+ return parsed;
588
+ };
589
+ var expectOk = (result, doing) => {
590
+ if (result.code !== 0) {
591
+ throw new Error(`${doing} failed:
592
+ ${result.output.slice(-OUTPUT_TAIL).trim()}`);
593
+ }
594
+ };
595
+ var declaredPackages = (manifest) => {
596
+ const names = /* @__PURE__ */ new Set();
597
+ for (const field of ["dependencies", "devDependencies"]) {
598
+ const block = manifest[field];
599
+ if (isJsonObject(block)) {
600
+ for (const name of Object.keys(block)) {
601
+ names.add(name);
602
+ }
603
+ }
604
+ }
605
+ return names;
606
+ };
607
+ var ensureCapacitor = async ({ project, platform, say }) => {
608
+ const manifestPath = path2.join(project.root, "package.json");
609
+ if (!existsSync2(manifestPath)) {
610
+ writeFileSync2(
611
+ manifestPath,
612
+ `${JSON.stringify({ name: project.slug, private: true }, null, 2)}
613
+ `
614
+ );
615
+ }
616
+ const declared = declaredPackages(readJsonObject(manifestPath));
617
+ const wanted = ["@capacitor/core", "@capacitor/cli", `@capacitor/${platform}`].filter(
618
+ (name) => !declared.has(name)
619
+ );
620
+ if (wanted.length === 0) {
621
+ return;
622
+ }
623
+ const manager = projectPackageManager(project.root);
624
+ say(`Installing ${wanted.join(", ")} with ${manager.bin}`);
625
+ expectOk(
626
+ await run(
627
+ manager.bin,
628
+ [...manager.add, ...wanted.map((name) => `${name}@${CAPACITOR}`)],
629
+ project.root
630
+ ),
631
+ `${manager.bin} ${manager.add.join(" ")}`
632
+ );
633
+ };
634
+ var CODE_CONFIGS = ["capacitor.config.ts", "capacitor.config.js", "capacitor.config.mjs"];
635
+ var writeCapacitorConfig = ({ project, native, buildDir }) => {
636
+ const code = CODE_CONFIGS.find((name) => existsSync2(path2.join(project.root, name)));
637
+ if (code !== void 0) {
638
+ throw new Error(
639
+ `${code} is in the way: \`vg distribute\` writes capacitor.config.json from vibedgames.json, and Capacitor reads the code config first. Move its settings into capacitor.config.json and delete it.`
640
+ );
641
+ }
642
+ const file = path2.join(project.root, "capacitor.config.json");
643
+ const existing = existsSync2(file) ? readJsonObject(file) : {};
644
+ const config = {
645
+ ...existing,
646
+ appId: native.appId,
647
+ appName: project.name,
648
+ backgroundColor: native.backgroundColor,
649
+ webDir: path2.relative(project.root, buildDir).split(path2.sep).join("/")
650
+ };
651
+ writeFileSync2(file, `${JSON.stringify(config, null, 2)}
652
+ `);
653
+ };
654
+ var cap = (root, args) => run("npx", ["--no-install", "cap", ...args], root);
655
+ var rewrite = (file, transform) => {
656
+ if (!existsSync2(file)) {
657
+ throw new Error(`${file} is missing: delete the platform folder and run this again.`);
658
+ }
659
+ writeFileSync2(file, transform(readFileSync2(file, "utf-8")));
660
+ };
661
+ var applyIos = ({ project, native }) => {
662
+ const app = path2.join(project.root, "ios", "App");
663
+ rewrite(
664
+ path2.join(app, "App", "Info.plist"),
665
+ (plist) => setPlistEntries(plist, iosPlistEntries(native))
666
+ );
667
+ rewrite(
668
+ path2.join(app, "App.xcodeproj", "project.pbxproj"),
669
+ (pbxproj) => setXcodeBuildSettings(pbxproj, native)
670
+ );
671
+ return "ios/App/App.xcodeproj";
672
+ };
673
+ var applyAndroid = ({ project, native }) => {
674
+ const app = path2.join(project.root, "android", "app");
675
+ const gradle = path2.join(app, "build.gradle");
676
+ const created = existsSync2(gradle) ? readApplicationId(readFileSync2(gradle, "utf-8")) : null;
677
+ if (created !== null && created !== native.appId) {
678
+ throw new Error(
679
+ `android/ was created as ${created}, but vibedgames.json now says ${native.appId}. Delete android/ and run this again.`
680
+ );
681
+ }
682
+ rewrite(gradle, (text) => setGradleVersion(text, native));
683
+ rewrite(
684
+ path2.join(app, "src", "main", "AndroidManifest.xml"),
685
+ (manifest) => setManifest(manifest, native)
686
+ );
687
+ const activityDir = path2.join(app, "src", "main", "java", ...native.appId.split("."));
688
+ mkdirSync(activityDir, { recursive: true });
689
+ writeFileSync2(path2.join(activityDir, "MainActivity.java"), mainActivitySource(native.appId));
690
+ return "android";
691
+ };
692
+ var generateIcons = async ({ project, native, platform, say }) => {
693
+ if (native.icon === null) {
694
+ return false;
695
+ }
696
+ const source = path2.resolve(project.root, native.icon);
697
+ if (!existsSync2(source)) {
698
+ throw new Error(`distribute.icon points at ${native.icon}, which does not exist.`);
699
+ }
700
+ const size = readPngSize(source);
701
+ if (size === null || size.width !== size.height || size.width < MIN_ICON) {
702
+ throw new Error(
703
+ `${native.icon} must be a square PNG of ${MIN_ICON}px or more${size ? ` (it is ${size.width}\xD7${size.height})` : ""}.`
704
+ );
705
+ }
706
+ say("Generating icons and splash screens");
707
+ const staging = mkdtempSync(path2.join(tmpdir(), "vg-distribute-"));
708
+ try {
709
+ copyFileSync(source, path2.join(staging, "logo.png"));
710
+ const color = native.backgroundColor;
711
+ expectOk(
712
+ await run(
713
+ "npx",
714
+ [
715
+ "--yes",
716
+ ASSETS,
717
+ "generate",
718
+ `--${platform}`,
719
+ "--assetPath",
720
+ staging,
721
+ "--iconBackgroundColor",
722
+ color,
723
+ "--iconBackgroundColorDark",
724
+ color,
725
+ "--splashBackgroundColor",
726
+ color,
727
+ "--splashBackgroundColorDark",
728
+ color
729
+ ],
730
+ project.root
731
+ ),
732
+ "Icon generation"
733
+ );
734
+ } finally {
735
+ rmSync(staging, { force: true, recursive: true });
736
+ }
737
+ return true;
738
+ };
739
+ var prepareShell = async (input) => {
740
+ const { project, platform, buildDir, say } = input;
741
+ if (path2.resolve(buildDir) === path2.resolve(project.root)) {
742
+ throw new Error(
743
+ "The game must sit in its own folder (dist/, build/ or out/): the shell copies that whole folder into the app, and the project root holds the shell itself."
744
+ );
745
+ }
746
+ await ensureCapacitor(input);
747
+ writeCapacitorConfig(input);
748
+ if (!existsSync2(path2.join(project.root, platform))) {
749
+ say(`Creating the ${platform} project`);
750
+ expectOk(await cap(project.root, ["add", platform]), `cap add ${platform}`);
751
+ }
752
+ say("Copying the build into the shell");
753
+ expectOk(await cap(project.root, ["sync", platform]), `cap sync ${platform}`);
754
+ const shell = platform === "ios" ? applyIos(input) : applyAndroid(input);
755
+ return { icon: await generateIcons(input), project: shell };
756
+ };
757
+
758
+ // src/lib/distribute/portals.ts
759
+ var MB = 1024 * 1024;
760
+ var UNLIMITED = {
761
+ fileName: null,
762
+ maxExtractedBytes: null,
763
+ maxFileBytes: null,
764
+ maxFiles: null,
765
+ maxPathLength: null,
766
+ maxZipBytes: null,
767
+ network: "open"
768
+ };
769
+ var YOUTUBE_CSP = "default-src 'none'; script-src 'report-sample' 'self' 'unsafe-eval' 'unsafe-inline' blob: https://www.youtube.com/game_api/v0 https://www.youtube.com/game_api/v0/ https://www.youtube.com/game_api/v1 https://www.youtube.com/game_api/v1/; object-src 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' blob: data:; media-src 'self' blob:; font-src 'self' data: https://fonts.googleapis.com https://fonts.gstatic.com; connect-src 'self' blob: data:; sandbox allow-pointer-lock allow-same-origin allow-scripts; base-uri 'self'; manifest-src 'self'; worker-src 'self' blob:";
770
+ var PORTALS = [
771
+ {
772
+ access: "open",
773
+ id: "web",
774
+ integration: null,
775
+ limits: UNLIMITED,
776
+ name: "Any web host",
777
+ notes: "No portal's limits: only the checks every folder-hosted, framed game must pass.",
778
+ sdk: "none",
779
+ submitUrl: null
780
+ },
781
+ {
782
+ access: "open",
783
+ id: "itch",
784
+ integration: null,
785
+ limits: {
786
+ ...UNLIMITED,
787
+ maxExtractedBytes: 500 * MB,
788
+ maxFileBytes: 200 * MB,
789
+ maxFiles: 1e3,
790
+ maxPathLength: 240
791
+ },
792
+ name: "itch.io",
793
+ notes: "Live on upload. Set the upload's kind to HTML and give the embed a viewport size. `butler push` uploads from a shell.",
794
+ sdk: "none",
795
+ submitUrl: "https://itch.io/game/new"
796
+ },
797
+ {
798
+ access: "open",
799
+ id: "newgrounds",
800
+ integration: null,
801
+ limits: UNLIMITED,
802
+ name: "Newgrounds",
803
+ notes: "Live on upload, then players vote on whether it stays. Two submissions a day; the size cap is per account.",
804
+ sdk: "none",
805
+ submitUrl: "https://www.newgrounds.com/projects/games"
806
+ },
807
+ {
808
+ access: "review",
809
+ id: "crazygames",
810
+ integration: null,
811
+ limits: { ...UNLIMITED, maxExtractedBytes: 250 * MB, maxFiles: 1500 },
812
+ name: "CrazyGames",
813
+ notes: "Reviewed before it is listed. Without their SDK the whole build must be under 50 MB, and the first playable moment under 20 seconds.",
814
+ sdk: "none",
815
+ submitUrl: "https://developer.crazygames.com"
816
+ },
817
+ {
818
+ access: "review",
819
+ id: "poki",
820
+ integration: null,
821
+ limits: { ...UNLIMITED, network: "restricted" },
822
+ name: "Poki",
823
+ notes: "Curated, and exclusive on the web: a game listed there may not be on other portals. Their SDK is required, and every other host (a multiplayer server too) is blocked until they approve it.",
824
+ sdk: "required",
825
+ submitUrl: "https://developers.poki.com"
826
+ },
827
+ {
828
+ access: "review",
829
+ id: "gamedistribution",
830
+ integration: null,
831
+ limits: UNLIMITED,
832
+ name: "GameDistribution",
833
+ notes: "Reviewed, and their SDK is required in every game.",
834
+ sdk: "required",
835
+ submitUrl: "https://gamedistribution.com/developers"
836
+ },
837
+ {
838
+ access: "review",
839
+ id: "youtube",
840
+ integration: {
841
+ calls: ["firstFrameReady", "gameReady", "onPause", "onResume", "isAudioEnabled"],
842
+ csp: YOUTUBE_CSP,
843
+ script: "https://www.youtube.com/game_api/v1",
844
+ stub: "ytgame"
845
+ },
846
+ limits: {
847
+ fileName: /^[A-Za-z0-9_.-]+$/u,
848
+ maxExtractedBytes: 250 * MB,
849
+ maxFileBytes: 30 * MB,
850
+ maxFiles: 8e3,
851
+ maxPathLength: null,
852
+ maxZipBytes: null,
853
+ network: "restricted"
854
+ },
855
+ name: "YouTube Playables",
856
+ notes: "Invite-only early access: a channel YouTube has onboarded uploads through the Playables portal. The game must call YouTube's SDK, play sound only when YouTube allows, and reach no other host.",
857
+ sdk: "required",
858
+ submitUrl: "https://www.youtube.com/playables_portal"
859
+ }
860
+ ];
861
+
862
+ // src/lib/distribute/toolchain.ts
863
+ import { existsSync as existsSync3 } from "node:fs";
864
+ import { homedir } from "node:os";
865
+ import path3 from "node:path";
866
+ var STUDIO_JDK = "/Applications/Android Studio.app/Contents/jbr/Contents/Home";
867
+ var androidSdkDir = (env) => {
868
+ const candidates = [
869
+ env.ANDROID_HOME,
870
+ env.ANDROID_SDK_ROOT,
871
+ path3.join(homedir(), "Library/Android/sdk"),
872
+ path3.join(homedir(), "Android/Sdk")
873
+ ];
874
+ return candidates.find((dir) => dir !== void 0 && existsSync3(dir)) ?? null;
875
+ };
876
+ var iosMissing = async () => {
877
+ if (process.platform !== "darwin") {
878
+ return ["An iOS build needs a Mac with Xcode; this machine can only prepare the project."];
879
+ }
880
+ const xcode = await run("xcodebuild", ["-version"]);
881
+ return xcode.code === 0 ? [] : [
882
+ "Xcode is not installed or not selected: install it, then `sudo xcode-select -s /Applications/Xcode.app`."
883
+ ];
884
+ };
885
+ var androidMissing = async (env) => {
886
+ const missing = [];
887
+ const hasJavaHome = env.JAVA_HOME !== void 0 && existsSync3(env.JAVA_HOME);
888
+ const java = hasJavaHome ? null : await run("java", ["-version"]);
889
+ if (java !== null && java.code !== 0) {
890
+ missing.push(
891
+ existsSync3(STUDIO_JDK) ? `No JDK on PATH. Android Studio ships one: export JAVA_HOME="${STUDIO_JDK}"` : "No JDK: install JDK 21 (or Android Studio, which bundles one) and set JAVA_HOME."
892
+ );
893
+ }
894
+ const sdk = androidSdkDir(env);
895
+ if (sdk === null) {
896
+ missing.push("No Android SDK: install Android Studio, or set ANDROID_HOME to an SDK.");
897
+ } else if (env.ANDROID_HOME === void 0 && env.ANDROID_SDK_ROOT === void 0) {
898
+ missing.push(`Android SDK found but not exported: export ANDROID_HOME="${sdk}"`);
899
+ }
900
+ return missing;
901
+ };
902
+ var checkToolchain = async (platform, env = process.env) => {
903
+ const missing = platform === "ios" ? await iosMissing() : await androidMissing(env);
904
+ return missing.length === 0 ? { ready: true } : { missing, ready: false };
905
+ };
906
+
907
+ // src/lib/distribute/preview.ts
908
+ import { createServer } from "node:http";
909
+
910
+ // ../../node_modules/.pnpm/fflate@0.8.3/node_modules/fflate/esm/index.mjs
911
+ import { createRequire } from "module";
912
+ var require2 = createRequire("/");
913
+ var _a;
914
+ var Worker;
915
+ var isMarkedAsUntransferable;
916
+ try {
917
+ _a = require2("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
918
+ } catch (e) {
919
+ }
920
+ var u8 = Uint8Array;
921
+ var u16 = Uint16Array;
922
+ var i32 = Int32Array;
923
+ var fleb = new u8([
924
+ 0,
925
+ 0,
926
+ 0,
927
+ 0,
928
+ 0,
929
+ 0,
930
+ 0,
931
+ 0,
932
+ 1,
933
+ 1,
934
+ 1,
935
+ 1,
936
+ 2,
937
+ 2,
938
+ 2,
939
+ 2,
940
+ 3,
941
+ 3,
942
+ 3,
943
+ 3,
944
+ 4,
945
+ 4,
946
+ 4,
947
+ 4,
948
+ 5,
949
+ 5,
950
+ 5,
951
+ 5,
952
+ 0,
953
+ /* unused */
954
+ 0,
955
+ 0,
956
+ /* impossible */
957
+ 0
958
+ ]);
959
+ var fdeb = new u8([
960
+ 0,
961
+ 0,
962
+ 0,
963
+ 0,
964
+ 1,
965
+ 1,
966
+ 2,
967
+ 2,
968
+ 3,
969
+ 3,
970
+ 4,
971
+ 4,
972
+ 5,
973
+ 5,
974
+ 6,
975
+ 6,
976
+ 7,
977
+ 7,
978
+ 8,
979
+ 8,
980
+ 9,
981
+ 9,
982
+ 10,
983
+ 10,
984
+ 11,
985
+ 11,
986
+ 12,
987
+ 12,
988
+ 13,
989
+ 13,
990
+ /* unused */
991
+ 0,
992
+ 0
993
+ ]);
994
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
995
+ var freb = function(eb, start) {
996
+ var b = new u16(31);
997
+ for (var i2 = 0; i2 < 31; ++i2) {
998
+ b[i2] = start += 1 << eb[i2 - 1];
999
+ }
1000
+ var r = new i32(b[30]);
1001
+ for (var i2 = 1; i2 < 30; ++i2) {
1002
+ for (var j = b[i2]; j < b[i2 + 1]; ++j) {
1003
+ r[j] = j - b[i2] << 5 | i2;
1004
+ }
1005
+ }
1006
+ return { b, r };
1007
+ };
1008
+ var _a = freb(fleb, 2);
1009
+ var fl = _a.b;
1010
+ var revfl = _a.r;
1011
+ fl[28] = 258, revfl[258] = 28;
1012
+ var _b = freb(fdeb, 0);
1013
+ var fd = _b.b;
1014
+ var revfd = _b.r;
1015
+ var rev = new u16(32768);
1016
+ for (i = 0; i < 32768; ++i) {
1017
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
1018
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
1019
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
1020
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
1021
+ }
1022
+ var x;
1023
+ var i;
1024
+ var hMap = (function(cd, mb, r) {
1025
+ var s = cd.length;
1026
+ var i2 = 0;
1027
+ var l = new u16(mb);
1028
+ for (; i2 < s; ++i2) {
1029
+ if (cd[i2])
1030
+ ++l[cd[i2] - 1];
1031
+ }
1032
+ var le = new u16(mb);
1033
+ for (i2 = 1; i2 < mb; ++i2) {
1034
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
1035
+ }
1036
+ var co;
1037
+ if (r) {
1038
+ co = new u16(1 << mb);
1039
+ var rvb = 15 - mb;
1040
+ for (i2 = 0; i2 < s; ++i2) {
1041
+ if (cd[i2]) {
1042
+ var sv = i2 << 4 | cd[i2];
1043
+ var r_1 = mb - cd[i2];
1044
+ var v = le[cd[i2] - 1]++ << r_1;
1045
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
1046
+ co[rev[v] >> rvb] = sv;
1047
+ }
1048
+ }
1049
+ }
1050
+ } else {
1051
+ co = new u16(s);
1052
+ for (i2 = 0; i2 < s; ++i2) {
1053
+ if (cd[i2]) {
1054
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
1055
+ }
1056
+ }
1057
+ }
1058
+ return co;
1059
+ });
1060
+ var flt = new u8(288);
1061
+ for (i = 0; i < 144; ++i)
1062
+ flt[i] = 8;
1063
+ var i;
1064
+ for (i = 144; i < 256; ++i)
1065
+ flt[i] = 9;
1066
+ var i;
1067
+ for (i = 256; i < 280; ++i)
1068
+ flt[i] = 7;
1069
+ var i;
1070
+ for (i = 280; i < 288; ++i)
1071
+ flt[i] = 8;
1072
+ var i;
1073
+ var fdt = new u8(32);
1074
+ for (i = 0; i < 32; ++i)
1075
+ fdt[i] = 5;
1076
+ var i;
1077
+ var flm = /* @__PURE__ */ hMap(flt, 9, 0);
1078
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
1079
+ var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
1080
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
1081
+ var max = function(a) {
1082
+ var m = a[0];
1083
+ for (var i2 = 1; i2 < a.length; ++i2) {
1084
+ if (a[i2] > m)
1085
+ m = a[i2];
1086
+ }
1087
+ return m;
1088
+ };
1089
+ var bits = function(d, p, m) {
1090
+ var o = p / 8 | 0;
1091
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
1092
+ };
1093
+ var bits16 = function(d, p) {
1094
+ var o = p / 8 | 0;
1095
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
1096
+ };
1097
+ var shft = function(p) {
1098
+ return (p + 7) / 8 | 0;
1099
+ };
1100
+ var slc = function(v, s, e) {
1101
+ if (s == null || s < 0)
1102
+ s = 0;
1103
+ if (e == null || e > v.length)
1104
+ e = v.length;
1105
+ return new u8(v.subarray(s, e));
1106
+ };
1107
+ var ec = [
1108
+ "unexpected EOF",
1109
+ "invalid block type",
1110
+ "invalid length/literal",
1111
+ "invalid distance",
1112
+ "stream finished",
1113
+ "no stream handler",
1114
+ ,
1115
+ // determined by compression function
1116
+ "no callback",
1117
+ "invalid UTF-8 data",
1118
+ "extra field too long",
1119
+ "date not in range 1980-2099",
1120
+ "filename too long",
1121
+ "stream finishing",
1122
+ "invalid zip data"
1123
+ // determined by unknown compression method
1124
+ ];
1125
+ var err = function(ind, msg, nt) {
1126
+ var e = new Error(msg || ec[ind]);
1127
+ e.code = ind;
1128
+ if (Error.captureStackTrace)
1129
+ Error.captureStackTrace(e, err);
1130
+ if (!nt)
1131
+ throw e;
1132
+ return e;
1133
+ };
1134
+ var inflt = function(dat, st, buf, dict) {
1135
+ var sl = dat.length, dl = dict ? dict.length : 0;
1136
+ if (!sl || st.f && !st.l)
1137
+ return buf || new u8(0);
1138
+ var noBuf = !buf;
1139
+ var resize = noBuf || st.i != 2;
1140
+ var noSt = st.i;
1141
+ if (noBuf)
1142
+ buf = new u8(sl * 3);
1143
+ var cbuf = function(l2) {
1144
+ var bl = buf.length;
1145
+ if (l2 > bl) {
1146
+ var nbuf = new u8(Math.max(bl * 2, l2));
1147
+ nbuf.set(buf);
1148
+ buf = nbuf;
1149
+ }
1150
+ };
1151
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
1152
+ var tbts = sl * 8;
1153
+ do {
1154
+ if (!lm) {
1155
+ final = bits(dat, pos, 1);
1156
+ var type = bits(dat, pos + 1, 3);
1157
+ pos += 3;
1158
+ if (!type) {
1159
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
1160
+ if (t > sl) {
1161
+ if (noSt)
1162
+ err(0);
1163
+ break;
1164
+ }
1165
+ if (resize)
1166
+ cbuf(bt + l);
1167
+ buf.set(dat.subarray(s, t), bt);
1168
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
1169
+ continue;
1170
+ } else if (type == 1)
1171
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
1172
+ else if (type == 2) {
1173
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
1174
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
1175
+ pos += 14;
1176
+ var ldt = new u8(tl);
1177
+ var clt = new u8(19);
1178
+ for (var i2 = 0; i2 < hcLen; ++i2) {
1179
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
1180
+ }
1181
+ pos += hcLen * 3;
1182
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
1183
+ var clm = hMap(clt, clb, 1);
1184
+ for (var i2 = 0; i2 < tl; ) {
1185
+ var r = clm[bits(dat, pos, clbmsk)];
1186
+ pos += r & 15;
1187
+ var s = r >> 4;
1188
+ if (s < 16) {
1189
+ ldt[i2++] = s;
1190
+ } else {
1191
+ var c = 0, n = 0;
1192
+ if (s == 16)
1193
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
1194
+ else if (s == 17)
1195
+ n = 3 + bits(dat, pos, 7), pos += 3;
1196
+ else if (s == 18)
1197
+ n = 11 + bits(dat, pos, 127), pos += 7;
1198
+ while (n--)
1199
+ ldt[i2++] = c;
1200
+ }
1201
+ }
1202
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
1203
+ lbt = max(lt);
1204
+ dbt = max(dt);
1205
+ lm = hMap(lt, lbt, 1);
1206
+ dm = hMap(dt, dbt, 1);
1207
+ } else
1208
+ err(1);
1209
+ if (pos > tbts) {
1210
+ if (noSt)
1211
+ err(0);
1212
+ break;
1213
+ }
1214
+ }
1215
+ if (resize)
1216
+ cbuf(bt + 131072);
1217
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
1218
+ var lpos = pos;
1219
+ for (; ; lpos = pos) {
1220
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
1221
+ pos += c & 15;
1222
+ if (pos > tbts) {
1223
+ if (noSt)
1224
+ err(0);
1225
+ break;
1226
+ }
1227
+ if (!c)
1228
+ err(2);
1229
+ if (sym < 256)
1230
+ buf[bt++] = sym;
1231
+ else if (sym == 256) {
1232
+ lpos = pos, lm = null;
1233
+ break;
1234
+ } else {
1235
+ var add = sym - 254;
1236
+ if (sym > 264) {
1237
+ var i2 = sym - 257, b = fleb[i2];
1238
+ add = bits(dat, pos, (1 << b) - 1) + fl[i2];
1239
+ pos += b;
1240
+ }
1241
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
1242
+ if (!d)
1243
+ err(3);
1244
+ pos += d & 15;
1245
+ var dt = fd[dsym];
1246
+ if (dsym > 3) {
1247
+ var b = fdeb[dsym];
1248
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
1249
+ }
1250
+ if (pos > tbts) {
1251
+ if (noSt)
1252
+ err(0);
1253
+ break;
1254
+ }
1255
+ if (resize)
1256
+ cbuf(bt + 131072);
1257
+ var end = bt + add;
1258
+ if (bt < dt) {
1259
+ var shift = dl - dt, dend = Math.min(dt, end);
1260
+ if (shift + bt < 0)
1261
+ err(3);
1262
+ for (; bt < dend; ++bt)
1263
+ buf[bt] = dict[shift + bt];
1264
+ }
1265
+ for (; bt < end; ++bt)
1266
+ buf[bt] = buf[bt - dt];
1267
+ }
1268
+ }
1269
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
1270
+ if (lm)
1271
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
1272
+ } while (!final);
1273
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
1274
+ };
1275
+ var wbits = function(d, p, v) {
1276
+ v <<= p & 7;
1277
+ var o = p / 8 | 0;
1278
+ d[o] |= v;
1279
+ d[o + 1] |= v >> 8;
1280
+ };
1281
+ var wbits16 = function(d, p, v) {
1282
+ v <<= p & 7;
1283
+ var o = p / 8 | 0;
1284
+ d[o] |= v;
1285
+ d[o + 1] |= v >> 8;
1286
+ d[o + 2] |= v >> 16;
1287
+ };
1288
+ var hTree = function(d, mb) {
1289
+ var t = [];
1290
+ for (var i2 = 0; i2 < d.length; ++i2) {
1291
+ if (d[i2])
1292
+ t.push({ s: i2, f: d[i2] });
1293
+ }
1294
+ var s = t.length;
1295
+ var t2 = t.slice();
1296
+ if (!s)
1297
+ return { t: et, l: 0 };
1298
+ if (s == 1) {
1299
+ var v = new u8(t[0].s + 1);
1300
+ v[t[0].s] = 1;
1301
+ return { t: v, l: 1 };
1302
+ }
1303
+ t.sort(function(a, b) {
1304
+ return a.f - b.f;
1305
+ });
1306
+ t.push({ s: -1, f: 25001 });
1307
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
1308
+ t[0] = { s: -1, f: l.f + r.f, l, r };
1309
+ while (i1 != s - 1) {
1310
+ l = t[t[i0].f < t[i22].f ? i0++ : i22++];
1311
+ r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
1312
+ t[i1++] = { s: -1, f: l.f + r.f, l, r };
1313
+ }
1314
+ var maxSym = t2[0].s;
1315
+ for (var i2 = 1; i2 < s; ++i2) {
1316
+ if (t2[i2].s > maxSym)
1317
+ maxSym = t2[i2].s;
1318
+ }
1319
+ var tr = new u16(maxSym + 1);
1320
+ var mbt = ln(t[i1 - 1], tr, 0);
1321
+ if (mbt > mb) {
1322
+ var i2 = 0, dt = 0;
1323
+ var lft = mbt - mb, cst = 1 << lft;
1324
+ t2.sort(function(a, b) {
1325
+ return tr[b.s] - tr[a.s] || a.f - b.f;
1326
+ });
1327
+ for (; i2 < s; ++i2) {
1328
+ var i2_1 = t2[i2].s;
1329
+ if (tr[i2_1] > mb) {
1330
+ dt += cst - (1 << mbt - tr[i2_1]);
1331
+ tr[i2_1] = mb;
1332
+ } else
1333
+ break;
1334
+ }
1335
+ dt >>= lft;
1336
+ while (dt > 0) {
1337
+ var i2_2 = t2[i2].s;
1338
+ if (tr[i2_2] < mb)
1339
+ dt -= 1 << mb - tr[i2_2]++ - 1;
1340
+ else
1341
+ ++i2;
1342
+ }
1343
+ for (; i2 >= 0 && dt; --i2) {
1344
+ var i2_3 = t2[i2].s;
1345
+ if (tr[i2_3] == mb) {
1346
+ --tr[i2_3];
1347
+ ++dt;
1348
+ }
1349
+ }
1350
+ mbt = mb;
1351
+ }
1352
+ return { t: new u8(tr), l: mbt };
1353
+ };
1354
+ var ln = function(n, l, d) {
1355
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
1356
+ };
1357
+ var lc = function(c) {
1358
+ var s = c.length;
1359
+ while (s && !c[--s])
1360
+ ;
1361
+ var cl = new u16(++s);
1362
+ var cli = 0, cln = c[0], cls = 1;
1363
+ var w = function(v) {
1364
+ cl[cli++] = v;
1365
+ };
1366
+ for (var i2 = 1; i2 <= s; ++i2) {
1367
+ if (c[i2] == cln && i2 != s)
1368
+ ++cls;
1369
+ else {
1370
+ if (!cln && cls > 2) {
1371
+ for (; cls > 138; cls -= 138)
1372
+ w(32754);
1373
+ if (cls > 2) {
1374
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
1375
+ cls = 0;
1376
+ }
1377
+ } else if (cls > 3) {
1378
+ w(cln), --cls;
1379
+ for (; cls > 6; cls -= 6)
1380
+ w(8304);
1381
+ if (cls > 2)
1382
+ w(cls - 3 << 5 | 8208), cls = 0;
1383
+ }
1384
+ while (cls--)
1385
+ w(cln);
1386
+ cls = 1;
1387
+ cln = c[i2];
1388
+ }
1389
+ }
1390
+ return { c: cl.subarray(0, cli), n: s };
1391
+ };
1392
+ var clen = function(cf, cl) {
1393
+ var l = 0;
1394
+ for (var i2 = 0; i2 < cl.length; ++i2)
1395
+ l += cf[i2] * cl[i2];
1396
+ return l;
1397
+ };
1398
+ var wfblk = function(out, pos, dat) {
1399
+ var s = dat.length;
1400
+ var o = shft(pos + 2);
1401
+ out[o] = s & 255;
1402
+ out[o + 1] = s >> 8;
1403
+ out[o + 2] = out[o] ^ 255;
1404
+ out[o + 3] = out[o + 1] ^ 255;
1405
+ for (var i2 = 0; i2 < s; ++i2)
1406
+ out[o + i2 + 4] = dat[i2];
1407
+ return (o + 4 + s) * 8;
1408
+ };
1409
+ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
1410
+ wbits(out, p++, final);
1411
+ ++lf[256];
1412
+ var _a2 = hTree(lf, 15), dlt = _a2.t, mlb = _a2.l;
1413
+ var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
1414
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
1415
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
1416
+ var lcfreq = new u16(19);
1417
+ for (var i2 = 0; i2 < lclt.length; ++i2)
1418
+ ++lcfreq[lclt[i2] & 31];
1419
+ for (var i2 = 0; i2 < lcdt.length; ++i2)
1420
+ ++lcfreq[lcdt[i2] & 31];
1421
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
1422
+ var nlcc = 19;
1423
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
1424
+ ;
1425
+ var flen = bl + 5 << 3;
1426
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
1427
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
1428
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen)
1429
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
1430
+ var lm, ll, dm, dl;
1431
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
1432
+ if (dtlen < ftlen) {
1433
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
1434
+ var llm = hMap(lct, mlcb, 0);
1435
+ wbits(out, p, nlc - 257);
1436
+ wbits(out, p + 5, ndc - 1);
1437
+ wbits(out, p + 10, nlcc - 4);
1438
+ p += 14;
1439
+ for (var i2 = 0; i2 < nlcc; ++i2)
1440
+ wbits(out, p + 3 * i2, lct[clim[i2]]);
1441
+ p += 3 * nlcc;
1442
+ var lcts = [lclt, lcdt];
1443
+ for (var it = 0; it < 2; ++it) {
1444
+ var clct = lcts[it];
1445
+ for (var i2 = 0; i2 < clct.length; ++i2) {
1446
+ var len = clct[i2] & 31;
1447
+ wbits(out, p, llm[len]), p += lct[len];
1448
+ if (len > 15)
1449
+ wbits(out, p, clct[i2] >> 5 & 127), p += clct[i2] >> 12;
1450
+ }
1451
+ }
1452
+ } else {
1453
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
1454
+ }
1455
+ for (var i2 = 0; i2 < li; ++i2) {
1456
+ var sym = syms[i2];
1457
+ if (sym > 255) {
1458
+ var len = sym >> 18 & 31;
1459
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
1460
+ if (len > 7)
1461
+ wbits(out, p, sym >> 23 & 31), p += fleb[len];
1462
+ var dst = sym & 31;
1463
+ wbits16(out, p, dm[dst]), p += dl[dst];
1464
+ if (dst > 3)
1465
+ wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
1466
+ } else {
1467
+ wbits16(out, p, lm[sym]), p += ll[sym];
1468
+ }
1469
+ }
1470
+ wbits16(out, p, lm[256]);
1471
+ return p + ll[256];
1472
+ };
1473
+ var deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
1474
+ var et = /* @__PURE__ */ new u8(0);
1475
+ var dflt = function(dat, lvl, plvl, pre, post, st) {
1476
+ var s = st.z || dat.length;
1477
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post);
1478
+ var w = o.subarray(pre, o.length - post);
1479
+ var lst = st.l;
1480
+ var pos = (st.r || 0) & 7;
1481
+ if (lvl) {
1482
+ if (pos)
1483
+ w[0] = st.r >> 3;
1484
+ var opt = deo[lvl - 1];
1485
+ var n = opt >> 13, c = opt & 8191;
1486
+ var msk_1 = (1 << plvl) - 1;
1487
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
1488
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
1489
+ var hsh = function(i3) {
1490
+ return (dat[i3] ^ dat[i3 + 1] << bs1_1 ^ dat[i3 + 2] << bs2_1) & msk_1;
1491
+ };
1492
+ var syms = new i32(25e3);
1493
+ var lf = new u16(288), df = new u16(32);
1494
+ var lc_1 = 0, eb = 0, i2 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
1495
+ for (; i2 + 2 < s; ++i2) {
1496
+ var hv = hsh(i2);
1497
+ var imod = i2 & 32767, pimod = head[hv];
1498
+ prev[imod] = pimod;
1499
+ head[hv] = imod;
1500
+ if (wi <= i2) {
1501
+ var rem = s - i2;
1502
+ if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
1503
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i2 - bs, pos);
1504
+ li = lc_1 = eb = 0, bs = i2;
1505
+ for (var j = 0; j < 286; ++j)
1506
+ lf[j] = 0;
1507
+ for (var j = 0; j < 30; ++j)
1508
+ df[j] = 0;
1509
+ }
1510
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
1511
+ if (rem > 2 && hv == hsh(i2 - dif)) {
1512
+ var maxn = Math.min(n, rem) - 1;
1513
+ var maxd = Math.min(32767, i2);
1514
+ var ml = Math.min(258, rem);
1515
+ while (dif <= maxd && --ch_1 && imod != pimod) {
1516
+ if (dat[i2 + l] == dat[i2 + l - dif]) {
1517
+ var nl = 0;
1518
+ for (; nl < ml && dat[i2 + nl] == dat[i2 + nl - dif]; ++nl)
1519
+ ;
1520
+ if (nl > l) {
1521
+ l = nl, d = dif;
1522
+ if (nl > maxn)
1523
+ break;
1524
+ var mmd = Math.min(dif, nl - 2);
1525
+ var md = 0;
1526
+ for (var j = 0; j < mmd; ++j) {
1527
+ var ti = i2 - dif + j & 32767;
1528
+ var pti = prev[ti];
1529
+ var cd = ti - pti & 32767;
1530
+ if (cd > md)
1531
+ md = cd, pimod = ti;
1532
+ }
1533
+ }
1534
+ }
1535
+ imod = pimod, pimod = prev[imod];
1536
+ dif += imod - pimod & 32767;
1537
+ }
1538
+ }
1539
+ if (d) {
1540
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
1541
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
1542
+ eb += fleb[lin] + fdeb[din];
1543
+ ++lf[257 + lin];
1544
+ ++df[din];
1545
+ wi = i2 + l;
1546
+ ++lc_1;
1547
+ } else {
1548
+ syms[li++] = dat[i2];
1549
+ ++lf[dat[i2]];
1550
+ }
1551
+ }
1552
+ }
1553
+ for (i2 = Math.max(i2, wi); i2 < s; ++i2) {
1554
+ syms[li++] = dat[i2];
1555
+ ++lf[dat[i2]];
1556
+ }
1557
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i2 - bs, pos);
1558
+ if (!lst) {
1559
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
1560
+ pos -= 7;
1561
+ st.h = head, st.p = prev, st.i = i2, st.w = wi;
1562
+ }
1563
+ } else {
1564
+ for (var i2 = st.w || 0; i2 < s + lst; i2 += 65535) {
1565
+ var e = i2 + 65535;
1566
+ if (e >= s) {
1567
+ w[pos / 8 | 0] = lst;
1568
+ e = s;
1569
+ }
1570
+ pos = wfblk(w, pos + 1, dat.subarray(i2, e));
1571
+ }
1572
+ st.i = s;
1573
+ }
1574
+ return slc(o, 0, pre + shft(pos) + post);
1575
+ };
1576
+ var crct = /* @__PURE__ */ (function() {
1577
+ var t = new Int32Array(256);
1578
+ for (var i2 = 0; i2 < 256; ++i2) {
1579
+ var c = i2, k = 9;
1580
+ while (--k)
1581
+ c = (c & 1 && -306674912) ^ c >>> 1;
1582
+ t[i2] = c;
1583
+ }
1584
+ return t;
1585
+ })();
1586
+ var crc = function() {
1587
+ var c = -1;
1588
+ return {
1589
+ p: function(d) {
1590
+ var cr = c;
1591
+ for (var i2 = 0; i2 < d.length; ++i2)
1592
+ cr = crct[cr & 255 ^ d[i2]] ^ cr >>> 8;
1593
+ c = cr;
1594
+ },
1595
+ d: function() {
1596
+ return ~c;
1597
+ }
1598
+ };
1599
+ };
1600
+ var dopt = function(dat, opt, pre, post, st) {
1601
+ if (!st) {
1602
+ st = { l: 1 };
1603
+ if (opt.dictionary) {
1604
+ var dict = opt.dictionary.subarray(-32768);
1605
+ var newDat = new u8(dict.length + dat.length);
1606
+ newDat.set(dict);
1607
+ newDat.set(dat, dict.length);
1608
+ dat = newDat;
1609
+ st.w = dict.length;
1610
+ }
1611
+ }
1612
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
1613
+ };
1614
+ var mrg = function(a, b) {
1615
+ var o = {};
1616
+ for (var k in a)
1617
+ o[k] = a[k];
1618
+ for (var k in b)
1619
+ o[k] = b[k];
1620
+ return o;
1621
+ };
1622
+ var b2 = function(d, b) {
1623
+ return d[b] | d[b + 1] << 8;
1624
+ };
1625
+ var b4 = function(d, b) {
1626
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
1627
+ };
1628
+ var b8 = function(d, b) {
1629
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
1630
+ };
1631
+ var wbytes = function(d, b, v) {
1632
+ for (; v; ++b)
1633
+ d[b] = v, v >>>= 8;
1634
+ };
1635
+ function deflateSync(data, opts) {
1636
+ return dopt(data, opts || {}, 0, 0);
1637
+ }
1638
+ function inflateSync(data, opts) {
1639
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
1640
+ }
1641
+ var fltn = function(d, p, t, o) {
1642
+ for (var k in d) {
1643
+ var val = d[k], n = p + k, op = o;
1644
+ if (Array.isArray(val))
1645
+ op = mrg(o, val[1]), val = val[0];
1646
+ if (ArrayBuffer.isView(val))
1647
+ t[n] = [val, op];
1648
+ else {
1649
+ t[n += "/"] = [new u8(0), op];
1650
+ fltn(val, n, t, o);
1651
+ }
1652
+ }
1653
+ };
1654
+ var te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder();
1655
+ var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
1656
+ var tds = 0;
1657
+ try {
1658
+ td.decode(et, { stream: true });
1659
+ tds = 1;
1660
+ } catch (e) {
1661
+ }
1662
+ var dutf8 = function(d) {
1663
+ for (var r = "", i2 = 0; ; ) {
1664
+ var c = d[i2++];
1665
+ var eb = (c > 127) + (c > 223) + (c > 239);
1666
+ if (i2 + eb > d.length)
1667
+ return { s: r, r: slc(d, i2 - 1) };
1668
+ if (!eb)
1669
+ r += String.fromCharCode(c);
1670
+ else if (eb == 3) {
1671
+ c = ((c & 15) << 18 | (d[i2++] & 63) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
1672
+ } else if (eb & 1)
1673
+ r += String.fromCharCode((c & 31) << 6 | d[i2++] & 63);
1674
+ else
1675
+ r += String.fromCharCode((c & 15) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63);
1676
+ }
1677
+ };
1678
+ function strToU8(str, latin1) {
1679
+ if (latin1) {
1680
+ var ar_1 = new u8(str.length);
1681
+ for (var i2 = 0; i2 < str.length; ++i2)
1682
+ ar_1[i2] = str.charCodeAt(i2);
1683
+ return ar_1;
1684
+ }
1685
+ if (te)
1686
+ return te.encode(str);
1687
+ var l = str.length;
1688
+ var ar = new u8(str.length + (str.length >> 1));
1689
+ var ai = 0;
1690
+ var w = function(v) {
1691
+ ar[ai++] = v;
1692
+ };
1693
+ for (var i2 = 0; i2 < l; ++i2) {
1694
+ if (ai + 5 > ar.length) {
1695
+ var n = new u8(ai + 8 + (l - i2 << 1));
1696
+ n.set(ar);
1697
+ ar = n;
1698
+ }
1699
+ var c = str.charCodeAt(i2);
1700
+ if (c < 128 || latin1)
1701
+ w(c);
1702
+ else if (c < 2048)
1703
+ w(192 | c >> 6), w(128 | c & 63);
1704
+ else if (c > 55295 && c < 57344)
1705
+ c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i2) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);
1706
+ else
1707
+ w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
1708
+ }
1709
+ return slc(ar, 0, ai);
1710
+ }
1711
+ function strFromU8(dat, latin1) {
1712
+ if (latin1) {
1713
+ var r = "";
1714
+ for (var i2 = 0; i2 < dat.length; i2 += 16384)
1715
+ r += String.fromCharCode.apply(null, dat.subarray(i2, i2 + 16384));
1716
+ return r;
1717
+ } else if (td) {
1718
+ return td.decode(dat);
1719
+ } else {
1720
+ var _a2 = dutf8(dat), s = _a2.s, r = _a2.r;
1721
+ if (r.length)
1722
+ err(8);
1723
+ return s;
1724
+ }
1725
+ }
1726
+ var slzh = function(d, b) {
1727
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
1728
+ };
1729
+ var zh = function(d, b, z) {
1730
+ var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;
1731
+ var _a2 = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a2[0], su = _a2[1], off = _a2[2];
1732
+ return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];
1733
+ };
1734
+ var z64hs = function(d, b, l, z, sc, su, off) {
1735
+ var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;
1736
+ var nf = nsc + nsu + noff;
1737
+ if (z && nf) {
1738
+ for (; b + 4 < e; b += 4 + b2(d, b + 2)) {
1739
+ if (b2(d, b) == 1) {
1740
+ return [
1741
+ nsc ? b8(d, b + 4 + 8 * nsu) : sc,
1742
+ nsu ? b8(d, b + 4) : su,
1743
+ noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,
1744
+ 1
1745
+ ];
1746
+ }
1747
+ }
1748
+ if (z < 2)
1749
+ err(13);
1750
+ }
1751
+ return [sc, su, off, 0];
1752
+ };
1753
+ var exfl = function(ex) {
1754
+ var le = 0;
1755
+ if (ex) {
1756
+ for (var k in ex) {
1757
+ var l = ex[k].length;
1758
+ if (l > 65535)
1759
+ err(9);
1760
+ le += l + 4;
1761
+ }
1762
+ }
1763
+ return le;
1764
+ };
1765
+ var wzh = function(d, b, f, fn, u, c, ce, co) {
1766
+ var fl2 = fn.length, ex = f.extra, col = co && co.length;
1767
+ var exl = exfl(ex);
1768
+ wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
1769
+ if (ce != null)
1770
+ d[b++] = 20, d[b++] = f.os;
1771
+ d[b] = 20, b += 2;
1772
+ d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
1773
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
1774
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
1775
+ if (y < 0 || y > 119)
1776
+ err(10);
1777
+ wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
1778
+ if (c != -1) {
1779
+ wbytes(d, b, f.crc);
1780
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
1781
+ wbytes(d, b + 8, f.size);
1782
+ }
1783
+ wbytes(d, b + 12, fl2);
1784
+ wbytes(d, b + 14, exl), b += 16;
1785
+ if (ce != null) {
1786
+ wbytes(d, b, col);
1787
+ wbytes(d, b + 6, f.attrs);
1788
+ wbytes(d, b + 10, ce), b += 14;
1789
+ }
1790
+ d.set(fn, b);
1791
+ b += fl2;
1792
+ if (exl) {
1793
+ for (var k in ex) {
1794
+ var exf = ex[k], l = exf.length;
1795
+ wbytes(d, b, +k);
1796
+ wbytes(d, b + 2, l);
1797
+ d.set(exf, b + 4), b += 4 + l;
1798
+ }
1799
+ }
1800
+ if (col)
1801
+ d.set(co, b), b += col;
1802
+ return b;
1803
+ };
1804
+ var wzf = function(o, b, c, d, e) {
1805
+ wbytes(o, b, 101010256);
1806
+ wbytes(o, b + 8, c);
1807
+ wbytes(o, b + 10, c);
1808
+ wbytes(o, b + 12, d);
1809
+ wbytes(o, b + 16, e);
1810
+ };
1811
+ function zipSync(data, opts) {
1812
+ if (!opts)
1813
+ opts = {};
1814
+ var r = {};
1815
+ var files = [];
1816
+ fltn(data, "", r, opts);
1817
+ var o = 0;
1818
+ var tot = 0;
1819
+ for (var fn in r) {
1820
+ var _a2 = r[fn], file = _a2[0], p = _a2[1];
1821
+ var compression = p.level == 0 ? 0 : 8;
1822
+ var f = strToU8(fn), s = f.length;
1823
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
1824
+ var exl = exfl(p.extra);
1825
+ if (s > 65535)
1826
+ err(11);
1827
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
1828
+ var c = crc();
1829
+ c.p(file);
1830
+ files.push(mrg(p, {
1831
+ size: file.length,
1832
+ crc: c.d(),
1833
+ c: d,
1834
+ f,
1835
+ m,
1836
+ u: s != fn.length || m && com.length != ms,
1837
+ o,
1838
+ compression
1839
+ }));
1840
+ o += 30 + s + exl + l;
1841
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
1842
+ }
1843
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
1844
+ for (var i2 = 0; i2 < files.length; ++i2) {
1845
+ var f = files[i2];
1846
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
1847
+ var badd = 30 + f.f.length + exfl(f.extra);
1848
+ out.set(f.c, f.o + badd);
1849
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
1850
+ }
1851
+ wzf(out, o, files.length, cdl, oe);
1852
+ return out;
1853
+ }
1854
+ function unzipSync(data, opts) {
1855
+ var files = {};
1856
+ var e = data.length - 22;
1857
+ for (; b4(data, e) != 101010256; --e) {
1858
+ if (!e || data.length - e > 65558)
1859
+ err(13);
1860
+ }
1861
+ ;
1862
+ var c = b2(data, e + 8);
1863
+ if (!c)
1864
+ return {};
1865
+ var o = b4(data, e + 16);
1866
+ var z = b4(data, e - 20) == 117853008;
1867
+ if (z) {
1868
+ var ze = b4(data, e - 12);
1869
+ z = b4(data, ze) == 101075792;
1870
+ if (z) {
1871
+ c = b4(data, ze + 32);
1872
+ o = b4(data, ze + 48);
1873
+ }
1874
+ }
1875
+ var fltr = opts && opts.filter;
1876
+ for (var i2 = 0; i2 < c; ++i2) {
1877
+ var _a2 = zh(data, o, z), c_2 = _a2[0], sc = _a2[1], su = _a2[2], fn = _a2[3], no = _a2[4], off = _a2[5], b = slzh(data, off);
1878
+ o = no;
1879
+ if (!fltr || fltr({
1880
+ name: fn,
1881
+ size: sc,
1882
+ originalSize: su,
1883
+ compression: c_2
1884
+ })) {
1885
+ if (!c_2)
1886
+ files[fn] = slc(data, b, b + sc);
1887
+ else if (c_2 == 8)
1888
+ files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
1889
+ else
1890
+ err(14, "unknown compression type " + c_2);
1891
+ }
1892
+ }
1893
+ return files;
1894
+ }
1895
+
1896
+ // src/lib/distribute/ytgame-stub.ts
1897
+ var YTGAME_STUB = String.raw`(() => {
1898
+ const log = { calls: [], errors: [], save: null };
1899
+ const listeners = { pause: [], resume: [], audio: [] };
1900
+ let audio = true;
1901
+ let firstFrame = false;
1902
+ const report = () => parent.postMessage({ type: "vg-ytgame-log", log }, "*");
1903
+ const record = (name, detail) => {
1904
+ log.calls.push(detail === undefined ? name : name + " " + JSON.stringify(detail));
1905
+ report();
1906
+ };
1907
+ const fail = (message) => {
1908
+ log.errors.push(message);
1909
+ report();
1910
+ };
1911
+ const subscribe = (kind, name) => (callback) => {
1912
+ record(name);
1913
+ listeners[kind].push(callback);
1914
+ return () => {
1915
+ listeners[kind] = listeners[kind].filter((c) => c !== callback);
1916
+ };
1917
+ };
1918
+ let loaded = false;
1919
+ window.__ytgameStub = log;
1920
+ window.ytgame = {
1921
+ IN_PLAYABLES_ENV: true,
1922
+ SDK_VERSION: "vg-preview-stub",
1923
+ ads: {
1924
+ requestInterstitialAd: () => (record("ads.requestInterstitialAd"), Promise.resolve()),
1925
+ requestRewardedAd: (id) => (record("ads.requestRewardedAd", id), Promise.resolve(true)),
1926
+ },
1927
+ engagement: {
1928
+ sendScore: (score) => (record("engagement.sendScore", score), Promise.resolve()),
1929
+ },
1930
+ game: {
1931
+ firstFrameReady: () => {
1932
+ if (firstFrame) fail("firstFrameReady called more than once");
1933
+ firstFrame = true;
1934
+ record("game.firstFrameReady");
1935
+ },
1936
+ gameReady: () => {
1937
+ if (!firstFrame) fail("gameReady called before firstFrameReady");
1938
+ record("game.gameReady");
1939
+ },
1940
+ loadData: () => {
1941
+ loaded = true;
1942
+ record("game.loadData");
1943
+ return Promise.resolve(log.save ?? "");
1944
+ },
1945
+ saveData: (data) => {
1946
+ if (!loaded) fail("saveData called before loadData resolved");
1947
+ if (data.length * 2 > 3 * 1024 * 1024) fail("saveData over 3 MiB");
1948
+ log.save = data;
1949
+ record("game.saveData", data.length + " chars");
1950
+ return Promise.resolve();
1951
+ },
1952
+ },
1953
+ health: {
1954
+ logError: () => record("health.logError"),
1955
+ logWarning: () => record("health.logWarning"),
1956
+ },
1957
+ system: {
1958
+ getLanguage: () => (record("system.getLanguage"), Promise.resolve("en")),
1959
+ isAudioEnabled: () => (record("system.isAudioEnabled"), audio),
1960
+ onAudioEnabledChange: subscribe("audio", "system.onAudioEnabledChange"),
1961
+ onPause: subscribe("pause", "system.onPause"),
1962
+ onResume: subscribe("resume", "system.onResume"),
1963
+ },
1964
+ };
1965
+ addEventListener("message", (event) => {
1966
+ const data = event.data;
1967
+ if (event.source !== parent || !data || data.type !== "vg-ytgame") return;
1968
+ if (data.action === "pause") listeners.pause.forEach((c) => c());
1969
+ if (data.action === "resume") listeners.resume.forEach((c) => c());
1970
+ if (data.action === "audio") {
1971
+ audio = Boolean(data.enabled);
1972
+ listeners.audio.forEach((c) => c(audio));
1973
+ }
1974
+ record("preview." + data.action, data.action === "audio" ? audio : undefined);
1975
+ });
1976
+ addEventListener("error", (event) => fail("page error: " + event.message));
1977
+ addEventListener("securitypolicyviolation", (event) =>
1978
+ fail("blocked by the portal's CSP: " + event.violatedDirective + " " + event.blockedURI),
1979
+ );
1980
+ })();
1981
+ `;
1982
+
1983
+ // src/lib/distribute/preview.ts
1984
+ var GAME_PATH = "/play/";
1985
+ var STUB_PATH = "/__vg/sdk.js";
1986
+ var PAGE_CSS = "body{margin:0;display:grid;grid-template-rows:auto 1fr;height:100vh;font:13px ui-monospace,monospace;background:#111;color:#ddd}header{display:flex;gap:8px;align-items:center;padding:8px;flex-wrap:wrap}button{font:inherit;padding:4px 10px}iframe{border:0;width:100%;height:100%;background:#000}pre{margin:0;max-height:30vh;overflow:auto;white-space:pre-wrap}";
1987
+ var previewPage = (portal, gameUrl) => {
1988
+ const controls = portal.integration === null ? "" : `<button data-a="pause">YouTube pause</button><button data-a="resume">YouTube resume</button><button data-a="audio-off">Audio off</button><button data-a="audio-on">Audio on</button><pre id="log"></pre>`;
1989
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1990
+ <title>${portal.name} preview</title><style>${PAGE_CSS}</style></head><body>
1991
+ <header><strong>${portal.name} preview</strong>${controls}</header>
1992
+ <iframe id="game" src="${gameUrl}" allow="autoplay; fullscreen; gamepad"></iframe>
1993
+ <script>
1994
+ const frame = document.getElementById("game");
1995
+ const send = (action, enabled) => frame.contentWindow.postMessage({ type: "vg-ytgame", action, enabled }, "*");
1996
+ window.vgPreview = {
1997
+ log: { calls: [], errors: [], save: null },
1998
+ pause: () => send("pause"),
1999
+ resume: () => send("resume"),
2000
+ setAudio: (enabled) => send("audio", enabled),
2001
+ };
2002
+ addEventListener("message", (event) => {
2003
+ if (event.source !== frame.contentWindow || !event.data || event.data.type !== "vg-ytgame-log") return;
2004
+ window.vgPreview.log = event.data.log;
2005
+ const out = document.getElementById("log");
2006
+ if (out) out.textContent = [...event.data.log.errors.map((e) => "ERROR " + e), ...event.data.log.calls.slice(-8)].join("\\n");
2007
+ });
2008
+ for (const button of document.querySelectorAll("button[data-a]")) {
2009
+ button.addEventListener("click", () => {
2010
+ const a = button.dataset.a;
2011
+ if (a === "audio-on" || a === "audio-off") send("audio", a === "audio-on");
2012
+ else send(a);
2013
+ });
2014
+ }
2015
+ </script></body></html>`;
2016
+ };
2017
+ var listen = (server, port, host) => (
2018
+ // oxlint-disable-next-line promise/avoid-new -- node:http's listen is callback-based
2019
+ new Promise((resolve, reject) => {
2020
+ server.once("error", reject);
2021
+ server.listen(port, host, () => resolve());
2022
+ })
2023
+ );
2024
+ var closeServer = (server) => (
2025
+ // oxlint-disable-next-line promise/avoid-new -- node:http's close is callback-based
2026
+ new Promise((resolve) => {
2027
+ server.close(() => resolve());
2028
+ server.closeAllConnections();
2029
+ })
2030
+ );
2031
+ var send = (res, status, type, body, headers = {}) => {
2032
+ res.writeHead(status, { "cache-control": "no-store", "content-type": type, ...headers });
2033
+ res.end(body);
2034
+ };
2035
+ var startPreview = async ({ zip, portal, port }) => {
2036
+ const files = unzipSync(zip);
2037
+ if (!("index.html" in files)) {
2038
+ throw new Error("The zip has no index.html at its root.");
2039
+ }
2040
+ const { integration } = portal;
2041
+ const decoder = new TextDecoder();
2042
+ const serveGame = (req, res) => {
2043
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
2044
+ if (integration !== null && url.pathname === STUB_PATH) {
2045
+ send(res, 200, "text/javascript; charset=utf-8", YTGAME_STUB);
2046
+ return;
2047
+ }
2048
+ if (!url.pathname.startsWith(GAME_PATH)) {
2049
+ send(res, 404, "text/plain", "Not in the game's folder.");
2050
+ return;
2051
+ }
2052
+ const relative = decodeURIComponent(url.pathname.slice(GAME_PATH.length)) || "index.html";
2053
+ const body = files[relative];
2054
+ if (body === void 0) {
2055
+ send(res, 404, "text/plain", `${relative} is not in the zip.`);
2056
+ return;
2057
+ }
2058
+ if (relative !== "index.html") {
2059
+ send(res, 200, contentTypeForPath(relative), body);
2060
+ return;
2061
+ }
2062
+ if (integration === null) {
2063
+ send(res, 200, "text/html; charset=utf-8", body);
2064
+ return;
2065
+ }
2066
+ const html = decoder.decode(body).replaceAll(integration.script, STUB_PATH);
2067
+ send(res, 200, "text/html; charset=utf-8", html, {
2068
+ "content-security-policy": integration.csp
2069
+ });
2070
+ };
2071
+ const gameUrl = `http://127.0.0.1:${port}${GAME_PATH}index.html`;
2072
+ const page = previewPage(portal, gameUrl);
2073
+ const game = createServer(serveGame);
2074
+ const host = createServer((_req, res) => send(res, 200, "text/html; charset=utf-8", page));
2075
+ try {
2076
+ await listen(game, port, "127.0.0.1");
2077
+ await listen(host, port + 1, "localhost");
2078
+ } catch (error) {
2079
+ await closeServer(game);
2080
+ const reason = error instanceof Error ? error.message : String(error);
2081
+ throw new Error(`Could not listen on ports ${port}-${port + 1} (${reason}). Pass --port.`, {
2082
+ cause: error
2083
+ });
2084
+ }
2085
+ return {
2086
+ close: async () => {
2087
+ await Promise.all([closeServer(game), closeServer(host)]);
2088
+ },
2089
+ gameUrl,
2090
+ url: `http://localhost:${port + 1}/`
2091
+ };
2092
+ };
2093
+
2094
+ // src/lib/distribute/sdk-script.ts
2095
+ var withSdkScript = (html, script) => {
2096
+ if (html.includes(`src="${script}"`) || html.includes(`src='${script}'`)) {
2097
+ return html;
2098
+ }
2099
+ const tag = `<script src="${script}"></script>`;
2100
+ const head = /<head(?:\s[^>]*)?>/iu.exec(html);
2101
+ if (head !== null) {
2102
+ const at = head.index + head[0].length;
2103
+ return `${html.slice(0, at)}
2104
+ ${tag}${html.slice(at)}`;
2105
+ }
2106
+ const firstScript = html.search(/<script\b/iu);
2107
+ return firstScript === -1 ? `${tag}
2108
+ ${html}` : `${html.slice(0, firstScript)}${tag}
2109
+ ${html.slice(firstScript)}`;
2110
+ };
2111
+
2112
+ // src/lib/distribute/zip.ts
2113
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
2114
+ import path4 from "node:path";
2115
+ var STORED = /\.(?:png|jpe?g|webp|avif|gif|mp3|ogg|m4a|aac|mp4|webm|woff2?|br|gz|zip|ktx2)$/iu;
2116
+ var ENTRY_TIME = new Date(1980, 0, 1);
2117
+ var writeZip = (entries, outFile, overrides = /* @__PURE__ */ new Map()) => {
2118
+ const tree = {};
2119
+ for (const entry of entries) {
2120
+ tree[entry.path] = [
2121
+ overrides.get(entry.path) ?? readFileSync3(entry.absolutePath),
2122
+ { level: STORED.test(entry.path) ? 0 : 9, mtime: ENTRY_TIME }
2123
+ ];
2124
+ }
2125
+ const archive = zipSync(tree);
2126
+ mkdirSync2(path4.dirname(outFile), { recursive: true });
2127
+ writeFileSync3(outFile, archive);
2128
+ return { bytes: archive.byteLength };
2129
+ };
2130
+
2131
+ // src/commands/distribute.ts
2132
+ var OUT_DIR = "distribute";
2133
+ var fail = (message) => {
2134
+ consola.error(message);
2135
+ process.exit(1);
2136
+ };
2137
+ var narrator = (args) => isJsonOutput(args) || Boolean(args.field) ? () => {
2138
+ } : (message) => consola.info(message);
2139
+ var formatBytes2 = (bytes) => bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2140
+ var requireBuild = (dir) => {
2141
+ if (!existsSync4(dir)) {
2142
+ return fail(`Directory does not exist: ${dir}`);
2143
+ }
2144
+ const build = resolveBuildDir(dir);
2145
+ if (build.kind === "unbuilt") {
2146
+ return fail(
2147
+ "This project has no build output (dist/, build/ or out/). Run its build first: the source index.html references files only the dev server can serve."
2148
+ );
2149
+ }
2150
+ return build.dir;
2151
+ };
2152
+ var printFindings = (findings) => {
2153
+ for (const finding of findings) {
2154
+ const detail = finding.paths ? `
2155
+ ${finding.paths.slice(0, 10).join("\n ")}` : "";
2156
+ const line = `[${finding.id}] ${finding.message}${detail}`;
2157
+ if (finding.level === "error") {
2158
+ consola.error(line);
2159
+ } else {
2160
+ consola.warn(line);
2161
+ }
2162
+ }
2163
+ };
2164
+ var DEFAULT_PREVIEW_PORT = 8471;
2165
+ var portalArgs = {
2166
+ dir: {
2167
+ default: ".",
2168
+ description: "The project, or its build output",
2169
+ required: false,
2170
+ type: "positional"
2171
+ },
2172
+ out: {
2173
+ description: `Where to write the zip (default: ${OUT_DIR}/<slug>-<platform>.zip in the project).`,
2174
+ type: "string"
2175
+ },
2176
+ port: {
2177
+ default: String(DEFAULT_PREVIEW_PORT),
2178
+ description: "With --preview: the game's port; the page framing it takes the next one.",
2179
+ type: "string"
2180
+ },
2181
+ preview: {
2182
+ default: false,
2183
+ description: "Then serve the zip the way the platform does (unpacked under a folder, framed from another origin, under its CSP, with a stand-in for its SDK) until stopped.",
2184
+ type: "boolean"
2185
+ },
2186
+ ...outputArgs
2187
+ };
2188
+ var webProject = (dir) => {
2189
+ try {
2190
+ return readDistributeProject(dir);
2191
+ } catch {
2192
+ return { root: dir, slug: path5.basename(dir) };
2193
+ }
2194
+ };
2195
+ var sdkFinding2 = (portal) => portal.sdk === "required" && portal.integration === null ? [
2196
+ {
2197
+ id: "sdk-required",
2198
+ level: "warning",
2199
+ message: `${portal.name} only accepts games with its SDK built in. This command packs the build as it is; integrate the SDK first.`
2200
+ }
2201
+ ] : [];
2202
+ var packagedOverrides = (portal, buildDir) => {
2203
+ const overrides = /* @__PURE__ */ new Map();
2204
+ if (portal.integration !== null) {
2205
+ const html = readFileSync4(path5.join(buildDir, "index.html"), "utf-8");
2206
+ overrides.set(
2207
+ "index.html",
2208
+ new TextEncoder().encode(withSdkScript(html, portal.integration.script))
2209
+ );
2210
+ }
2211
+ return overrides;
2212
+ };
2213
+ var overZipLimit = (portal, bytes) => portal.limits.maxZipBytes !== null && bytes > portal.limits.maxZipBytes ? [
2214
+ {
2215
+ id: "zip-too-large",
2216
+ level: "error",
2217
+ message: `The zip is ${formatBytes2(bytes)}; ${portal.name} accepts ${formatBytes2(portal.limits.maxZipBytes)}.`
2218
+ }
2219
+ ] : [];
2220
+ var parsePort = (raw) => {
2221
+ const port = Number(raw);
2222
+ if (!Number.isInteger(port) || port < 1024 || port > 65534) {
2223
+ return fail("--port must be a whole number from 1024 to 65534.");
2224
+ }
2225
+ return port;
2226
+ };
2227
+ var pack = (portal, dirArg, outArg) => {
2228
+ const dir = path5.resolve(dirArg);
2229
+ const buildDir = requireBuild(dir);
2230
+ const project = webProject(dir);
2231
+ const outFile = path5.resolve(
2232
+ outArg ?? path5.join(project.root, OUT_DIR, `${project.slug}-${portal.id}.zip`)
2233
+ );
2234
+ const outDir = `${path5.dirname(outFile)}${path5.sep}`;
2235
+ const files = buildManifest(buildDir).filter((file) => !file.absolutePath.startsWith(outDir));
2236
+ const input = {
2237
+ files,
2238
+ readText: (file) => readFileSync4(path5.join(buildDir, file), "utf-8")
2239
+ };
2240
+ const findings = [
2241
+ ...auditBuild({ ...input, limits: portal.limits, sdk: portal.integration }),
2242
+ ...sdkFinding2(portal)
2243
+ ];
2244
+ let bytes = null;
2245
+ if (!findings.some((finding) => finding.level === "error")) {
2246
+ ({ bytes } = writeZip(files, outFile, packagedOverrides(portal, buildDir)));
2247
+ const tooLarge = overZipLimit(portal, bytes);
2248
+ if (tooLarge.length > 0) {
2249
+ rmSync2(outFile, { force: true });
2250
+ bytes = null;
2251
+ findings.push(...tooLarge);
2252
+ }
2253
+ }
2254
+ return {
2255
+ bytes,
2256
+ extracted_bytes: files.reduce((sum, file) => sum + file.size, 0),
2257
+ files: files.length,
2258
+ findings: findings.map((finding) => ({ ...finding, paths: finding.paths ?? [] })),
2259
+ hosts: remoteHosts(input),
2260
+ ok: bytes !== null,
2261
+ platform: portal.id,
2262
+ submit_url: portal.submitUrl,
2263
+ zip: bytes === null ? null : outFile
2264
+ };
2265
+ };
2266
+ var printPack = (portal, result, previewing) => {
2267
+ printFindings(result.findings);
2268
+ if (result.zip === null || result.bytes === null) {
2269
+ return;
2270
+ }
2271
+ consola.success(`${result.zip} (${result.files} files, ${formatBytes2(result.bytes)})`);
2272
+ if (!previewing) {
2273
+ consola.info(`Try it as ${portal.name} serves it: vg distribute ${portal.id} --preview`);
2274
+ }
2275
+ if (portal.submitUrl !== null) {
2276
+ consola.info(`Upload it at ${portal.submitUrl}`);
2277
+ }
2278
+ if (result.hosts.length > 0) {
2279
+ consola.info(`The game reaches: ${result.hosts.join(", ")}`);
2280
+ }
2281
+ };
2282
+ var servePreview = async (portal, zip, port) => {
2283
+ let preview;
2284
+ try {
2285
+ preview = await startPreview({ port, portal, zip: readFileSync4(zip) });
2286
+ } catch (error) {
2287
+ return fail(error instanceof Error ? error.message : String(error));
2288
+ }
2289
+ const stop = async () => {
2290
+ await preview.close();
2291
+ process.exit(0);
2292
+ };
2293
+ process.once("SIGINT", stop);
2294
+ process.once("SIGTERM", stop);
2295
+ return { game_url: preview.gameUrl, sdk_stub: portal.integration !== null, url: preview.url };
2296
+ };
2297
+ var portalCommand = (portal) => defineCommand({
2298
+ args: portalArgs,
2299
+ meta: {
2300
+ description: portal.id === "web" ? "Pack the build as a zip for any web host or portal not listed here." : `Pack the zip ${portal.name} takes, checked against the rules it publishes.`,
2301
+ name: portal.id
2302
+ },
2303
+ run: async ({ args, rawArgs }) => {
2304
+ assertKnownFlags(rawArgs, portalArgs);
2305
+ const port = args.preview ? parsePort(args.port) : null;
2306
+ const result = pack(portal, args.dir, args.out);
2307
+ if (result.zip === null || port === null) {
2308
+ if (!writeStructured(result, args)) {
2309
+ printPack(portal, result, false);
2310
+ }
2311
+ if (!result.ok) {
2312
+ process.exit(1);
2313
+ }
2314
+ return;
2315
+ }
2316
+ const preview = await servePreview(portal, result.zip, port);
2317
+ const served = { game_url: preview.game_url, sdk_stub: preview.sdk_stub, url: preview.url };
2318
+ if (writeStructured({ ...result, preview: served }, args)) {
2319
+ return;
2320
+ }
2321
+ printPack(portal, result, true);
2322
+ consola.success(`Preview: ${preview.url}, framed from another origin`);
2323
+ if (preview.sdk_stub) {
2324
+ consola.info(
2325
+ "The SDK is a stand-in: window.vgPreview on that page holds its call log (log.calls, log.errors) and pause(), resume(), setAudio(bool)."
2326
+ );
2327
+ }
2328
+ consola.info("Stop with Ctrl-C.");
2329
+ }
2330
+ });
2331
+ var nativeArgs = {
2332
+ "app-id": {
2333
+ description: "Reverse-DNS app id, e.g. com.yourstudio.game. Saved to vibedgames.json; permanent once the app is in a store.",
2334
+ type: "string"
2335
+ },
2336
+ dir: {
2337
+ default: ".",
2338
+ description: "The project (the folder holding vibedgames.json)",
2339
+ required: false,
2340
+ type: "positional"
2341
+ },
2342
+ ...outputArgs
2343
+ };
2344
+ var NEXT_STEPS = {
2345
+ android: [
2346
+ "npx cap run android",
2347
+ "npx cap build android --androidreleasetype AAB --keystorepath <keystore> --keystorepass <pass> --keystorealias <alias> --keystorealiaspass <pass>"
2348
+ ],
2349
+ ios: ["npx cap run ios", "npx cap open ios"]
2350
+ };
2351
+ var requireNative = (dir, appId) => {
2352
+ if (appId !== void 0) {
2353
+ if (!APP_ID_RE.test(appId)) {
2354
+ return fail(`--app-id must be a reverse-DNS id such as com.yourstudio.game, not "${appId}".`);
2355
+ }
2356
+ try {
2357
+ writeDistributeFields(readDistributeProject(dir).root, { appId });
2358
+ } catch (error) {
2359
+ return fail(error instanceof Error ? error.message : String(error));
2360
+ }
2361
+ }
2362
+ try {
2363
+ const project = readDistributeProject(dir);
2364
+ if (project.native === null) {
2365
+ return fail(
2366
+ `No app id yet. It is the app's permanent identity in the store, so choose it deliberately:
2367
+ vg distribute <platform> --app-id com.yourstudio.${project.slug.replaceAll("-", "")}`
2368
+ );
2369
+ }
2370
+ return { native: project.native, project };
2371
+ } catch (error) {
2372
+ return fail(error instanceof Error ? error.message : String(error));
2373
+ }
2374
+ };
2375
+ var nativeCommand = (platform, store) => defineCommand({
2376
+ args: nativeArgs,
2377
+ meta: {
2378
+ description: `Wrap the build in a native ${platform === "ios" ? "iOS" : "Android"} app for ${store}, generated from vibedgames.json. Run it again after every build.`,
2379
+ name: platform
2380
+ },
2381
+ run: async ({ args, rawArgs }) => {
2382
+ assertKnownFlags(rawArgs, nativeArgs);
2383
+ const say = narrator(args);
2384
+ const dir = path5.resolve(args.dir);
2385
+ const { project, native } = requireNative(dir, args["app-id"]);
2386
+ const buildDir = requireBuild(project.root);
2387
+ let shell;
2388
+ try {
2389
+ shell = await prepareShell({ buildDir, native, platform, project, say });
2390
+ } catch (error) {
2391
+ return fail(error instanceof Error ? error.message : String(error));
2392
+ }
2393
+ const toolchain = await checkToolchain(platform);
2394
+ const result = {
2395
+ app_id: native.appId,
2396
+ build: native.build,
2397
+ icon: shell.icon,
2398
+ next: NEXT_STEPS[platform],
2399
+ platform,
2400
+ project: path5.join(project.root, shell.project),
2401
+ toolchain_missing: toolchain.ready ? [] : toolchain.missing,
2402
+ version: native.version
2403
+ };
2404
+ if (writeStructured(result, args)) {
2405
+ return;
2406
+ }
2407
+ consola.success(`${result.project} \u2014 ${native.appId} ${native.version} (${native.build})`);
2408
+ if (!shell.icon) {
2409
+ consola.warn(
2410
+ "Still the placeholder icon, which no store accepts. Add a square 1024px icon.png to the project (or set distribute.icon) and run this again."
2411
+ );
2412
+ }
2413
+ for (const missing of result.toolchain_missing) {
2414
+ consola.warn(missing);
2415
+ }
2416
+ consola.info(`Next:
2417
+ ${result.next.join("\n ")}`);
2418
+ }
2419
+ });
2420
+ var targetsArgs = { ...outputArgs };
2421
+ var targetsCommand = defineCommand({
2422
+ args: targetsArgs,
2423
+ meta: {
2424
+ description: "List where a game can go: each portal's limits, and whether this machine can build each store's app.",
2425
+ name: "targets"
2426
+ },
2427
+ run: async ({ args, rawArgs }) => {
2428
+ assertKnownFlags(rawArgs, targetsArgs);
2429
+ const stores = await Promise.all(
2430
+ PLATFORMS.map(async (platform) => {
2431
+ const toolchain = await checkToolchain(platform);
2432
+ return { missing: toolchain.ready ? [] : toolchain.missing, platform };
2433
+ })
2434
+ );
2435
+ const portals = PORTALS.map((portal) => ({
2436
+ access: portal.access,
2437
+ id: portal.id,
2438
+ limits: {
2439
+ max_extracted_bytes: portal.limits.maxExtractedBytes,
2440
+ max_file_bytes: portal.limits.maxFileBytes,
2441
+ max_files: portal.limits.maxFiles,
2442
+ max_path_length: portal.limits.maxPathLength,
2443
+ max_zip_bytes: portal.limits.maxZipBytes,
2444
+ network: portal.limits.network
2445
+ },
2446
+ name: portal.name,
2447
+ notes: portal.notes,
2448
+ sdk: portal.sdk,
2449
+ submit_url: portal.submitUrl
2450
+ }));
2451
+ if (writeStructured({ portals, stores }, args)) {
2452
+ return;
2453
+ }
2454
+ for (const portal of portals) {
2455
+ consola.log(`${portal.id.padEnd(18)} ${portal.name} \u2014 ${portal.notes}`);
2456
+ }
2457
+ for (const store of stores) {
2458
+ consola.log(
2459
+ `${store.platform.padEnd(18)} ${store.missing.length === 0 ? "ready to build" : store.missing.join(" ")}`
2460
+ );
2461
+ }
2462
+ }
2463
+ });
2464
+ var distributeCommand = defineCommand({
2465
+ meta: {
2466
+ description: `Package a built game for one platform other than vibedgames: ${[...PORTALS.map((portal) => portal.id), ...PLATFORMS].join(", ")}. \`vg distribute targets\` lists each one's rules.`,
2467
+ name: "distribute"
2468
+ },
2469
+ subCommands: {
2470
+ ...Object.fromEntries(PORTALS.map((portal) => [portal.id, portalCommand(portal)])),
2471
+ android: nativeCommand("android", "Google Play"),
2472
+ ios: nativeCommand("ios", "the App Store"),
2473
+ targets: targetsCommand
2474
+ }
2475
+ });
2476
+ export {
2477
+ distributeCommand
2478
+ };