create-eigen-game 0.13.0 → 0.13.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.
- package/README.md +1 -1
- package/dist/cli.d.ts +1 -2
- package/dist/cli.js +466 -378
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +119 -108
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -27
- package/dist/src-q9BxESYC.js +833 -0
- package/dist/src-q9BxESYC.js.map +1 -0
- package/package.json +8 -8
- package/src/cli.ts +437 -0
- package/{dist/engine-range.d.ts → src/engine-range.ts} +23 -2
- package/src/index.ts +971 -0
- package/src/link-firebase.ts +70 -0
- package/src/prompt.ts +182 -0
- package/src/summary.ts +86 -0
- package/templates/app-overlay/lib/game/README.md +1 -1
- package/templates/app-overlay/lib/main.dart.template +8 -5
- package/templates/project/README.md +2 -2
- package/templates/project/package.json +3 -3
- package/templates/worker/.dev.vars.example +1 -0
- package/templates/worker/README.md +5 -2
- package/templates/worker/src/module/v1.ts +1 -0
- package/dist/chunk-L7EVXO3Y.js +0 -439
- package/dist/chunk-L7EVXO3Y.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/link-firebase.d.ts +0 -28
- package/dist/prompt.d.ts +0 -79
- package/dist/summary.d.ts +0 -26
package/src/index.ts
ADDED
|
@@ -0,0 +1,971 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, relative, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { ENGINE_PACKAGE, engineRange } from "./engine-range.js";
|
|
6
|
+
import { type FirebaseLink, readFirebaseLink } from "./link-firebase.js";
|
|
7
|
+
|
|
8
|
+
export type { FirebaseLink } from "./link-firebase.js";
|
|
9
|
+
|
|
10
|
+
export type PackageManager = "npm" | "pnpm";
|
|
11
|
+
|
|
12
|
+
export type Runner = (command: string, args: string[], cwd: string) => void;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Where a scaffold says what it is doing, so that presentation belongs to the
|
|
16
|
+
* caller and this module only has to name things.
|
|
17
|
+
*
|
|
18
|
+
* The default is the behaviour a library caller expects with no opinion:
|
|
19
|
+
* subprocesses inherit the terminal and warnings go to `console.warn`. The CLI
|
|
20
|
+
* substitutes one that captures each step's output and shows it only if the
|
|
21
|
+
* step fails.
|
|
22
|
+
*/
|
|
23
|
+
export interface Reporter {
|
|
24
|
+
/** Runs `body` as one named step. Its subprocesses can be captured. */
|
|
25
|
+
step<T>(label: string, body: () => T): T;
|
|
26
|
+
/**
|
|
27
|
+
* Runs `body` as a step that owns the terminal, because something inside it
|
|
28
|
+
* asks questions. FlutterFire is the only one.
|
|
29
|
+
*/
|
|
30
|
+
handOver<T>(label: string, body: () => T): T;
|
|
31
|
+
/** Output from a subprocess inside the current step. */
|
|
32
|
+
emit(output: string): void;
|
|
33
|
+
/** A failure the scaffold survives. */
|
|
34
|
+
warn(message: string): void;
|
|
35
|
+
/** Whether subprocesses must inherit the terminal rather than be captured. */
|
|
36
|
+
readonly interactive: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Gives a terminal that reports no width the width clack would have assumed.
|
|
41
|
+
*
|
|
42
|
+
* A pty can report itself as a TTY and set `columns` to 0. `script` does, and
|
|
43
|
+
* so do some container terminals. clack falls back to 80 for a stream with no
|
|
44
|
+
* `columns` at all, but `0` is a number and satisfies that check, so the width
|
|
45
|
+
* it draws its rules from goes negative and a scaffold dies partway through
|
|
46
|
+
* with `RangeError: Invalid string length`. Supplying the default its check
|
|
47
|
+
* misses is better than giving up the drawing.
|
|
48
|
+
*/
|
|
49
|
+
export function normaliseTerminalWidth(stream: { isTTY?: boolean; columns?: number }): void {
|
|
50
|
+
if (stream.isTTY === true && (stream.columns ?? 0) < 1) stream.columns = 80;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Runs every step plainly, which is what a library caller gets by default. */
|
|
54
|
+
export const plainReporter: Reporter = {
|
|
55
|
+
step: (_label, body) => body(),
|
|
56
|
+
handOver: (_label, body) => body(),
|
|
57
|
+
emit: (output) => process.stdout.write(output),
|
|
58
|
+
warn: (message) => console.warn(`create-eigen-game: ${message}`),
|
|
59
|
+
interactive: true,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The runner a scaffold uses when the caller has not supplied one: it asks the
|
|
64
|
+
* reporter whether the terminal is spoken for.
|
|
65
|
+
*
|
|
66
|
+
* `interactive` inherits, which is the only way FlutterFire can put a question
|
|
67
|
+
* on screen and read the answer. Otherwise both streams are captured and
|
|
68
|
+
* handed to the reporter: on success so it can discard them, and on failure
|
|
69
|
+
* so the reason survives.
|
|
70
|
+
*/
|
|
71
|
+
export function capturingRunner(reporter: Reporter): Runner {
|
|
72
|
+
return (command, args, cwd) => {
|
|
73
|
+
if (reporter.interactive) {
|
|
74
|
+
execFileSync(command, args, { cwd, stdio: "inherit" });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
reporter.emit(execFileSync(command, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }));
|
|
79
|
+
} catch (error: unknown) {
|
|
80
|
+
// Both streams, because which one a tool failed on is its own business:
|
|
81
|
+
// pub explains itself on stdout, Gradle on stderr.
|
|
82
|
+
const { stdout, stderr } = error as { stdout?: string; stderr?: string };
|
|
83
|
+
reporter.emit(`${stdout ?? ""}${stderr ?? ""}`);
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface ScaffoldOptions {
|
|
90
|
+
directory: string;
|
|
91
|
+
org?: string;
|
|
92
|
+
packageManager?: PackageManager;
|
|
93
|
+
/**
|
|
94
|
+
* Run Flutter, package installation, and contract/payload generation.
|
|
95
|
+
* Kept as a programmatic test seam; the public CLI always bootstraps both
|
|
96
|
+
* halves of the combined project.
|
|
97
|
+
*/
|
|
98
|
+
bootstrap?: boolean;
|
|
99
|
+
/**
|
|
100
|
+
* Emit the GitHub Actions workflows. Off by default; see the call site for
|
|
101
|
+
* why, and `addContinuousIntegration` for adding them to an existing
|
|
102
|
+
* project later.
|
|
103
|
+
*/
|
|
104
|
+
ci?: boolean;
|
|
105
|
+
/**
|
|
106
|
+
* Initialise a repository and commit the scaffold. Defaults to `bootstrap`,
|
|
107
|
+
* because the commit is only worth having once the generated files exist.
|
|
108
|
+
*/
|
|
109
|
+
git?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Configure Firebase before the first commit, by running the Flutter
|
|
112
|
+
* client's `configure_firebase`. A string names the project to use; `true`
|
|
113
|
+
* lets FlutterFire ask, which is also where a project can be created.
|
|
114
|
+
*
|
|
115
|
+
* Explicit here, though the CLI turns it on by default: this is the one step
|
|
116
|
+
* that reaches outside the destination directory, and a library caller
|
|
117
|
+
* should say so rather than discover it. {@link firebaseReadiness} is how
|
|
118
|
+
* the CLI decides.
|
|
119
|
+
*/
|
|
120
|
+
firebase?: boolean | string;
|
|
121
|
+
/**
|
|
122
|
+
* Runs the bootstrap subprocesses. A seam: the tests substitute a recorder,
|
|
123
|
+
* and `scripts/scaffold-e2e.mjs` wraps it to point the generated server at
|
|
124
|
+
* this workspace's engine rather than npm's copy.
|
|
125
|
+
*/
|
|
126
|
+
run?: Runner;
|
|
127
|
+
/**
|
|
128
|
+
* Where the scaffold says what it is doing. See {@link Reporter}; the
|
|
129
|
+
* default runs every step plainly.
|
|
130
|
+
*/
|
|
131
|
+
reporter?: Reporter;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* What became of the repository, so the CLI's closing summary can say rather
|
|
136
|
+
* than guess. `failed` has already warned by the time it is returned, and
|
|
137
|
+
* carries no advice of its own.
|
|
138
|
+
*/
|
|
139
|
+
export type GitOutcome = "committed" | "existing" | "skipped" | "failed";
|
|
140
|
+
|
|
141
|
+
export interface ScaffoldResult {
|
|
142
|
+
root: string;
|
|
143
|
+
name: string;
|
|
144
|
+
git: GitOutcome;
|
|
145
|
+
/**
|
|
146
|
+
* Whether Firebase was configured, so the summary can either stop naming the
|
|
147
|
+
* step or spell it out. `failed` has already warned.
|
|
148
|
+
*/
|
|
149
|
+
firebase: "configured" | "failed" | "skipped";
|
|
150
|
+
/**
|
|
151
|
+
* What the Firebase step made knowable and this scaffold therefore filled
|
|
152
|
+
* in. Absent unless `firebase` is `configured`, since there is nothing to
|
|
153
|
+
* read otherwise.
|
|
154
|
+
*/
|
|
155
|
+
link?: FirebaseLink;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
159
|
+
const templatesRoot = resolve(packageRoot, "templates");
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The engine range emitted into a scaffolded project's package.json.
|
|
163
|
+
*
|
|
164
|
+
* Read from this package's `@eigeninteractive/server` devDependency rather than
|
|
165
|
+
* from its own version. See `engine-range.ts` for why that is the version the
|
|
166
|
+
* templates are known to compile against, and what it replaced.
|
|
167
|
+
*/
|
|
168
|
+
const engineVersion = engineRange((JSON.parse(readFileSync(resolve(packageRoot, "package.json"), "utf8")) as { devDependencies?: Record<string, string> }).devDependencies?.[ENGINE_PACKAGE], () => {
|
|
169
|
+
// Only reached in this workspace, where the manifest still says
|
|
170
|
+
// `workspace:*`. A published tarball has no sibling here and never asks.
|
|
171
|
+
const sibling = resolve(packageRoot, "../server/package.json");
|
|
172
|
+
return existsSync(sibling) ? (JSON.parse(readFileSync(sibling, "utf8")) as { version: string }).version : undefined;
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The Flutter client range installed into the app half.
|
|
177
|
+
*
|
|
178
|
+
* A stated version, not a derived or resolved one. The Dart templates import
|
|
179
|
+
* `package:eigen_flutter/eigen_flutter.dart` and
|
|
180
|
+
* `package:eigen_flutter/testing/twin_fixtures.dart` and are written against a
|
|
181
|
+
* specific Dart API. `eigen_flutter` is published and versioned separately from
|
|
182
|
+
* this package even though both now live in the platform monorepo, so a source
|
|
183
|
+
* location cannot compute which released version the template should request.
|
|
184
|
+
* Only compiling a scaffolded app establishes it, which the platform gate does
|
|
185
|
+
* on every change.
|
|
186
|
+
*
|
|
187
|
+
* This briefly resolved from pub.dev instead: "the newest `eigen_flutter` whose
|
|
188
|
+
* own `eigen_api` constraint targets the engine line being scaffolded". That
|
|
189
|
+
* predicate is wrong. The `eigen_api` constraint describes the WIRE the shell
|
|
190
|
+
* speaks, not the Dart API these templates call, and the two move
|
|
191
|
+
* independently: a future `eigen_flutter` may legitimately keep `eigen_api:
|
|
192
|
+
* ^0.2.0` while renaming everything the templates touch. It would have been
|
|
193
|
+
* selected, and the generated app would not compile.
|
|
194
|
+
*
|
|
195
|
+
* A caret RANGE rather than an exact version, so it still improves without a
|
|
196
|
+
* republish: `flutter pub add eigen_flutter@^0.4.0` already picks the newest
|
|
197
|
+
* 0.4.x at scaffold time, which is the part the pub.dev lookup was duplicating.
|
|
198
|
+
* What it deliberately cannot do is cross to 0.5.x, the one move that needs a
|
|
199
|
+
* human to confirm the templates still compile.
|
|
200
|
+
*
|
|
201
|
+
* Staleness is therefore a failing check rather than a broken scaffold: this is
|
|
202
|
+
* only ever a release behind, never wrong.
|
|
203
|
+
*
|
|
204
|
+
* Raised to 0.4.0 with the engine's session-snapshot wire. This is the one kind
|
|
205
|
+
* of bump that is not merely an improvement: a scaffold writes both halves, and
|
|
206
|
+
* the worker half is this repository's own line, so the shell it installs has to
|
|
207
|
+
* speak that line's socket. `eigen_flutter` 0.4.0 is the first that does, and
|
|
208
|
+
* every 0.3.x pins `eigen_api: ^0.2.0`, which cannot read a 0.3.x engine at all.
|
|
209
|
+
* A scaffold pinning 0.3.x would therefore resolve, compile, and then fail to
|
|
210
|
+
* render a game, which is the worst of the three.
|
|
211
|
+
*
|
|
212
|
+
* Raised to 0.4.1 for `EngineConfig.authDomain`, which the generated
|
|
213
|
+
* `main.dart` passes. Additive, so pre-1.0 it is a patch and `^0.4.0` would
|
|
214
|
+
* still resolve it, but `^0.4.0` also still resolves 0.4.0, where the parameter
|
|
215
|
+
* does not exist and the scaffold would not compile. The floor is what makes
|
|
216
|
+
* the generated code and the installed shell agree.
|
|
217
|
+
*
|
|
218
|
+
* Raised to 0.6.0 with the engine's opaque pagination cursors, and this is the
|
|
219
|
+
* same *required* kind of bump the 0.4.0 note describes rather than an
|
|
220
|
+
* improvement. The 0.4.x engine line takes `cursor` as an opaque string and
|
|
221
|
+
* returns `nextCursor` on every paged response; `eigen_flutter` 0.6.0 is the
|
|
222
|
+
* first shell that pins `eigen_api: ^0.4.0` and can read it. Everything below
|
|
223
|
+
* that pins `eigen_api: ^0.3.0` or older, so a scaffold left on `^0.4.1` would
|
|
224
|
+
* install the engine's current line beside a shell that cannot read a single
|
|
225
|
+
* paged list from it: it resolves, it compiles, and then the lobby and history
|
|
226
|
+
* are empty. 0.5.0 is skipped for the same reason, being a web-design release
|
|
227
|
+
* that still speaks the 0.3.x wire.
|
|
228
|
+
*
|
|
229
|
+
* Raised to 0.7.0 for the 0.5.x engine line and the `PlayerLimits` client API.
|
|
230
|
+
* vNext later simplified the wire again: versions are a contiguous prefix and
|
|
231
|
+
* generic mutation identities are gone. The next Flutter release must raise
|
|
232
|
+
* this floor before the corresponding scaffolder is published.
|
|
233
|
+
*
|
|
234
|
+
* Note that this floor and the engine range are raised in one commit on
|
|
235
|
+
* purpose. The scaffolder writes both halves, and `updateInternalDependencies`
|
|
236
|
+
* republishes this package whenever the engine version moves, so between an
|
|
237
|
+
* engine line crossing and this line moving there is a published scaffolder
|
|
238
|
+
* that pairs a new worker with an old shell. That window is real and this is
|
|
239
|
+
* what closes it.
|
|
240
|
+
*
|
|
241
|
+
* The 0.7.0 raise is the exception that shows where that promise cannot hold. A
|
|
242
|
+
* floor names a *published* `eigen_flutter`, and `eigen_flutter` publishes at the
|
|
243
|
+
* end of the release chain, after the npm packages this scaffolder ships with --
|
|
244
|
+
* so at the moment the engine crossed to 0.5.x there was no 0.7.0 to point at,
|
|
245
|
+
* and `create-eigen-game@0.12.0` went out pairing a `^0.5.0` worker with a 0.6.0
|
|
246
|
+
* shell. A Flutter line move therefore costs a follow-up scaffolder patch, and
|
|
247
|
+
* `scripts/scaffold-e2e.mjs` is what refuses to let it be forgotten: it resolves
|
|
248
|
+
* both halves for real and compares the wire lines they land on.
|
|
249
|
+
*/
|
|
250
|
+
const flutterClientVersion = "^0.8.0";
|
|
251
|
+
|
|
252
|
+
/** Optional Firebase adapter installed by the standard app scaffold. */
|
|
253
|
+
const firebaseAdapterVersion = "^0.1.0";
|
|
254
|
+
|
|
255
|
+
/** Development-only contract compiler installed into the generated app. */
|
|
256
|
+
const dartCodegenVersion = "^0.1.0";
|
|
257
|
+
|
|
258
|
+
const gameSlug = (value: string): string => {
|
|
259
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value)) {
|
|
260
|
+
throw new Error("destination directory name must be a lowercase kebab-case slug, for example my-game");
|
|
261
|
+
}
|
|
262
|
+
return value;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
const dartName = (value: string): string => value.replaceAll("-", "_");
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The Android `applicationId`, and iOS bundle id, a scaffold at `directory`
|
|
269
|
+
* will produce, so the CLI can show it rather than describe it.
|
|
270
|
+
*
|
|
271
|
+
* `flutter create --org X --project-name Y` derives `X.Y`. The organization is
|
|
272
|
+
* the *prefix*, not the whole identifier, which is the part worth seeing
|
|
273
|
+
* before answering: Google Play makes it permanent at first upload.
|
|
274
|
+
*/
|
|
275
|
+
export function applicationId(directory: string, org?: string): string {
|
|
276
|
+
return `${org?.trim() || "com.example"}.${dartName(gameSlug(basename(resolve(directory))))}`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const title = (value: string): string =>
|
|
280
|
+
value
|
|
281
|
+
.split("-")
|
|
282
|
+
.map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`)
|
|
283
|
+
.join(" ");
|
|
284
|
+
|
|
285
|
+
const identifier = (value: string): string => {
|
|
286
|
+
const pascal = value
|
|
287
|
+
.split("-")
|
|
288
|
+
.map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`)
|
|
289
|
+
.join("");
|
|
290
|
+
return /^[0-9]/.test(pascal) ? `Game${pascal}` : pascal;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
export function detectPackageManager(userAgent = process.env.npm_config_user_agent): PackageManager | undefined {
|
|
294
|
+
if (userAgent?.startsWith("pnpm/")) return "pnpm";
|
|
295
|
+
if (userAgent?.startsWith("npm/")) return "npm";
|
|
296
|
+
return undefined;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Substitutes the scaffold's tokens, of which there are two deliberate kinds.
|
|
301
|
+
*
|
|
302
|
+
* `{{BRACED}}` for values that have no valid example: a package manager,
|
|
303
|
+
* an engine version, an Android package id. They appear only in manifests,
|
|
304
|
+
* READMEs, workflows and the `Appfile`: files nothing compiles.
|
|
305
|
+
*
|
|
306
|
+
* Bare words (`ExampleGame`, `example-game`, …) for names a real example game
|
|
307
|
+
* genuinely has. This is what keeps `templates/worker` and the Dart templates
|
|
308
|
+
* VALID, COMPILING SOURCE rather than text with holes in it, which the rest of
|
|
309
|
+
* this package leans on hard: `typecheck` runs `tsc` over `templates/worker`,
|
|
310
|
+
* the tests `import` its game module directly and build a real contract from
|
|
311
|
+
* it, and the `scaffold` job compiles the Dart templates. Bracing these would
|
|
312
|
+
* trade all of that for a marker.
|
|
313
|
+
*
|
|
314
|
+
* The cost, and the one rule for template authors: a template file cannot
|
|
315
|
+
* contain the literal string `example-game`, `Example Game`, `ExampleGame` or
|
|
316
|
+
* `example_game` and keep it; every occurrence is rewritten, in prose and in
|
|
317
|
+
* code alike. Write around it, or brace a new token instead.
|
|
318
|
+
*
|
|
319
|
+
* Note this means the set of files carrying a token changes whenever someone
|
|
320
|
+
* writes one into an existing file. Nothing needs to track that: `renderTree`
|
|
321
|
+
* decides what to rewrite from the bytes, not from a list of paths.
|
|
322
|
+
*/
|
|
323
|
+
function render(contents: string, name: string, manager: PackageManager, packageId: string): string {
|
|
324
|
+
const replacements: ReadonlyArray<readonly [string, string]> = [
|
|
325
|
+
["@game/example-game-server", `@game/${name}-server`],
|
|
326
|
+
["{{PACKAGE_MANAGER}}", manager],
|
|
327
|
+
["{{PACKAGE_ID}}", packageId],
|
|
328
|
+
["{{ENGINE_VERSION}}", engineVersion],
|
|
329
|
+
["ExampleGame", identifier(name)],
|
|
330
|
+
["Example Game", title(name)],
|
|
331
|
+
["example_game", dartName(name)],
|
|
332
|
+
["example-game", name],
|
|
333
|
+
];
|
|
334
|
+
return replacements.reduce((result, [from, to]) => result.replaceAll(from, to), contents);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* True when the bytes are valid UTF-8.
|
|
339
|
+
*
|
|
340
|
+
* This is not a guess at whether a file is "binary"; it is the precondition
|
|
341
|
+
* of the operation. Token substitution is `String.replaceAll`, so a file that
|
|
342
|
+
* cannot be decoded cannot take part, and one that can is safe to rewrite.
|
|
343
|
+
*
|
|
344
|
+
* Deliberately not an extension list. A DENY list (`.png`, `.jar`, …) fails
|
|
345
|
+
* silently in the dangerous direction: the day someone adds a `.webp`, it is
|
|
346
|
+
* corrupted with no error. An ALLOW list fails the safe way but fits this tree
|
|
347
|
+
* badly: `Gemfile`, `Fastfile`, `.nvmrc`, `.fvmrc` and `.ruby-version` all
|
|
348
|
+
* need rendering and none carry a usable extension, so it would have to be a
|
|
349
|
+
* list of extensions *and* a list of bare filenames, both drifting.
|
|
350
|
+
*
|
|
351
|
+
* `.template` is not the signal either, despite the name: it marks files a
|
|
352
|
+
* language server must not claim before they have an enclosing package. Five
|
|
353
|
+
* of them contain no token at all, and nine token-bearing files are not
|
|
354
|
+
* marked, so the two concepts are orthogonal here.
|
|
355
|
+
*
|
|
356
|
+
* `renderTree`'s test pins the resulting classification for the whole tree, so
|
|
357
|
+
* this stays a reviewed decision rather than an invisible one.
|
|
358
|
+
*/
|
|
359
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
360
|
+
|
|
361
|
+
export function decodeUtf8(bytes: Buffer): string | undefined {
|
|
362
|
+
try {
|
|
363
|
+
return utf8.decode(bytes);
|
|
364
|
+
} catch {
|
|
365
|
+
return undefined;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function renderTree(source: string, destination: string, name: string, manager: PackageManager, packageId: string): void {
|
|
370
|
+
cpSync(source, destination, { recursive: true });
|
|
371
|
+
// Walks the TEMPLATE, not the destination. The app overlay renders on top of
|
|
372
|
+
// a `flutter create` result, so walking the destination meant rewriting
|
|
373
|
+
// every file Flutter had just generated, including its binaries, for files
|
|
374
|
+
// this scaffolder does not own and has no business touching.
|
|
375
|
+
const visit = (directory: string): void => {
|
|
376
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
377
|
+
const templatePath = resolve(directory, entry.name);
|
|
378
|
+
if (entry.isDirectory()) {
|
|
379
|
+
visit(templatePath);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
if (!entry.isFile()) continue;
|
|
383
|
+
|
|
384
|
+
const rendered = resolve(destination, relative(source, templatePath));
|
|
385
|
+
const text = decodeUtf8(readFileSync(templatePath));
|
|
386
|
+
// Undecodable files are already in place from the copy above, byte for
|
|
387
|
+
// byte. Only decodable ones are rewritten.
|
|
388
|
+
if (text !== undefined) {
|
|
389
|
+
writeFileSync(rendered, render(text, name, manager, packageId));
|
|
390
|
+
}
|
|
391
|
+
// Template-only source must not be claimed by language servers before
|
|
392
|
+
// it has an enclosing generated package. Restore the real extension
|
|
393
|
+
// only in the rendered project.
|
|
394
|
+
if (entry.name.endsWith(".template")) {
|
|
395
|
+
renameSync(rendered, rendered.slice(0, -".template".length));
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
visit(source);
|
|
400
|
+
|
|
401
|
+
// npm deliberately excludes files named `.gitignore` from package
|
|
402
|
+
// tarballs. Their packaged twins live outside the C3 template so a direct
|
|
403
|
+
// Git-based C3 render does not inherit a scaffolder-only helper file.
|
|
404
|
+
const packagedGitignore = resolve(templatesRoot, "scaffold", `${basename(source)}.gitignore`);
|
|
405
|
+
if (existsSync(packagedGitignore)) {
|
|
406
|
+
writeFileSync(resolve(destination, ".gitignore"), render(readFileSync(packagedGitignore, "utf8"), name, manager, packageId));
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function packageCommand(manager: PackageManager, operation: "install" | "contract" | "cf-typegen"): [string, string[]] {
|
|
411
|
+
if (operation === "install") return [manager, ["install"]];
|
|
412
|
+
return [manager, ["run", operation]];
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Appends `block` to a file this scaffolder does not own, as its own paragraph.
|
|
417
|
+
*
|
|
418
|
+
* **Append, never insert.** That is the rule the three callers below follow, and
|
|
419
|
+
* it is what keeps them from competing with `flutter create` and `flutterfire
|
|
420
|
+
* configure` for position in the same files. A pure append cannot collide with
|
|
421
|
+
* whatever those tools write above it; the one edit here that ever needed a
|
|
422
|
+
* position, prepending a Kotlin `import`, was broken by an AGP upgrade and has
|
|
423
|
+
* since been rewritten away. See MAINTAINERS.md for the whole doctrine, including
|
|
424
|
+
* why FlutterFire's `// START:`/`// END:` marker comments are deliberately not
|
|
425
|
+
* copied.
|
|
426
|
+
*
|
|
427
|
+
* `contents` is passed in rather than read here because every caller has already
|
|
428
|
+
* read the file to decide whether its block is present, and two of them assert
|
|
429
|
+
* on the shape of what they found. This owns the whitespace and nothing else.
|
|
430
|
+
*
|
|
431
|
+
* That is worth one function because it was previously written three times with
|
|
432
|
+
* two different answers, so the desugaring block got a blank line before it and
|
|
433
|
+
* the other two did not, and the two Gradle blocks ended up flush against each
|
|
434
|
+
* other in every generated project. Separation belongs to the append, so the
|
|
435
|
+
* block constants carry no leading or trailing newline of their own.
|
|
436
|
+
*/
|
|
437
|
+
function appendBlock(path: string, contents: string, block: string): void {
|
|
438
|
+
appendFileSync(path, `${contents.endsWith("\n") ? "" : "\n"}\n${block}\n`);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const androidDesugaring = `// flutter_local_notifications requires desugaring in the application module.
|
|
442
|
+
// A library plugin cannot enable this compiler setting transitively.
|
|
443
|
+
android {
|
|
444
|
+
compileOptions {
|
|
445
|
+
isCoreLibraryDesugaringEnabled = true
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
dependencies {
|
|
450
|
+
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
|
|
451
|
+
}`;
|
|
452
|
+
|
|
453
|
+
function enableAndroidCoreLibraryDesugaring(appRoot: string): void {
|
|
454
|
+
const gradlePath = resolve(appRoot, "android/app/build.gradle.kts");
|
|
455
|
+
const gradle = readFileSync(gradlePath, "utf8");
|
|
456
|
+
if (!gradle.includes('id("com.android.application")')) {
|
|
457
|
+
throw new Error(`Flutter created an unexpected Android application build file: ${gradlePath}`);
|
|
458
|
+
}
|
|
459
|
+
const settingExists = gradle.includes("isCoreLibraryDesugaringEnabled");
|
|
460
|
+
const dependencyExists = gradle.includes("coreLibraryDesugaring(");
|
|
461
|
+
if (settingExists && dependencyExists) return;
|
|
462
|
+
if (settingExists || dependencyExists) {
|
|
463
|
+
throw new Error(`Flutter created an incomplete Android core library desugaring configuration: ${gradlePath}`);
|
|
464
|
+
}
|
|
465
|
+
appendBlock(gradlePath, gradle, androidDesugaring);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// A second top-level `android { }` block is valid Gradle Kotlin DSL, since Gradle
|
|
469
|
+
// merges repeated extension-configuration blocks in one file, which is what
|
|
470
|
+
// lets this stay a pure append, same as the desugaring block above. A second
|
|
471
|
+
// top-level `plugins { }` block is NOT valid (Gradle allows exactly one per
|
|
472
|
+
// script), which is why the Crashlytics Gradle plugin registration,
|
|
473
|
+
// `flutterfire configure`'s own territory, is deliberately left alone here.
|
|
474
|
+
//
|
|
475
|
+
// Parsed with the Kotlin stdlib rather than `java.util.Properties`, which is
|
|
476
|
+
// what keeps this appendable. `Properties` would need a real `import`, and
|
|
477
|
+
// Kotlin requires imports before every other top-level declaration, so using it
|
|
478
|
+
// meant also reaching into the very start of a file this scaffolder does not
|
|
479
|
+
// own. A fully-qualified `java.util.Properties()` reference was tried to avoid
|
|
480
|
+
// that, and does not resolve under AGP 9's Kotlin DSL script compilation
|
|
481
|
+
// (`flutter create`'s current default): "Unresolved reference 'util'".
|
|
482
|
+
// Confirmed by actually building a scaffolded project, not just reading it.
|
|
483
|
+
const androidReleaseSigning = `val releaseKeyProperties: Map<String, String> =
|
|
484
|
+
rootProject.file("key.properties")
|
|
485
|
+
.takeIf { it.exists() }
|
|
486
|
+
?.readLines()
|
|
487
|
+
?.map { it.trim() }
|
|
488
|
+
?.filter { it.isNotEmpty() && !it.startsWith("#") && it.contains("=") }
|
|
489
|
+
?.associate { it.substringBefore("=").trim() to it.substringAfter("=").trim() }
|
|
490
|
+
.orEmpty()
|
|
491
|
+
|
|
492
|
+
android {
|
|
493
|
+
signingConfigs {
|
|
494
|
+
create("release") {
|
|
495
|
+
storeFile = releaseKeyProperties["storeFile"]?.let { file(it) }
|
|
496
|
+
storePassword = releaseKeyProperties["storePassword"]
|
|
497
|
+
keyAlias = releaseKeyProperties["keyAlias"]
|
|
498
|
+
keyPassword = releaseKeyProperties["keyPassword"]
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
buildTypes {
|
|
502
|
+
release {
|
|
503
|
+
signingConfig = if (releaseKeyProperties["storeFile"] != null)
|
|
504
|
+
signingConfigs.getByName("release")
|
|
505
|
+
else
|
|
506
|
+
signingConfigs.getByName("debug")
|
|
507
|
+
isMinifyEnabled = true
|
|
508
|
+
isShrinkResources = true
|
|
509
|
+
proguardFiles(
|
|
510
|
+
getDefaultProguardFile("proguard-android-optimize.txt"),
|
|
511
|
+
"proguard-rules.pro",
|
|
512
|
+
)
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}`;
|
|
516
|
+
|
|
517
|
+
function enableAndroidReleaseSigning(appRoot: string): void {
|
|
518
|
+
const gradlePath = resolve(appRoot, "android/app/build.gradle.kts");
|
|
519
|
+
const gradle = readFileSync(gradlePath, "utf8");
|
|
520
|
+
// Not `gradle.includes("signingConfigs")`, because Flutter's own template already
|
|
521
|
+
// contains that substring (`signingConfig = signingConfigs.getByName("debug")`),
|
|
522
|
+
// so that check would always short-circuit and never append anything.
|
|
523
|
+
if (gradle.includes("releaseKeyProperties")) return;
|
|
524
|
+
// A pure append. This previously also PREPENDED `import java.util.Properties`,
|
|
525
|
+
// the most position-dependent edit here and the one already broken once by an
|
|
526
|
+
// AGP upgrade; see the block above for what replaced it.
|
|
527
|
+
appendBlock(gradlePath, gradle, androidReleaseSigning);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// `flutter_launcher_icons`/`flutter_native_splash` read these as plain
|
|
531
|
+
// top-level pubspec keys, so appending is safe regardless of what
|
|
532
|
+
// `flutter create` already wrote under `flutter:`. Deliberately omits
|
|
533
|
+
// `ios`/`macos`, since `scaffoldGame` only creates `--platforms android,web`, and
|
|
534
|
+
// `flutter_launcher_icons` errors if told to target a platform whose
|
|
535
|
+
// directory doesn't exist.
|
|
536
|
+
// The colours are the EigenInteractive palette (ink #1B1E24, paper #F4F1EA) because the
|
|
537
|
+
// shipped placeholder art is the EigenInteractive mark: the adaptive foreground is the
|
|
538
|
+
// reversed, light-on-dark variant, so an ink background is what makes it
|
|
539
|
+
// legible. Rebranding a game means replacing the four PNGs *and* these
|
|
540
|
+
// colours together. See https://eigeninteractive.com/docs/ship-it/branding.
|
|
541
|
+
const launcherIconsAndSplashConfig = `flutter_launcher_icons:
|
|
542
|
+
android: true
|
|
543
|
+
web:
|
|
544
|
+
generate: true
|
|
545
|
+
image_path: "assets/icon/icon.png"
|
|
546
|
+
image_path: "assets/icon/icon.png"
|
|
547
|
+
adaptive_icon_background: "#1B1E24"
|
|
548
|
+
adaptive_icon_foreground: "assets/icon/icon_foreground.png"
|
|
549
|
+
min_sdk_android: 21
|
|
550
|
+
|
|
551
|
+
flutter_native_splash:
|
|
552
|
+
color: "#F4F1EA"
|
|
553
|
+
color_dark: "#1B1E24"
|
|
554
|
+
image: assets/icon/splash.png
|
|
555
|
+
image_dark: assets/icon/splash_dark.png
|
|
556
|
+
fullscreen: true
|
|
557
|
+
android_12:
|
|
558
|
+
color: "#F4F1EA"
|
|
559
|
+
color_dark: "#1B1E24"
|
|
560
|
+
image: assets/icon/splash.png
|
|
561
|
+
image_dark: assets/icon/splash_dark.png
|
|
562
|
+
icon_background_color: "#F4F1EA"
|
|
563
|
+
icon_background_color_dark: "#1B1E24"
|
|
564
|
+
web: true`;
|
|
565
|
+
|
|
566
|
+
function configureLauncherIconsAndSplash(appRoot: string): void {
|
|
567
|
+
const pubspecPath = resolve(appRoot, "pubspec.yaml");
|
|
568
|
+
const pubspec = readFileSync(pubspecPath, "utf8");
|
|
569
|
+
if (pubspec.includes("flutter_launcher_icons:")) return;
|
|
570
|
+
appendBlock(pubspecPath, pubspec, launcherIconsAndSplashConfig);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export interface AddContinuousIntegrationOptions {
|
|
574
|
+
directory: string;
|
|
575
|
+
/** Overrides the manager recorded in the project's own package.json. */
|
|
576
|
+
packageManager?: PackageManager;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Adds the GitHub Actions workflows to an existing generated project.
|
|
581
|
+
*
|
|
582
|
+
* The companion to `ci: false`: a game can be built and played locally for as
|
|
583
|
+
* long as its author likes, then gain the same PR gate and signed release
|
|
584
|
+
* pipeline a `--ci` scaffold would have produced.
|
|
585
|
+
*/
|
|
586
|
+
export function addContinuousIntegration(options: AddContinuousIntegrationOptions): { root: string; files: string[] } {
|
|
587
|
+
const root = resolve(options.directory);
|
|
588
|
+
const manifestPath = resolve(root, "package.json");
|
|
589
|
+
if (!existsSync(manifestPath) || !existsSync(resolve(root, "server")) || !existsSync(resolve(root, "app"))) {
|
|
590
|
+
throw new Error(`not an EigenInteractive game project (expected package.json, server/ and app/): ${root}`);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as {
|
|
594
|
+
name?: string;
|
|
595
|
+
scripts?: Record<string, string>;
|
|
596
|
+
};
|
|
597
|
+
const name = gameSlug(manifest.name ?? basename(root));
|
|
598
|
+
|
|
599
|
+
// The generated `contract` script embeds the manager the project was
|
|
600
|
+
// scaffolded with (`cd server && pnpm run contract && …`), which is a more
|
|
601
|
+
// reliable signal than a lockfile: it is present before anything is
|
|
602
|
+
// installed, and it is what the project actually uses.
|
|
603
|
+
const recorded = manifest.scripts?.contract?.includes("pnpm ") ? "pnpm" : manifest.scripts?.contract?.includes("npm ") ? "npm" : undefined;
|
|
604
|
+
const manager = options.packageManager ?? recorded ?? detectPackageManager() ?? "pnpm";
|
|
605
|
+
|
|
606
|
+
// Only `{{PACKAGE_MANAGER}}` appears in these templates, but the real
|
|
607
|
+
// package id is read back rather than reconstructed, so a project scaffolded
|
|
608
|
+
// under a different `--org` cannot be silently rewritten to `com.example`.
|
|
609
|
+
const appfile = resolve(root, "app/fastlane/Appfile");
|
|
610
|
+
const packageId = existsSync(appfile) ? (/package_name\("([^"]+)"\)/.exec(readFileSync(appfile, "utf8"))?.[1] ?? `com.example.${dartName(name)}`) : `com.example.${dartName(name)}`;
|
|
611
|
+
|
|
612
|
+
const workflows = resolve(root, ".github/workflows");
|
|
613
|
+
const existing = existsSync(workflows) ? readdirSync(workflows).filter((f) => f === "checks.yml" || f === "release.yml") : [];
|
|
614
|
+
if (existing.length > 0) {
|
|
615
|
+
throw new Error(`refusing to overwrite existing workflows: ${existing.join(", ")}`);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
renderTree(resolve(templatesRoot, "ci"), root, name, manager, packageId);
|
|
619
|
+
return { root, files: [".github/workflows/checks.yml", ".github/workflows/release.yml"] };
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** Asks a command a question. `ok` is "ran and succeeded"; a tool that is not installed and one that fails are both `false`, because neither can be used. */
|
|
623
|
+
export type Probe = (command: string, args: string[]) => { ok: boolean; stdout: string };
|
|
624
|
+
|
|
625
|
+
const probeCommand: Probe = (command, args) => {
|
|
626
|
+
try {
|
|
627
|
+
return { ok: true, stdout: execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) };
|
|
628
|
+
} catch {
|
|
629
|
+
return { ok: false, stdout: "" };
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
|
|
633
|
+
/** One thing standing between this machine and a configured Firebase project, and the single command that clears it. */
|
|
634
|
+
export interface FirebaseProblem {
|
|
635
|
+
/** Said as a sentence fragment, so it reads after "Firebase is not set up here:". */
|
|
636
|
+
reason: string;
|
|
637
|
+
/** The one command that fixes this, and nothing else. */
|
|
638
|
+
fix: string;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export type FirebaseReadiness = { ready: true } | { ready: false; problems: FirebaseProblem[] };
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Whether this machine can configure Firebase, asked *before* the scaffold
|
|
645
|
+
* rather than after it.
|
|
646
|
+
*
|
|
647
|
+
* `configure_firebase` runs the same three checks and is the authority on
|
|
648
|
+
* them; this one exists only to move the answer earlier. Learning that
|
|
649
|
+
* `flutterfire` is missing costs nothing here and costs two minutes of Flutter
|
|
650
|
+
* and pub at the far end, which is where the step actually runs.
|
|
651
|
+
*
|
|
652
|
+
* Every problem, not the first one. The checks are independent (two CLIs from
|
|
653
|
+
* two ecosystems, plus a sign-in) so short-circuiting turns one setup into a
|
|
654
|
+
* sequence of runs that each reveal the next missing piece. Reported in the
|
|
655
|
+
* order they have to be fixed in: the CLI, then the sign-in it stores, then
|
|
656
|
+
* the bridge that consumes both.
|
|
657
|
+
*
|
|
658
|
+
* The sign-in check fails open, for the same reason it does there: only an
|
|
659
|
+
* answer that positively reports no accounts counts as "no", so a `firebase`
|
|
660
|
+
* that errors or grows a different output shape is left to the command that
|
|
661
|
+
* actually needs the credentials.
|
|
662
|
+
*/
|
|
663
|
+
export function firebaseReadiness(probe: Probe = probeCommand): FirebaseReadiness {
|
|
664
|
+
const problems: FirebaseProblem[] = [];
|
|
665
|
+
|
|
666
|
+
if (probe("firebase", ["--version"]).ok) {
|
|
667
|
+
if (signedOut(probe)) problems.push({ reason: "no Google account is signed in to the Firebase CLI", fix: "firebase login" });
|
|
668
|
+
} else {
|
|
669
|
+
// Nothing to say about the sign-in: the CLI that would answer is the one
|
|
670
|
+
// that is missing, and `firebase login` is what installing leads to anyway.
|
|
671
|
+
// Google's own installer, which picks a standalone binary or npm to suit
|
|
672
|
+
// the machine. `npm install -g firebase-tools` also works and is what this
|
|
673
|
+
// used to print, but it needs a global npm prefix the reader may not have
|
|
674
|
+
// write access to, and it is not the install the Firebase docs lead with.
|
|
675
|
+
problems.push({ reason: "the `firebase` CLI is not installed", fix: "curl -sL https://firebase.tools | bash" });
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
if (!probe("flutterfire", ["--version"]).ok) {
|
|
679
|
+
problems.push({ reason: "the `flutterfire` CLI is not installed", fix: "dart pub global activate flutterfire_cli" });
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
return problems.length === 0 ? { ready: true } : { ready: false, problems };
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Whether the Firebase CLI holds no credentials.
|
|
687
|
+
*
|
|
688
|
+
* `login:list --json` prints the stored refresh and access tokens along with
|
|
689
|
+
* the account list. Read the shape, count the entries, and never surface the
|
|
690
|
+
* output: not in a warning, not in a captured stream, not on the failure
|
|
691
|
+
* path. That is why this returns a boolean rather than the response.
|
|
692
|
+
*/
|
|
693
|
+
function signedOut(probe: Probe): boolean {
|
|
694
|
+
const accounts = probe("firebase", ["login:list", "--json"]);
|
|
695
|
+
if (!accounts.ok) return false;
|
|
696
|
+
try {
|
|
697
|
+
const { result } = JSON.parse(accounts.stdout) as { result?: unknown };
|
|
698
|
+
return Array.isArray(result) && result.length === 0;
|
|
699
|
+
} catch {
|
|
700
|
+
// Unparseable is not evidence of anything.
|
|
701
|
+
return false;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Whether the scaffold would land inside a repository that already exists.
|
|
707
|
+
*
|
|
708
|
+
* Asked of the nearest ancestor that exists, because the destination does not
|
|
709
|
+
* yet. The point is not to change what {@link scaffoldGame} does, which already
|
|
710
|
+
* declines to nest a repository, but to stop the CLI asking a question whose
|
|
711
|
+
* answer cannot matter.
|
|
712
|
+
*/
|
|
713
|
+
/**
|
|
714
|
+
* Why this destination cannot be scaffolded into, said as a whole message, or
|
|
715
|
+
* `undefined` when there is nothing in the way.
|
|
716
|
+
*
|
|
717
|
+
* A directory that exists and is *empty* is not in the way, since people make
|
|
718
|
+
* one out of habit, so it is removed and rewritten rather than refused over
|
|
719
|
+
* nothing. Anything with contents in it is refused, and a cloned repository is
|
|
720
|
+
* not an exception: `.git` is in the way like any other entry, and the message
|
|
721
|
+
* names it. Publishing into one would mean parking `.git`, renaming staging
|
|
722
|
+
* over the top and putting it back, with a failure in the middle able to
|
|
723
|
+
* orphan a remote, which is a lot of care to spend on a flow that has a
|
|
724
|
+
* one-line alternative.
|
|
725
|
+
*
|
|
726
|
+
* Refused, and deliberately not offered as a "remove it and continue?"
|
|
727
|
+
* question, which is where several scaffolders in this family go. This one
|
|
728
|
+
* writes ninety-odd files and runs `flutter create`; the cost of getting that
|
|
729
|
+
* answer wrong against a mistyped path has no upper bound, and `rm -rf` is one
|
|
730
|
+
* command that belongs to the person who can see what is in there. Every other
|
|
731
|
+
* question this CLI asks is reversible. This one would not be.
|
|
732
|
+
*
|
|
733
|
+
* Exported so the CLI can ask it before the first question rather than after
|
|
734
|
+
* the last one. {@link scaffoldGame} asks it again, for callers that are not
|
|
735
|
+
* the CLI.
|
|
736
|
+
*/
|
|
737
|
+
export function destinationProblem(directory: string): string | undefined {
|
|
738
|
+
const root = resolve(directory);
|
|
739
|
+
if (!existsSync(root)) return undefined;
|
|
740
|
+
|
|
741
|
+
if (!statSync(root).isDirectory()) return `${root} already exists, and is a file.`;
|
|
742
|
+
|
|
743
|
+
const entries = readdirSync(root);
|
|
744
|
+
if (entries.length === 0) return undefined;
|
|
745
|
+
|
|
746
|
+
// Named, not counted. "not empty" invites an `ls`; the three that are
|
|
747
|
+
// actually there usually settle whether this was the wrong path or a
|
|
748
|
+
// directory that has already been scaffolded once.
|
|
749
|
+
const shown = entries.slice(0, 3).sort().join(", ");
|
|
750
|
+
const rest = entries.length > 3 ? `, and ${entries.length - 3} more` : "";
|
|
751
|
+
return `${root} already exists, and is not empty: it holds ${shown}${rest}.\n\nScaffold somewhere else, or clear it out yourself. This will not delete a directory you already had.`;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
export function insideWorkTree(directory: string, probe: Probe = probeCommand): boolean {
|
|
755
|
+
let candidate = resolve(directory);
|
|
756
|
+
while (!existsSync(candidate)) {
|
|
757
|
+
const parent = dirname(candidate);
|
|
758
|
+
if (parent === candidate) return false;
|
|
759
|
+
candidate = parent;
|
|
760
|
+
}
|
|
761
|
+
return probe("git", ["-C", candidate, "rev-parse", "--is-inside-work-tree"]).ok;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Runs the Flutter client's `configure_firebase` against the generated app.
|
|
766
|
+
*
|
|
767
|
+
* The command owns everything about how Firebase is configured: which
|
|
768
|
+
* platforms, which CLIs must exist, whether anyone is signed in, and what to
|
|
769
|
+
* do when no project has been chosen yet. This only decides *when*: before the
|
|
770
|
+
* scaffold commit, so a configured project is committed configured.
|
|
771
|
+
*
|
|
772
|
+
* Not fatal. Every failure here (a missing `flutterfire`, no Google login, a
|
|
773
|
+
* cancelled picker) leaves a complete and usable project that is exactly what
|
|
774
|
+
* a scaffold without `--firebase` produces, so it warns with the command to
|
|
775
|
+
* re-run and lets the commit happen.
|
|
776
|
+
*/
|
|
777
|
+
function configureFirebase(appRoot: string, project: boolean | string, run: Runner, reporter: Reporter): "configured" | "failed" {
|
|
778
|
+
// FlutterFire asks before overwriting `firebase_options.dart`, and the
|
|
779
|
+
// scaffold has just written one, a throwing placeholder whose entire
|
|
780
|
+
// purpose is to be replaced by this step. Answering that is a question with
|
|
781
|
+
// one right answer, so the placeholder is moved out of the way and the
|
|
782
|
+
// question never gets asked.
|
|
783
|
+
const placeholder = resolve(appRoot, "lib/firebase_options.dart");
|
|
784
|
+
const parked = `${placeholder}.placeholder`;
|
|
785
|
+
const parking = existsSync(placeholder);
|
|
786
|
+
if (parking) renameSync(placeholder, parked);
|
|
787
|
+
|
|
788
|
+
try {
|
|
789
|
+
// `dart run` compiles the package executable on first use and says so.
|
|
790
|
+
// Doing it against `--help`, which returns immediately, moves that noise
|
|
791
|
+
// into a step whose output can be captured; the real run cannot be, since
|
|
792
|
+
// FlutterFire prompts through it.
|
|
793
|
+
reporter.step("Preparing the Firebase configurator", () => run("dart", ["run", "eigen_firebase:configure_firebase", "--help"], appRoot));
|
|
794
|
+
// `--worker` is what makes this fill in `FIREBASE_PROJECT_ID` as well as
|
|
795
|
+
// the app's own values. An app-only repository omits it and gets the app
|
|
796
|
+
// half; a combined scaffold has the Worker one directory over.
|
|
797
|
+
reporter.handOver("Configuring Firebase", () => run("dart", ["run", "eigen_firebase:configure_firebase", "--worker", "../server", ...(typeof project === "string" ? ["--project", project] : [])], appRoot));
|
|
798
|
+
if (parking) rmSync(parked, { force: true });
|
|
799
|
+
return "configured";
|
|
800
|
+
} catch {
|
|
801
|
+
// Back only if nothing took its place. FlutterFire writes
|
|
802
|
+
// `firebase_options.dart` before the service worker configuration is
|
|
803
|
+
// derived from it, so a late failure leaves a real one that is worth more
|
|
804
|
+
// than the placeholder.
|
|
805
|
+
if (parking) {
|
|
806
|
+
if (existsSync(placeholder)) rmSync(parked, { force: true });
|
|
807
|
+
else renameSync(parked, placeholder);
|
|
808
|
+
}
|
|
809
|
+
reporter.warn("Could not configure Firebase. The project is complete. Run `firebase:configure` yourself, then commit what it writes.");
|
|
810
|
+
return "failed";
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* Commits the scaffold, so the first `git diff` is the first game change.
|
|
816
|
+
*
|
|
817
|
+
* This matters more here than in a scaffolder that only writes source. The
|
|
818
|
+
* bootstrap runs `flutter_launcher_icons` and `flutter_native_splash`, which
|
|
819
|
+
* write generated-but-committed files across `android/`, `web/` and
|
|
820
|
+
* `assets/`; without a baseline the first branding change is indistinguishable
|
|
821
|
+
* from the ninety files the scaffolder happened to produce.
|
|
822
|
+
*
|
|
823
|
+
* Nothing here is fatal. The project is complete and valid before this runs,
|
|
824
|
+
* so a missing `git`, or the unconfigured `user.email` that a fresh CI image
|
|
825
|
+
* has, warns and leaves the tree alone rather than discarding a scaffold that
|
|
826
|
+
* took two minutes of Flutter and pub to produce.
|
|
827
|
+
*/
|
|
828
|
+
function initialiseRepository(root: string, name: string, run: Runner, reporter: Reporter): GitOutcome {
|
|
829
|
+
// Scaffolding inside an existing checkout (a monorepo, or a repository
|
|
830
|
+
// created ahead of time) is a legitimate thing to do, and a nested
|
|
831
|
+
// repository there is silent breakage: the outer `git add` records a gitlink
|
|
832
|
+
// and the app's files never leave the machine. Asked directly rather than
|
|
833
|
+
// through `run`, because it is a question, not a step.
|
|
834
|
+
try {
|
|
835
|
+
execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: root, stdio: "ignore" });
|
|
836
|
+
return "existing";
|
|
837
|
+
} catch {
|
|
838
|
+
// Not inside a work tree, which is the case this function is for.
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
try {
|
|
842
|
+
run("git", ["init", "--quiet"], root);
|
|
843
|
+
run("git", ["add", "--all"], root);
|
|
844
|
+
} catch {
|
|
845
|
+
reporter.warn("Could not initialise a git repository. The project is complete. Run `git init` yourself when ready.");
|
|
846
|
+
return "failed";
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
try {
|
|
850
|
+
run("git", ["commit", "--quiet", "--message", `Scaffold ${name}`], root);
|
|
851
|
+
} catch {
|
|
852
|
+
reporter.warn(`Initialised a repository and staged the scaffold, but could not commit it. Set \`user.name\` and \`user.email\`, then \`git commit -m "Scaffold ${name}"\`.`);
|
|
853
|
+
return "failed";
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
return "committed";
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
export function scaffoldGame(options: ScaffoldOptions): ScaffoldResult {
|
|
860
|
+
const root = resolve(options.directory);
|
|
861
|
+
const name = gameSlug(basename(root));
|
|
862
|
+
const manager = options.packageManager ?? detectPackageManager() ?? "pnpm";
|
|
863
|
+
const org = options.org?.trim() || "com.example";
|
|
864
|
+
// Fastlane's `Appfile` names the same package the build actually produces,
|
|
865
|
+
// and the CLI shows the same one before asking.
|
|
866
|
+
const packageId = applicationId(root, org);
|
|
867
|
+
const bootstrap = options.bootstrap ?? true;
|
|
868
|
+
const reporter = options.reporter ?? plainReporter;
|
|
869
|
+
const run = options.run ?? capturingRunner(reporter);
|
|
870
|
+
|
|
871
|
+
const occupied = destinationProblem(root);
|
|
872
|
+
if (occupied !== undefined) throw new Error(occupied);
|
|
873
|
+
// Empty, or `destinationProblem` would have said so. Removed rather than
|
|
874
|
+
// scaffolded into, because the rename below publishes the staging directory
|
|
875
|
+
// *as* this path and cannot do that while something is standing there.
|
|
876
|
+
if (existsSync(root)) rmdirSync(root);
|
|
877
|
+
|
|
878
|
+
mkdirSync(dirname(root), { recursive: true });
|
|
879
|
+
|
|
880
|
+
// Build beside the destination and publish it with one rename. Failed
|
|
881
|
+
// subprocesses never leave a half-scaffolded project at the requested path.
|
|
882
|
+
const stagingRoot = mkdtempSync(resolve(dirname(root), `.${basename(root)}-`));
|
|
883
|
+
try {
|
|
884
|
+
const serverRoot = resolve(stagingRoot, "server");
|
|
885
|
+
const appRoot = resolve(stagingRoot, "app");
|
|
886
|
+
|
|
887
|
+
renderTree(resolve(templatesRoot, "worker"), serverRoot, name, manager, packageId);
|
|
888
|
+
renderTree(resolve(templatesRoot, "project"), stagingRoot, name, manager, packageId);
|
|
889
|
+
// Opt-in. release.yml wants an upload keystore and a Play service account
|
|
890
|
+
// that a brand-new project does not have, so generating it by default
|
|
891
|
+
// means a red X on main from the first push until someone sets both up.
|
|
892
|
+
// `create-eigen-game add ci` writes the same files whenever it is wanted.
|
|
893
|
+
if (options.ci) renderTree(resolve(templatesRoot, "ci"), stagingRoot, name, manager, packageId);
|
|
894
|
+
|
|
895
|
+
if (bootstrap) {
|
|
896
|
+
reporter.step("Creating the Flutter app", () => {
|
|
897
|
+
run("flutter", ["create", "--empty", "--platforms", "android,web", "--project-name", dartName(name), "--org", org, appRoot], stagingRoot);
|
|
898
|
+
enableAndroidCoreLibraryDesugaring(appRoot);
|
|
899
|
+
enableAndroidReleaseSigning(appRoot);
|
|
900
|
+
});
|
|
901
|
+
} else {
|
|
902
|
+
mkdirSync(appRoot, { recursive: true });
|
|
903
|
+
}
|
|
904
|
+
renderTree(resolve(templatesRoot, "app-overlay"), appRoot, name, manager, packageId);
|
|
905
|
+
|
|
906
|
+
if (bootstrap) {
|
|
907
|
+
reporter.step("Adding the Flutter packages", () => {
|
|
908
|
+
configureLauncherIconsAndSplash(appRoot);
|
|
909
|
+
run("flutter", ["pub", "add", `eigen_flutter@${flutterClientVersion}`, `eigen_firebase@${firebaseAdapterVersion}`, "firebase_core@^4.9.0"], appRoot);
|
|
910
|
+
run("flutter", ["pub", "add", `dev:eigen_codegen@${dartCodegenVersion}`, "dev:flutter_launcher_icons", "dev:flutter_native_splash"], appRoot);
|
|
911
|
+
});
|
|
912
|
+
// Actually apply the icons rather than only configuring them. Both tools
|
|
913
|
+
// write generated files (mipmaps, `web/icons/`, splash drawables and
|
|
914
|
+
// styles) that are committed, not built; leaving them unrun would ship
|
|
915
|
+
// Flutter's own blue logo until a game author happened to notice.
|
|
916
|
+
reporter.step("Generating the icons and splash", () => {
|
|
917
|
+
run("dart", ["run", "flutter_launcher_icons"], appRoot);
|
|
918
|
+
run("dart", ["run", "flutter_native_splash:create"], appRoot);
|
|
919
|
+
});
|
|
920
|
+
const [install, installArgs] = packageCommand(manager, "install");
|
|
921
|
+
const [typegen, typegenArgs] = packageCommand(manager, "cf-typegen");
|
|
922
|
+
reporter.step("Installing the Worker packages", () => {
|
|
923
|
+
run(install, installArgs, serverRoot);
|
|
924
|
+
// `worker-configuration.d.ts` is committed, and its header stamps the
|
|
925
|
+
// workerd version that produced the runtime types. `wrangler` floats
|
|
926
|
+
// on a caret and Cloudflare ships workerd about weekly, so the copy in
|
|
927
|
+
// `templates/worker` is stale for every scaffold made more than a few
|
|
928
|
+
// days after it was last regenerated, and `wrangler dev` opens by
|
|
929
|
+
// saying the types might be out of date. Regenerating against the
|
|
930
|
+
// wrangler that was just installed, rather than the one this package
|
|
931
|
+
// was built with, is what makes that true. It has to follow the server
|
|
932
|
+
// install for the same reason it is worth doing: it reads the wrangler
|
|
933
|
+
// that install resolved.
|
|
934
|
+
run(typegen, typegenArgs, serverRoot);
|
|
935
|
+
// The root holds Biome, which lints and formats both the Worker and
|
|
936
|
+
// the repository's own JSON. Installed after the server so a failure
|
|
937
|
+
// here costs the cheaper of the two.
|
|
938
|
+
run(install, installArgs, stagingRoot);
|
|
939
|
+
});
|
|
940
|
+
const [contract, contractArgs] = packageCommand(manager, "contract");
|
|
941
|
+
reporter.step("Generating the contract and payloads", () => {
|
|
942
|
+
run(contract, contractArgs, serverRoot);
|
|
943
|
+
run("dart", ["run", "eigen_codegen:generate_payloads", "--contract", "../server/game-contract.json", "--output", "lib/game/generated/payloads.dart", "--fixtures-output", "test/fixtures"], appRoot);
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
renameSync(stagingRoot, root);
|
|
948
|
+
} catch (error) {
|
|
949
|
+
rmSync(stagingRoot, { recursive: true, force: true });
|
|
950
|
+
throw error;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// Both steps below are deliberately outside the staging guard: the project
|
|
954
|
+
// is published by this point, and neither a Firebase project that could not
|
|
955
|
+
// be configured nor a repository that failed to initialise is a reason to
|
|
956
|
+
// delete two minutes of Flutter and pub.
|
|
957
|
+
//
|
|
958
|
+
// Firebase first, so what it writes (`firebase.json`,
|
|
959
|
+
// `android/app/google-services.json`, the real `firebase_options.dart` and
|
|
960
|
+
// `web/firebase-config.js` in place of the throwing placeholders, and
|
|
961
|
+
// FlutterFire's two Gradle edits) lands in the scaffold commit rather than
|
|
962
|
+
// arriving as the project's first diff.
|
|
963
|
+
const firebase = options.firebase ? configureFirebase(resolve(root, "app"), options.firebase, run, reporter) : "skipped";
|
|
964
|
+
// What that step settled, so the summary can name what it did not.
|
|
965
|
+
// `configure_firebase` does the writing, including into the Worker's
|
|
966
|
+
// wrangler.jsonc, which is what `--worker` above is for.
|
|
967
|
+
const link = firebase === "configured" ? readFirebaseLink(root) : undefined;
|
|
968
|
+
const git = (options.git ?? bootstrap) ? initialiseRepository(root, name, run, reporter) : "skipped";
|
|
969
|
+
|
|
970
|
+
return { root, name, git, firebase, link };
|
|
971
|
+
}
|