@air-jam/cli 0.0.0-stage → 1.0.0-beta.1

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 (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +273 -2
  3. package/bin/airjam.mjs +66 -0
  4. package/dist/ai-pack.d.ts +44 -0
  5. package/dist/ai-pack.js +15 -0
  6. package/dist/ai-pack.js.map +1 -0
  7. package/dist/auth-profile.d.ts +5 -0
  8. package/dist/auth-profile.js +7 -0
  9. package/dist/auth-profile.js.map +1 -0
  10. package/dist/auth-sessions.d.ts +5 -0
  11. package/dist/auth-sessions.js +7 -0
  12. package/dist/auth-sessions.js.map +1 -0
  13. package/dist/chunk-7D4AYBAV.js +64 -0
  14. package/dist/chunk-7D4AYBAV.js.map +1 -0
  15. package/dist/chunk-J5MAU4QZ.js +102 -0
  16. package/dist/chunk-J5MAU4QZ.js.map +1 -0
  17. package/dist/chunk-LH7UO57C.js +23 -0
  18. package/dist/chunk-LH7UO57C.js.map +1 -0
  19. package/dist/chunk-N7AI7HZK.js +529 -0
  20. package/dist/chunk-N7AI7HZK.js.map +1 -0
  21. package/dist/chunk-PKTLVQXZ.js +82 -0
  22. package/dist/chunk-PKTLVQXZ.js.map +1 -0
  23. package/dist/chunk-SQE4NPZP.js +31 -0
  24. package/dist/chunk-SQE4NPZP.js.map +1 -0
  25. package/dist/chunk-U6V3HEBB.js +939 -0
  26. package/dist/chunk-U6V3HEBB.js.map +1 -0
  27. package/dist/chunk-VEHNFPEO.js +224 -0
  28. package/dist/chunk-VEHNFPEO.js.map +1 -0
  29. package/dist/development.d.ts +102 -0
  30. package/dist/development.js +33 -0
  31. package/dist/development.js.map +1 -0
  32. package/dist/documentation.d.ts +27 -0
  33. package/dist/documentation.js +7 -0
  34. package/dist/documentation.js.map +1 -0
  35. package/dist/game-analytics.d.ts +5 -0
  36. package/dist/game-analytics.js +7 -0
  37. package/dist/game-analytics.js.map +1 -0
  38. package/dist/game-app-id.d.ts +5 -0
  39. package/dist/game-app-id.js +7 -0
  40. package/dist/game-app-id.js.map +1 -0
  41. package/dist/game-media.d.ts +5 -0
  42. package/dist/game-media.js +7 -0
  43. package/dist/game-media.js.map +1 -0
  44. package/dist/index.d.ts +1 -0
  45. package/dist/index.js +2468 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/scaffold.d.ts +6 -0
  48. package/dist/scaffold.js +20 -0
  49. package/dist/scaffold.js.map +1 -0
  50. package/package.json +82 -3
  51. package/runtime/local-network.d.mts +6 -0
  52. package/runtime/local-network.mjs +9 -0
  53. package/runtime/public-assets.mjs +62 -0
  54. package/runtime/source-fence.mjs +182 -0
  55. package/runtime/vite-config.d.mts +43 -0
  56. package/runtime/vite-config.mjs +134 -0
  57. package/runtime/vite-dev.mjs +18 -0
  58. package/runtime/vite-https.d.mts +11 -0
  59. package/runtime/vite-https.mjs +40 -0
  60. package/template-assets/bootstrap/.claude/launch.json +12 -0
  61. package/template-assets/bootstrap/AGENTS.md +290 -0
  62. package/template-assets/bootstrap/CLAUDE.md +55 -0
  63. package/template-assets/bootstrap/_gitignore +6 -0
  64. package/template-assets/bootstrap/skills/airjam-docs-workflow/SKILL.md +49 -0
  65. package/template-assets/bootstrap/skills/airjam-mcp/SKILL.md +100 -0
  66. package/template-assets/bootstrap/skills/canvas-2d-gameplay/SKILL.md +47 -0
  67. package/template-assets/bootstrap/skills/controller-ui/SKILL.md +71 -0
  68. package/template-assets/bootstrap/skills/debug-and-test/SKILL.md +72 -0
  69. package/template-assets/bootstrap/skills/game-architecture/SKILL.md +102 -0
  70. package/template-assets/bootstrap/skills/game-state-and-rendering/SKILL.md +44 -0
  71. package/template-assets/bootstrap/skills/host-surface/SKILL.md +52 -0
  72. package/template-assets/bootstrap/skills/index.md +36 -0
  73. package/template-assets/bootstrap/skills/prefab-authoring/SKILL.md +58 -0
  74. package/template-assets/bootstrap/skills/r3f-3d-scene/SKILL.md +61 -0
  75. package/template-assets/documentation/for-agents/controller-ui/page.mdx +99 -0
  76. package/template-assets/documentation/for-agents/page.mdx +120 -0
  77. package/template-assets/documentation/for-agents/project-structure/page.mdx +170 -0
  78. package/template-assets/documentation/for-agents/state-and-rendering/page.mdx +77 -0
  79. package/template-assets/documentation/for-agents/supported-agents/page.mdx +18 -0
  80. package/template-assets/documentation/getting-started/debugging/page.mdx +164 -0
  81. package/template-assets/documentation/getting-started/dev-logs/page.mdx +169 -0
  82. package/template-assets/documentation/getting-started/game-ideas/page.mdx +114 -0
  83. package/template-assets/documentation/getting-started/introduction/page.mdx +200 -0
  84. package/template-assets/documentation/getting-started/migrating-legacy-games/page.mdx +673 -0
  85. package/template-assets/documentation/getting-started/quick-start/page.mdx +310 -0
  86. package/template-assets/documentation/how-it-works/architecture/page.mdx +230 -0
  87. package/template-assets/documentation/how-it-works/host-system/page.mdx +270 -0
  88. package/template-assets/documentation/manifest.json +500 -0
  89. package/template-assets/documentation/sdk/assets-and-theme/page.mdx +185 -0
  90. package/template-assets/documentation/sdk/hooks/page.mdx +435 -0
  91. package/template-assets/documentation/sdk/input-system/page.mdx +240 -0
  92. package/template-assets/documentation/sdk/networked-state/page.mdx +295 -0
  93. package/template-assets/documentation/sdk/settings/page.mdx +155 -0
  94. package/template-assets/documentation/sdk/ui-components/page.mdx +268 -0
  95. package/template-assets/managed/.airjam/ai-pack.json +209 -0
  96. package/template-assets/managed/docs/airjam/agent-gold-path.md +115 -0
  97. package/template-assets/managed/docs/airjam/agent-mcp.md +179 -0
  98. package/template-assets/managed/docs/airjam/canvas-2d-gameplay.md +82 -0
  99. package/template-assets/managed/docs/airjam/composition-shell-contract.md +87 -0
  100. package/template-assets/managed/docs/airjam/debug-and-testing.md +104 -0
  101. package/template-assets/managed/docs/airjam/development-loop.md +51 -0
  102. package/template-assets/managed/docs/airjam/docs-index.md +64 -0
  103. package/template-assets/managed/docs/airjam/generated/architecture.md +223 -0
  104. package/template-assets/managed/docs/airjam/generated/assets-and-theme.md +188 -0
  105. package/template-assets/managed/docs/airjam/generated/controller-ui.md +102 -0
  106. package/template-assets/managed/docs/airjam/generated/debugging-and-logs.md +165 -0
  107. package/template-assets/managed/docs/airjam/generated/for-agents.md +123 -0
  108. package/template-assets/managed/docs/airjam/generated/game-ideas.md +107 -0
  109. package/template-assets/managed/docs/airjam/generated/host-system.md +261 -0
  110. package/template-assets/managed/docs/airjam/generated/input-system.md +241 -0
  111. package/template-assets/managed/docs/airjam/generated/introduction.md +195 -0
  112. package/template-assets/managed/docs/airjam/generated/migrating-legacy-games.md +674 -0
  113. package/template-assets/managed/docs/airjam/generated/networked-state.md +298 -0
  114. package/template-assets/managed/docs/airjam/generated/project-structure.md +171 -0
  115. package/template-assets/managed/docs/airjam/generated/quick-start.md +311 -0
  116. package/template-assets/managed/docs/airjam/generated/sdk-hooks.md +430 -0
  117. package/template-assets/managed/docs/airjam/generated/settings.md +158 -0
  118. package/template-assets/managed/docs/airjam/generated/state-and-rendering.md +80 -0
  119. package/template-assets/managed/docs/airjam/generated/supported-agents.md +21 -0
  120. package/template-assets/managed/docs/airjam/generated/ui-components.md +265 -0
  121. package/template-assets/managed/docs/airjam/generated/unified-dev-logs.md +170 -0
  122. package/template-assets/managed/docs/airjam/iconography.md +55 -0
  123. package/template-assets/managed/docs/airjam/prefab-authoring.md +212 -0
  124. package/template-assets/managed/docs/airjam/preview-controllers.md +129 -0
  125. package/template-assets/managed/docs/airjam/r3f-3d-scene.md +163 -0
  126. package/template-assets/managed/docs/airjam/state-lanes-cookbook.md +101 -0
  127. package/template-assets/managed/docs/airjam/visual-system.md +103 -0
@@ -0,0 +1,939 @@
1
+ // runtime/dev-utils.mjs
2
+ import crossSpawn from "cross-spawn";
3
+ import { execFileSync } from "child_process";
4
+ import fs from "fs";
5
+ import net from "net";
6
+ import os from "os";
7
+ var isPortOpen = (port) => new Promise((resolve) => {
8
+ const socket = net.createConnection({ port, host: "127.0.0.1" });
9
+ const done = (value) => {
10
+ socket.removeAllListeners();
11
+ socket.destroy();
12
+ resolve(value);
13
+ };
14
+ socket.setTimeout(400);
15
+ socket.on("connect", () => done(true));
16
+ socket.on("timeout", () => done(false));
17
+ socket.on("error", () => done(false));
18
+ });
19
+ var waitForPort = (port, timeoutMs) => new Promise((resolve, reject) => {
20
+ const start = Date.now();
21
+ const tryConnect = () => {
22
+ const socket = net.createConnection({ port, host: "127.0.0.1" });
23
+ socket.on("connect", () => {
24
+ socket.end();
25
+ resolve(true);
26
+ });
27
+ socket.on("error", () => {
28
+ socket.destroy();
29
+ if (Date.now() - start > timeoutMs) {
30
+ reject(new Error(`Timed out waiting for localhost:${port}`));
31
+ return;
32
+ }
33
+ setTimeout(tryConnect, 300);
34
+ });
35
+ };
36
+ tryConnect();
37
+ });
38
+ var loadEnvFile = (filePath, env = process.env) => {
39
+ if (!fs.existsSync(filePath)) {
40
+ return;
41
+ }
42
+ const content = fs.readFileSync(filePath, "utf8");
43
+ for (const rawLine of content.split("\n")) {
44
+ const line = rawLine.trim();
45
+ if (!line || line.startsWith("#")) {
46
+ continue;
47
+ }
48
+ const eq = line.indexOf("=");
49
+ if (eq <= 0) {
50
+ continue;
51
+ }
52
+ const key = line.slice(0, eq).trim();
53
+ const value = line.slice(eq + 1).trim();
54
+ if (!env[key]) {
55
+ env[key] = value;
56
+ }
57
+ }
58
+ };
59
+ var isPrivateIpv4 = (ip) => ip.startsWith("10.") || ip.startsWith("192.168.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip);
60
+ var isVirtualInterface = (name) => /^(lo|docker|br-|veth|vbox|vmnet|utun|gif|stf|awdl|llw)/i.test(name);
61
+ var scoreIp = (ip) => {
62
+ if (ip.startsWith("192.168.")) {
63
+ const parts = ip.split(".");
64
+ const third = Number(parts[2] ?? "0");
65
+ return third < 64 ? 300 - third : 200 - third;
66
+ }
67
+ if (ip.startsWith("10.")) {
68
+ return 150;
69
+ }
70
+ if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip)) {
71
+ return 100;
72
+ }
73
+ return 0;
74
+ };
75
+ var detectLocalIpv4 = () => {
76
+ const networks = os.networkInterfaces();
77
+ const candidates = [];
78
+ for (const [name, entries] of Object.entries(networks)) {
79
+ if (!entries || isVirtualInterface(name)) {
80
+ continue;
81
+ }
82
+ for (const entry of entries) {
83
+ if (!entry || entry.internal || entry.family !== "IPv4") {
84
+ continue;
85
+ }
86
+ const ip = entry.address;
87
+ if (!isPrivateIpv4(ip) || ip.startsWith("169.254.")) {
88
+ continue;
89
+ }
90
+ candidates.push({ ip, score: scoreIp(ip) });
91
+ }
92
+ }
93
+ candidates.sort((a, b) => b.score - a.score);
94
+ return candidates[0]?.ip ?? null;
95
+ };
96
+ var getFlagValue = (argv, flag) => {
97
+ const inlineArg = argv.find((arg) => arg.startsWith(`${flag}=`));
98
+ if (inlineArg) {
99
+ return inlineArg.slice(flag.length + 1);
100
+ }
101
+ const index = argv.indexOf(flag);
102
+ return index === -1 ? null : argv[index + 1] ?? null;
103
+ };
104
+ var hasFlag = (argv, flag) => argv.includes(flag);
105
+ var upsertEnv = (filePath, key, value) => {
106
+ let content = "";
107
+ if (fs.existsSync(filePath)) {
108
+ content = fs.readFileSync(filePath, "utf8");
109
+ }
110
+ const nextLine = `${key}=${value}`;
111
+ const pattern = new RegExp(`^${key}=.*$`, "m");
112
+ if (pattern.test(content)) {
113
+ content = content.replace(pattern, nextLine);
114
+ } else {
115
+ content += `${content.endsWith("\n") || content.length === 0 ? "" : "\n"}${nextLine}
116
+ `;
117
+ }
118
+ fs.writeFileSync(filePath, content, "utf8");
119
+ };
120
+ var commandExists = (command, args = ["--version"]) => {
121
+ try {
122
+ execFileSync(command, args, {
123
+ encoding: "utf8",
124
+ stdio: ["ignore", "pipe", "pipe"]
125
+ });
126
+ return true;
127
+ } catch {
128
+ return false;
129
+ }
130
+ };
131
+ var logChunk = (prefix, data) => {
132
+ const text = data.toString();
133
+ for (const line of text.split("\n")) {
134
+ if (!line.trim()) {
135
+ continue;
136
+ }
137
+ console.log(`[${prefix}] ${line}`);
138
+ }
139
+ };
140
+ var createProcessGroup = () => {
141
+ const children = [];
142
+ let isShuttingDown = false;
143
+ const shutdown = (code = 0) => {
144
+ if (isShuttingDown) {
145
+ return;
146
+ }
147
+ isShuttingDown = true;
148
+ for (const child of children) {
149
+ if (!child.killed) {
150
+ child.kill("SIGTERM");
151
+ }
152
+ }
153
+ setTimeout(() => process.exit(code), 100);
154
+ };
155
+ const run2 = (name, command, args, options = {}) => {
156
+ const { fatal = true, ...spawnOptions } = options;
157
+ const child = crossSpawn(command, args, {
158
+ stdio: ["inherit", "pipe", "pipe"],
159
+ ...spawnOptions
160
+ });
161
+ child.stdout.on("data", (data) => logChunk(name, data));
162
+ child.stderr.on("data", (data) => logChunk(name, data));
163
+ child.on("error", (error) => {
164
+ console.error(`[${name}] failed to start: ${error.message}`);
165
+ shutdown(1);
166
+ });
167
+ child.on("exit", (code, signal) => {
168
+ if (!fatal) {
169
+ return;
170
+ }
171
+ if (code === 0 || signal === "SIGTERM") {
172
+ return;
173
+ }
174
+ console.error(`[${name}] exited with code ${code ?? "null"}`);
175
+ shutdown(code ?? 1);
176
+ });
177
+ children.push(child);
178
+ return child;
179
+ };
180
+ const registerSignalHandlers = () => {
181
+ process.on("SIGINT", () => shutdown(0));
182
+ process.on("SIGTERM", () => shutdown(0));
183
+ };
184
+ return {
185
+ run: run2,
186
+ shutdown,
187
+ registerSignalHandlers
188
+ };
189
+ };
190
+
191
+ // runtime/runtime-topology.mjs
192
+ import {
193
+ resolveProjectRuntimeTopology,
194
+ resolveRuntimeTopology,
195
+ serializeRuntimeTopology
196
+ } from "@air-jam/sdk/runtime-topology";
197
+
198
+ // runtime/vite-https.mjs
199
+ import fs2 from "fs";
200
+
201
+ // runtime/local-network.mjs
202
+ var DEFAULT_AIR_JAM_SERVER_PORT = 4e3;
203
+ var resolveLocalBackendOrigin = (env = {}) => {
204
+ const explicitOrigin = env.VITE_AIR_JAM_SERVER_URL?.trim();
205
+ return explicitOrigin || `http://127.0.0.1:${env.AIR_JAM_SERVER_PORT ?? DEFAULT_AIR_JAM_SERVER_PORT}`;
206
+ };
207
+
208
+ // runtime/vite-https.mjs
209
+ var DEFAULT_AIR_JAM_DEV_BACKEND_URL = resolveLocalBackendOrigin();
210
+
211
+ // runtime/runtime-topology.mjs
212
+ var normalizeAssetBasePath = (runtimeUrl) => {
213
+ const parsed = new URL(runtimeUrl);
214
+ if (parsed.pathname.startsWith("/airjam-local-builds/")) {
215
+ const [, localBuilds, gameId] = parsed.pathname.split("/");
216
+ return `/${localBuilds}/${gameId}`;
217
+ }
218
+ return "/";
219
+ };
220
+ var buildStandaloneGameTopology = ({
221
+ surfaceRole,
222
+ publicHost,
223
+ secureTransport = false,
224
+ backendOrigin = DEFAULT_AIR_JAM_DEV_BACKEND_URL
225
+ }) => resolveProjectRuntimeTopology({
226
+ runtimeMode: secureTransport ? "standalone-secure" : "standalone-dev",
227
+ surfaceRole,
228
+ appOrigin: publicHost,
229
+ backendOrigin,
230
+ publicHost,
231
+ secureTransport
232
+ });
233
+ var buildPlatformShellTopology = ({
234
+ runtimeMode,
235
+ surfaceRole,
236
+ appOrigin,
237
+ publicHost,
238
+ backendOrigin = DEFAULT_AIR_JAM_DEV_BACKEND_URL,
239
+ secureTransport = false
240
+ }) => resolveRuntimeTopology({
241
+ runtimeMode,
242
+ surfaceRole,
243
+ appOrigin,
244
+ backendOrigin,
245
+ publicHost,
246
+ proxyStrategy: "platform-proxy",
247
+ secureTransport
248
+ });
249
+ var buildEmbeddedGameTopology = ({
250
+ runtimeMode,
251
+ surfaceRole,
252
+ runtimeUrl,
253
+ publicHost,
254
+ embedParentOrigin,
255
+ backendOrigin = DEFAULT_AIR_JAM_DEV_BACKEND_URL,
256
+ secureTransport = false
257
+ }) => resolveRuntimeTopology({
258
+ runtimeMode,
259
+ surfaceRole,
260
+ appOrigin: new URL(runtimeUrl).origin,
261
+ backendOrigin,
262
+ publicHost,
263
+ assetBasePath: normalizeAssetBasePath(runtimeUrl),
264
+ secureTransport,
265
+ embedded: true,
266
+ embedParentOrigin,
267
+ proxyStrategy: "none"
268
+ });
269
+ var serializeResolvedTopology = (topology) => serializeRuntimeTopology(topology);
270
+
271
+ // ../env/index.mjs
272
+ var ANSI = {
273
+ reset: "\x1B[0m",
274
+ bold: "\x1B[1m",
275
+ red: "\x1B[31m",
276
+ yellow: "\x1B[33m",
277
+ cyan: "\x1B[36m",
278
+ dim: "\x1B[2m"
279
+ };
280
+ var DEFAULT_FOOTER_HINT = "Set the required environment variables and retry.";
281
+ var resolveColorEnabled = (forced) => {
282
+ if (typeof forced === "boolean") {
283
+ return forced;
284
+ }
285
+ if (typeof process === "undefined") {
286
+ return false;
287
+ }
288
+ if (typeof process.env?.NO_COLOR !== "undefined") {
289
+ return false;
290
+ }
291
+ return Boolean(process.stderr?.isTTY);
292
+ };
293
+ var paint = (enabled, tone, value) => {
294
+ if (!enabled) {
295
+ return value;
296
+ }
297
+ return `${ANSI[tone]}${value}${ANSI.reset}`;
298
+ };
299
+ var toEnvKey = (path2) => {
300
+ if (!Array.isArray(path2) || path2.length === 0) {
301
+ return "<root>";
302
+ }
303
+ const firstStringSegment = path2.find(
304
+ (segment) => typeof segment === "string"
305
+ );
306
+ return typeof firstStringSegment === "string" ? firstStringSegment : "<root>";
307
+ };
308
+ var describeExpectedRule = (issue) => {
309
+ switch (issue.code) {
310
+ case "invalid_type":
311
+ return `type ${String(issue.expected)}`;
312
+ case "invalid_value":
313
+ return issue.values && issue.values.length > 0 ? `one of: ${issue.values.join(", ")}` : "a valid value";
314
+ case "too_small":
315
+ return issue.minimum != null ? `at least ${issue.minimum}${issue.inclusive === false ? " (exclusive)" : ""}` : "a larger value";
316
+ case "too_big":
317
+ return issue.maximum != null ? `at most ${issue.maximum}${issue.inclusive === false ? " (exclusive)" : ""}` : "a smaller value";
318
+ case "invalid_format":
319
+ return issue.format ? `format ${issue.format}` : "a valid format";
320
+ default:
321
+ return "a valid value";
322
+ }
323
+ };
324
+ var toReceivedValue = (env, envKey) => {
325
+ if (!env || envKey === "<root>") {
326
+ return void 0;
327
+ }
328
+ const value = env[envKey];
329
+ if (typeof value === "undefined") {
330
+ return void 0;
331
+ }
332
+ return String(value);
333
+ };
334
+ var normalizeIssues = ({ zodIssues, env, keyHints }) => zodIssues.map((issue) => {
335
+ const envKey = toEnvKey(issue.path);
336
+ return {
337
+ envKey,
338
+ expected: describeExpectedRule(issue),
339
+ received: toReceivedValue(env, envKey),
340
+ message: issue.message,
341
+ fix: keyHints?.[envKey] ?? (envKey === "<root>" ? "Adjust the environment values so the schema constraints pass." : `Set ${envKey} to a valid value.`)
342
+ };
343
+ }).sort((a, b) => {
344
+ if (a.envKey === b.envKey) {
345
+ return a.message.localeCompare(b.message);
346
+ }
347
+ return a.envKey.localeCompare(b.envKey);
348
+ });
349
+ var EnvValidationError = class extends Error {
350
+ constructor({ boundary, issues, docsHint }) {
351
+ const count = issues.length;
352
+ super(
353
+ `${boundary}: invalid environment configuration (${count} issue${count === 1 ? "" : "s"})`
354
+ );
355
+ this.name = "EnvValidationError";
356
+ this.boundary = boundary;
357
+ this.issues = issues;
358
+ this.docsHint = docsHint;
359
+ }
360
+ };
361
+ var isEnvValidationError = (error) => error instanceof EnvValidationError;
362
+ var validateEnv = ({
363
+ boundary,
364
+ schema,
365
+ env = process.env,
366
+ docsHint,
367
+ keyHints
368
+ }) => {
369
+ const result = schema.safeParse(env);
370
+ if (result.success) {
371
+ return result.data;
372
+ }
373
+ throw new EnvValidationError({
374
+ boundary,
375
+ docsHint,
376
+ issues: normalizeIssues({
377
+ zodIssues: result.error.issues,
378
+ env,
379
+ keyHints
380
+ })
381
+ });
382
+ };
383
+ var formatEnvValidationError = (error, { color, includeReceived = true, docsHint } = {}) => {
384
+ if (!isEnvValidationError(error)) {
385
+ return String(error);
386
+ }
387
+ const colorEnabled = resolveColorEnabled(color);
388
+ const heading = `\u2716 ${error.boundary}: invalid environment configuration`;
389
+ const lines = [
390
+ paint(colorEnabled, "red", paint(colorEnabled, "bold", heading))
391
+ ];
392
+ for (const [index, issue] of error.issues.entries()) {
393
+ lines.push(
394
+ `${paint(colorEnabled, "yellow", `${index + 1}. ${issue.envKey}`)} ${paint(colorEnabled, "dim", `(${issue.message})`)}`
395
+ );
396
+ lines.push(` expected: ${issue.expected}`);
397
+ if (includeReceived) {
398
+ lines.push(
399
+ ` received: ${typeof issue.received === "string" && issue.received.length > 0 ? `"${issue.received}"` : "<missing>"}`
400
+ );
401
+ }
402
+ lines.push(` fix: ${issue.fix}`);
403
+ }
404
+ lines.push("");
405
+ lines.push(
406
+ paint(
407
+ colorEnabled,
408
+ "cyan",
409
+ `Next: ${docsHint ?? error.docsHint ?? DEFAULT_FOOTER_HINT}`
410
+ )
411
+ );
412
+ return lines.join("\n");
413
+ };
414
+
415
+ // runtime/secure-dev.mjs
416
+ import { execFileSync as execFileSync2 } from "child_process";
417
+ import fs3 from "fs";
418
+ import path from "path";
419
+
420
+ // runtime/runtime-env.mjs
421
+ import { z } from "zod";
422
+ var trimToUndefined = (value) => {
423
+ if (typeof value !== "string") {
424
+ return void 0;
425
+ }
426
+ const normalized = value.trim();
427
+ return normalized.length > 0 ? normalized : void 0;
428
+ };
429
+ var optionalEnvValue = z.string().optional().transform((value) => trimToUndefined(value));
430
+ var optionalEnumFromEnv = (envKey, values) => optionalEnvValue.transform((value, context) => {
431
+ if (!value) {
432
+ return void 0;
433
+ }
434
+ if (!values.includes(value)) {
435
+ context.addIssue({
436
+ code: "custom",
437
+ message: `${envKey} must be one of: ${values.join(", ")}.`
438
+ });
439
+ return z.NEVER;
440
+ }
441
+ return value;
442
+ });
443
+ var positiveIntegerFromEnv = (envKey, fallback) => optionalEnvValue.transform((value, context) => {
444
+ if (!value) {
445
+ return fallback;
446
+ }
447
+ const parsed = Number.parseInt(value, 10);
448
+ if (!Number.isInteger(parsed) || parsed <= 0) {
449
+ context.addIssue({
450
+ code: "custom",
451
+ message: `${envKey} must be a positive integer.`
452
+ });
453
+ return z.NEVER;
454
+ }
455
+ return parsed;
456
+ });
457
+ var createAirJamRuntimeEnvSchema = z.object({
458
+ VITE_PORT: positiveIntegerFromEnv("VITE_PORT", 5173),
459
+ AIR_JAM_SERVER_PORT: positiveIntegerFromEnv(
460
+ "AIR_JAM_SERVER_PORT",
461
+ DEFAULT_AIR_JAM_SERVER_PORT
462
+ ),
463
+ AIR_JAM_BIND_HOST: optionalEnvValue,
464
+ AIR_JAM_SECURE_MODE: optionalEnumFromEnv("AIR_JAM_SECURE_MODE", [
465
+ "local",
466
+ "tunnel"
467
+ ]),
468
+ AIR_JAM_MKCERT_TRUST_STORES: optionalEnvValue,
469
+ AIR_JAM_SECURE_PUBLIC_HOST: optionalEnvValue,
470
+ CLOUDFLARE_TUNNEL_NAME: optionalEnvValue,
471
+ AIR_JAM_SECURE_ROOT: optionalEnvValue,
472
+ VITE_AIR_JAM_SERVER_URL: optionalEnvValue,
473
+ VITE_AIR_JAM_PUBLIC_HOST: optionalEnvValue,
474
+ NEXT_PUBLIC_APP_URL: optionalEnvValue,
475
+ HOME: optionalEnvValue
476
+ });
477
+ var loadCreateAirJamRuntimeEnv = ({
478
+ env = process.env,
479
+ boundary = "create-airjam.runtime"
480
+ } = {}) => validateEnv({
481
+ boundary,
482
+ schema: createAirJamRuntimeEnvSchema,
483
+ env,
484
+ docsHint: "Fix runtime env values in .env / .env.local before running create-airjam runtime commands.",
485
+ keyHints: {
486
+ VITE_PORT: "Set a positive integer Vite port (for example: VITE_PORT=5173).",
487
+ AIR_JAM_SERVER_PORT: "Set a positive integer local server port (for example: AIR_JAM_SERVER_PORT=4000).",
488
+ AIR_JAM_SECURE_MODE: "Use AIR_JAM_SECURE_MODE=local or AIR_JAM_SECURE_MODE=tunnel."
489
+ }
490
+ });
491
+
492
+ // runtime/secure-dev.mjs
493
+ var SECURE_MODE_LOCAL = "local";
494
+ var SECURE_MODE_TUNNEL = "tunnel";
495
+ var DEFAULT_GAME_PORT = 5173;
496
+ var DEFAULT_PLATFORM_PORT = 3e3;
497
+ var SECURE_DEV_VERSION = 1;
498
+ var SECURE_MODE_VALUES = /* @__PURE__ */ new Set([SECURE_MODE_LOCAL, SECURE_MODE_TUNNEL]);
499
+ var resolveRequestedSecureMode = ({
500
+ argv = [],
501
+ env = process.env,
502
+ defaultMode = SECURE_MODE_LOCAL
503
+ } = {}) => {
504
+ const flagValue = getFlagValue(argv, "--secure-mode");
505
+ const envValue = env.AIR_JAM_SECURE_MODE;
506
+ const rawValue = (flagValue ?? envValue ?? defaultMode).trim().toLowerCase();
507
+ if (!SECURE_MODE_VALUES.has(rawValue)) {
508
+ throw new Error(
509
+ `Unsupported secure mode "${rawValue}". Use "local" or "tunnel".`
510
+ );
511
+ }
512
+ return rawValue;
513
+ };
514
+ var parseSecureInitArgs = (argv = [], env = process.env) => ({
515
+ mode: resolveRequestedSecureMode({ argv, env }),
516
+ hostname: getFlagValue(argv, "--hostname")?.trim() ?? "",
517
+ tunnel: getFlagValue(argv, "--tunnel")?.trim() ?? ""
518
+ });
519
+ var parseGameDevArgs = (argv = [], env = process.env) => {
520
+ const runtimeEnv = typeof env.VITE_PORT === "number" ? env : loadCreateAirJamRuntimeEnv({
521
+ env,
522
+ boundary: "create-airjam.dev"
523
+ });
524
+ return {
525
+ secure: hasFlag(argv, "--secure"),
526
+ secureMode: resolveRequestedSecureMode({ argv, env: runtimeEnv }),
527
+ previewManaged: hasFlag(argv, "--preview-managed"),
528
+ webOnly: hasFlag(argv, "--web-only"),
529
+ serverOnly: hasFlag(argv, "--server-only"),
530
+ allowExistingGame: hasFlag(argv, "--allow-existing-game"),
531
+ port: runtimeEnv.VITE_PORT ?? DEFAULT_GAME_PORT
532
+ };
533
+ };
534
+ var getSecurePaths = (cwd) => {
535
+ const rootDir = cwd;
536
+ const airJamDir = path.join(rootDir, ".airjam");
537
+ const certDir = path.join(airJamDir, "certs");
538
+ return {
539
+ rootDir,
540
+ airJamDir,
541
+ certDir,
542
+ secureDevStateFile: path.join(airJamDir, "secure-dev.json"),
543
+ certFile: path.join(certDir, "local-dev.pem"),
544
+ keyFile: path.join(certDir, "local-dev-key.pem"),
545
+ cloudflaredDir: path.join(rootDir, ".cloudflared"),
546
+ cloudflaredConfigFile: path.join(rootDir, ".cloudflared", "config.yml")
547
+ };
548
+ };
549
+ var run = (command, args, options = {}) => execFileSync2(command, args, {
550
+ encoding: "utf8",
551
+ stdio: options.silent ? ["ignore", "pipe", "pipe"] : "inherit",
552
+ cwd: options.cwd,
553
+ env: options.env ?? process.env
554
+ });
555
+ var buildLocalCertificateHosts = (lanIp) => {
556
+ const hosts = ["localhost", "127.0.0.1", "::1"];
557
+ if (lanIp) {
558
+ hosts.push(lanIp);
559
+ }
560
+ return hosts;
561
+ };
562
+ var resolveSecurePublicHost = ({ mode, port, lanIp, tunnelHost }) => {
563
+ if (mode === SECURE_MODE_TUNNEL) {
564
+ return tunnelHost;
565
+ }
566
+ const host = lanIp ?? "localhost";
567
+ return `https://${host}:${port}`;
568
+ };
569
+ var resolveSecureLoopbackHost = (port) => `https://127.0.0.1:${port}`;
570
+ var resolveSecurePlatformHost = ({
571
+ mode,
572
+ lanIp,
573
+ tunnelHost,
574
+ port = DEFAULT_PLATFORM_PORT
575
+ }) => {
576
+ if (mode === SECURE_MODE_TUNNEL) {
577
+ return tunnelHost;
578
+ }
579
+ const host = lanIp ?? "localhost";
580
+ return `https://${host}:${port}`;
581
+ };
582
+ var readSecureDevState = (filePath) => {
583
+ if (!fs3.existsSync(filePath)) {
584
+ return null;
585
+ }
586
+ return JSON.parse(fs3.readFileSync(filePath, "utf8"));
587
+ };
588
+ var writeSecureDevState = (filePath, state) => {
589
+ fs3.mkdirSync(path.dirname(filePath), { recursive: true });
590
+ fs3.writeFileSync(filePath, JSON.stringify(state, null, 2), "utf8");
591
+ };
592
+ var ensureMkcertInstalled = () => {
593
+ if (!commandExists("mkcert", ["-help"])) {
594
+ throw new Error(
595
+ [
596
+ "mkcert is required for local secure dev.",
597
+ "Install it once, then rerun `airjam secure:init`.",
598
+ "macOS: brew install mkcert",
599
+ "Windows: winget install FiloSottile.mkcert or choco install mkcert",
600
+ "Linux: install mkcert from your package manager or https://github.com/FiloSottile/mkcert"
601
+ ].join("\n")
602
+ );
603
+ }
604
+ };
605
+ var ensureCloudflaredInstalled = () => {
606
+ if (!commandExists("cloudflared")) {
607
+ throw new Error(
608
+ [
609
+ "cloudflared is required for tunnel secure mode.",
610
+ "Install it once, then rerun `airjam secure:init --mode=tunnel ...`."
611
+ ].join("\n")
612
+ );
613
+ }
614
+ };
615
+ var ensureCloudflareLogin = (env = process.env) => {
616
+ const certPath = path.join(env.HOME || "", ".cloudflared", "cert.pem");
617
+ if (!fs3.existsSync(certPath)) {
618
+ throw new Error(
619
+ "Cloudflare login not found. Run: cloudflared tunnel login"
620
+ );
621
+ }
622
+ };
623
+ var ensureLocalCertificate = ({
624
+ cwd,
625
+ certFile,
626
+ keyFile,
627
+ lanIp,
628
+ env,
629
+ runtimeEnv
630
+ }) => {
631
+ ensureMkcertInstalled();
632
+ fs3.mkdirSync(path.dirname(certFile), { recursive: true });
633
+ const trustStores = runtimeEnv.AIR_JAM_MKCERT_TRUST_STORES || "system,nss";
634
+ const mkcertEnv = {
635
+ ...env,
636
+ TRUST_STORES: trustStores
637
+ };
638
+ run("mkcert", ["-install"], {
639
+ cwd,
640
+ env: mkcertEnv
641
+ });
642
+ run(
643
+ "mkcert",
644
+ [
645
+ "-cert-file",
646
+ certFile,
647
+ "-key-file",
648
+ keyFile,
649
+ ...buildLocalCertificateHosts(lanIp)
650
+ ],
651
+ { cwd, env: mkcertEnv }
652
+ );
653
+ };
654
+ var configureCloudflareTunnel = ({
655
+ cwd,
656
+ cloudflaredConfigFile,
657
+ hostname,
658
+ tunnel,
659
+ gamePort,
660
+ env
661
+ }) => {
662
+ ensureCloudflaredInstalled();
663
+ ensureCloudflareLogin(env);
664
+ let tunnelExists = false;
665
+ try {
666
+ run("cloudflared", ["tunnel", "info", tunnel], { cwd, silent: true });
667
+ tunnelExists = true;
668
+ } catch {
669
+ tunnelExists = false;
670
+ }
671
+ if (!tunnelExists) {
672
+ console.log(`Creating tunnel ${tunnel}...`);
673
+ run("cloudflared", ["tunnel", "create", tunnel], { cwd });
674
+ } else {
675
+ console.log(`Tunnel ${tunnel} already exists, reusing it.`);
676
+ }
677
+ console.log(`Routing DNS ${hostname} -> ${tunnel}...`);
678
+ run("cloudflared", ["tunnel", "route", "dns", tunnel, hostname], { cwd });
679
+ const tunnelInfoRaw = run("cloudflared", ["tunnel", "info", tunnel], {
680
+ cwd,
681
+ silent: true
682
+ });
683
+ const idMatch = tunnelInfoRaw.match(/[0-9a-f-]{36}/i);
684
+ if (!idMatch) {
685
+ throw new Error(
686
+ "Could not resolve tunnel UUID from `cloudflared tunnel info`."
687
+ );
688
+ }
689
+ const tunnelId = idMatch[0];
690
+ const credentialsFile = path.join(
691
+ env.HOME || "",
692
+ ".cloudflared",
693
+ `${tunnelId}.json`
694
+ );
695
+ fs3.mkdirSync(path.dirname(cloudflaredConfigFile), { recursive: true });
696
+ fs3.writeFileSync(
697
+ cloudflaredConfigFile,
698
+ [
699
+ `tunnel: ${tunnel}`,
700
+ `credentials-file: ${credentialsFile}`,
701
+ "",
702
+ "ingress:",
703
+ ` - hostname: ${hostname}`,
704
+ ` service: https://127.0.0.1:${gamePort}`,
705
+ " originRequest:",
706
+ " noTLSVerify: true",
707
+ " - service: http_status:404",
708
+ ""
709
+ ].join("\n"),
710
+ "utf8"
711
+ );
712
+ };
713
+ var initializeSecureDev = ({
714
+ cwd,
715
+ envFilePath,
716
+ mode,
717
+ hostname,
718
+ tunnel,
719
+ env = process.env,
720
+ runtimeEnv = loadCreateAirJamRuntimeEnv({
721
+ env,
722
+ boundary: "create-airjam.secure-init"
723
+ }),
724
+ gamePort = DEFAULT_GAME_PORT,
725
+ nextStepMessage = "pnpm run dev -- --secure"
726
+ } = {}) => {
727
+ const paths = getSecurePaths(cwd);
728
+ const lanIp = detectLocalIpv4();
729
+ const tunnelHost = hostname ? `https://${hostname}` : null;
730
+ ensureLocalCertificate({
731
+ cwd,
732
+ certFile: paths.certFile,
733
+ keyFile: paths.keyFile,
734
+ lanIp,
735
+ env,
736
+ runtimeEnv
737
+ });
738
+ if (mode === SECURE_MODE_TUNNEL) {
739
+ if (!hostname || !tunnel) {
740
+ throw new Error(
741
+ "Tunnel mode requires both --hostname <dev.example.com> and --tunnel <tunnel-name>."
742
+ );
743
+ }
744
+ configureCloudflareTunnel({
745
+ cwd,
746
+ cloudflaredConfigFile: paths.cloudflaredConfigFile,
747
+ hostname,
748
+ tunnel,
749
+ gamePort,
750
+ env
751
+ });
752
+ }
753
+ const nextState = {
754
+ version: SECURE_DEV_VERSION,
755
+ mode,
756
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
757
+ lanIp,
758
+ certFile: paths.certFile,
759
+ keyFile: paths.keyFile,
760
+ hosts: buildLocalCertificateHosts(lanIp),
761
+ publicHost: resolveSecurePublicHost({
762
+ mode,
763
+ port: gamePort,
764
+ lanIp,
765
+ tunnelHost
766
+ }),
767
+ tunnelHost,
768
+ tunnelName: tunnel || null
769
+ };
770
+ writeSecureDevState(paths.secureDevStateFile, nextState);
771
+ upsertEnv(envFilePath, "AIR_JAM_SECURE_MODE", mode);
772
+ if (mode === SECURE_MODE_TUNNEL) {
773
+ upsertEnv(envFilePath, "AIR_JAM_SECURE_PUBLIC_HOST", nextState.publicHost);
774
+ upsertEnv(envFilePath, "CLOUDFLARE_TUNNEL_NAME", tunnel);
775
+ }
776
+ console.log("\nSecure dev setup complete.");
777
+ console.log(`Mode: ${mode}`);
778
+ console.log(`Public host: ${nextState.publicHost}`);
779
+ console.log(`Certificate: ${paths.certFile}`);
780
+ if (!lanIp) {
781
+ console.log(
782
+ "No LAN IPv4 address was detected. Secure dev will work on localhost, but phone-on-LAN testing is not configured."
783
+ );
784
+ }
785
+ if (mode === SECURE_MODE_TUNNEL) {
786
+ console.log(`Tunnel: ${tunnel}`);
787
+ }
788
+ console.log(`Next: ${nextStepMessage}`);
789
+ return nextState;
790
+ };
791
+ var loadSecureDevState = ({
792
+ cwd,
793
+ mode,
794
+ env = process.env,
795
+ gamePort = DEFAULT_GAME_PORT,
796
+ runtimeEnv = loadCreateAirJamRuntimeEnv({
797
+ env,
798
+ boundary: "create-airjam.secure-state"
799
+ })
800
+ } = {}) => {
801
+ const paths = getSecurePaths(cwd);
802
+ const state = readSecureDevState(paths.secureDevStateFile);
803
+ if (!state) {
804
+ throw new Error(
805
+ "Missing .airjam/secure-dev.json. Run `airjam secure:init` first."
806
+ );
807
+ }
808
+ if (!fs3.existsSync(state.certFile ?? "") || !fs3.existsSync(state.keyFile ?? "")) {
809
+ throw new Error(
810
+ "Missing local HTTPS certificate files. Run `pnpm secure:init` again."
811
+ );
812
+ }
813
+ if (mode === SECURE_MODE_LOCAL) {
814
+ const currentLanIp = detectLocalIpv4();
815
+ if ((state.lanIp ?? null) !== (currentLanIp ?? null)) {
816
+ throw new Error(
817
+ "Your LAN IPv4 address changed since secure setup was created. Run `airjam secure:init` again."
818
+ );
819
+ }
820
+ }
821
+ const publicHost = resolveSecurePublicHost({
822
+ mode,
823
+ port: gamePort,
824
+ lanIp: state.lanIp ?? null,
825
+ tunnelHost: runtimeEnv.AIR_JAM_SECURE_PUBLIC_HOST || state.tunnelHost || null
826
+ });
827
+ const tunnelName = runtimeEnv.CLOUDFLARE_TUNNEL_NAME || state.tunnelName || null;
828
+ if (mode === SECURE_MODE_TUNNEL && !tunnelName) {
829
+ throw new Error(
830
+ "Missing CLOUDFLARE_TUNNEL_NAME for tunnel secure mode. Run `airjam secure:init --mode=tunnel ...` again."
831
+ );
832
+ }
833
+ return {
834
+ ...state,
835
+ mode,
836
+ publicHost,
837
+ tunnelName,
838
+ certFile: state.certFile,
839
+ keyFile: state.keyFile,
840
+ loopbackHost: resolveSecureLoopbackHost(gamePort),
841
+ platformHost: resolveSecurePlatformHost({
842
+ mode,
843
+ lanIp: state.lanIp ?? null,
844
+ tunnelHost: runtimeEnv.AIR_JAM_SECURE_PUBLIC_HOST || state.tunnelHost || null,
845
+ port: DEFAULT_PLATFORM_PORT
846
+ })
847
+ };
848
+ };
849
+ var buildSecureGameEnv = ({
850
+ secureState,
851
+ webOnly,
852
+ env = process.env,
853
+ backendOrigin
854
+ } = {}) => {
855
+ return {
856
+ VITE_AIR_JAM_RUNTIME_TOPOLOGY: serializeResolvedTopology(
857
+ buildStandaloneGameTopology({
858
+ surfaceRole: "host",
859
+ publicHost: secureState.publicHost,
860
+ backendOrigin,
861
+ secureTransport: true
862
+ })
863
+ ),
864
+ AIR_JAM_SECURE_MODE: secureState.mode,
865
+ AIR_JAM_SECURE_PUBLIC_HOST: secureState.publicHost,
866
+ AIR_JAM_DEV_CERT_FILE: secureState.certFile,
867
+ AIR_JAM_DEV_KEY_FILE: secureState.keyFile,
868
+ AIR_JAM_DEV_PROXY_BACKEND_URL: backendOrigin,
869
+ VITE_AIR_JAM_PUBLIC_HOST: secureState.publicHost,
870
+ ...webOnly && env.VITE_AIR_JAM_SERVER_URL ? { VITE_AIR_JAM_SERVER_URL: env.VITE_AIR_JAM_SERVER_URL } : {}
871
+ };
872
+ };
873
+ var runSecureInitCli = async ({
874
+ cwd = process.cwd(),
875
+ argv = process.argv.slice(2),
876
+ env = process.env,
877
+ nextStepMessage = "pnpm run dev -- --secure"
878
+ } = {}) => {
879
+ if (hasFlag(argv, "--help") || hasFlag(argv, "-h")) {
880
+ console.log(
881
+ "Usage: airjam secure:init [--mode=local|tunnel] [--hostname <dev.example.com>] [--tunnel <tunnel-name>]"
882
+ );
883
+ console.log("");
884
+ console.log("Modes:");
885
+ console.log(
886
+ " local Generate trusted local HTTPS certs with mkcert (default)"
887
+ );
888
+ console.log(
889
+ " tunnel Generate local HTTPS certs and configure the optional Cloudflare tunnel fallback"
890
+ );
891
+ return;
892
+ }
893
+ loadEnvFile(path.join(cwd, ".env"), env);
894
+ loadEnvFile(path.join(cwd, ".env.local"), env);
895
+ const runtimeEnv = loadCreateAirJamRuntimeEnv({
896
+ env,
897
+ boundary: "create-airjam.secure-init"
898
+ });
899
+ const args = parseSecureInitArgs(argv, runtimeEnv);
900
+ initializeSecureDev({
901
+ cwd,
902
+ envFilePath: path.join(cwd, ".env.local"),
903
+ mode: args.mode,
904
+ hostname: args.hostname,
905
+ tunnel: args.tunnel,
906
+ env,
907
+ runtimeEnv,
908
+ gamePort: runtimeEnv.VITE_PORT ?? DEFAULT_GAME_PORT,
909
+ nextStepMessage
910
+ });
911
+ };
912
+
913
+ export {
914
+ isPortOpen,
915
+ waitForPort,
916
+ loadEnvFile,
917
+ detectLocalIpv4,
918
+ getFlagValue,
919
+ hasFlag,
920
+ createProcessGroup,
921
+ resolveLocalBackendOrigin,
922
+ buildStandaloneGameTopology,
923
+ buildPlatformShellTopology,
924
+ buildEmbeddedGameTopology,
925
+ serializeResolvedTopology,
926
+ isEnvValidationError,
927
+ formatEnvValidationError,
928
+ loadCreateAirJamRuntimeEnv,
929
+ SECURE_MODE_LOCAL,
930
+ SECURE_MODE_TUNNEL,
931
+ DEFAULT_GAME_PORT,
932
+ DEFAULT_PLATFORM_PORT,
933
+ resolveRequestedSecureMode,
934
+ parseGameDevArgs,
935
+ loadSecureDevState,
936
+ buildSecureGameEnv,
937
+ runSecureInitCli
938
+ };
939
+ //# sourceMappingURL=chunk-U6V3HEBB.js.map