@puzzmo/cli 1.0.87 → 1.0.89

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 (36) hide show
  1. package/lib/commands/puzzles.js +3 -13
  2. package/lib/commands/puzzles.js.map +1 -1
  3. package/lib/commands/rounds.d.ts +13 -0
  4. package/lib/commands/rounds.js +42 -0
  5. package/lib/commands/rounds.js.map +1 -0
  6. package/lib/commands/upload.js +24 -2
  7. package/lib/commands/upload.js.map +1 -1
  8. package/lib/index.js +15 -0
  9. package/lib/index.js.map +1 -1
  10. package/lib/queries/__generated__/cliRoundFixturesQuery.graphql.d.ts +29 -0
  11. package/lib/queries/__generated__/cliRoundFixturesQuery.graphql.js +184 -0
  12. package/lib/queries/__generated__/cliRoundFixturesQuery.graphql.js.map +1 -0
  13. package/lib/queries/rounds.d.ts +10 -0
  14. package/lib/queries/rounds.js +30 -0
  15. package/lib/queries/rounds.js.map +1 -0
  16. package/lib/util/api.d.ts +8 -0
  17. package/lib/util/api.js +22 -3
  18. package/lib/util/api.js.map +1 -1
  19. package/lib/util/discoverGames.d.ts +13 -0
  20. package/lib/util/discoverGames.js +27 -1
  21. package/lib/util/discoverGames.js.map +1 -1
  22. package/lib/util/tokenForGame.d.ts +3 -0
  23. package/lib/util/tokenForGame.js +14 -0
  24. package/lib/util/tokenForGame.js.map +1 -0
  25. package/package.json +1 -1
  26. package/schemas/puzzmo-file-schema.json +4 -0
  27. package/src/commands/puzzles.ts +3 -12
  28. package/src/commands/rounds.ts +56 -0
  29. package/src/commands/upload.test.ts +164 -0
  30. package/src/commands/upload.ts +27 -2
  31. package/src/index.ts +17 -0
  32. package/src/queries/__generated__/cliRoundFixturesQuery.graphql.ts +222 -0
  33. package/src/queries/rounds.ts +32 -0
  34. package/src/util/api.ts +38 -5
  35. package/src/util/discoverGames.ts +41 -1
  36. package/src/util/tokenForGame.ts +12 -0
@@ -0,0 +1,222 @@
1
+ /**
2
+ * @generated SignedSource<<ad1e4ca0faf950f8df336622238cda2f>>
3
+ * @lightSyntaxTransform
4
+ */
5
+
6
+ /* tslint:disable */
7
+ /* eslint-disable */
8
+ // @ts-nocheck
9
+
10
+ import { ConcreteRequest } from 'relay-runtime';
11
+ export type cliRoundFixturesQuery$variables = {
12
+ gameSlug: string;
13
+ token: string;
14
+ };
15
+ export type cliRoundFixturesQuery$data = {
16
+ readonly gameAchievementsDebug: {
17
+ readonly members: ReadonlyArray<{
18
+ readonly rounds: ReadonlyArray<{
19
+ readonly at: number;
20
+ readonly fixture: any | null | undefined;
21
+ readonly hasLog: boolean;
22
+ readonly outcome: string;
23
+ readonly verified: boolean;
24
+ }>;
25
+ readonly username: string;
26
+ }>;
27
+ } | null | undefined;
28
+ };
29
+ export type cliRoundFixturesQuery = {
30
+ response: cliRoundFixturesQuery$data;
31
+ variables: cliRoundFixturesQuery$variables;
32
+ };
33
+
34
+ const node: ConcreteRequest = (function(){
35
+ var v0 = {
36
+ "defaultValue": null,
37
+ "kind": "LocalArgument",
38
+ "name": "gameSlug"
39
+ },
40
+ v1 = {
41
+ "defaultValue": null,
42
+ "kind": "LocalArgument",
43
+ "name": "token"
44
+ },
45
+ v2 = [
46
+ {
47
+ "kind": "Variable",
48
+ "name": "gameSlug",
49
+ "variableName": "gameSlug"
50
+ },
51
+ {
52
+ "kind": "Variable",
53
+ "name": "token",
54
+ "variableName": "token"
55
+ }
56
+ ],
57
+ v3 = {
58
+ "alias": null,
59
+ "args": null,
60
+ "kind": "ScalarField",
61
+ "name": "username",
62
+ "storageKey": null
63
+ },
64
+ v4 = {
65
+ "alias": null,
66
+ "args": null,
67
+ "kind": "ScalarField",
68
+ "name": "at",
69
+ "storageKey": null
70
+ },
71
+ v5 = {
72
+ "alias": null,
73
+ "args": null,
74
+ "kind": "ScalarField",
75
+ "name": "outcome",
76
+ "storageKey": null
77
+ },
78
+ v6 = {
79
+ "alias": null,
80
+ "args": null,
81
+ "kind": "ScalarField",
82
+ "name": "verified",
83
+ "storageKey": null
84
+ },
85
+ v7 = {
86
+ "alias": null,
87
+ "args": null,
88
+ "kind": "ScalarField",
89
+ "name": "hasLog",
90
+ "storageKey": null
91
+ },
92
+ v8 = {
93
+ "alias": null,
94
+ "args": null,
95
+ "kind": "ScalarField",
96
+ "name": "fixture",
97
+ "storageKey": null
98
+ };
99
+ return {
100
+ "fragment": {
101
+ "argumentDefinitions": [
102
+ (v0/*:: as any*/),
103
+ (v1/*:: as any*/)
104
+ ],
105
+ "kind": "Fragment",
106
+ "metadata": null,
107
+ "name": "cliRoundFixturesQuery",
108
+ "selections": [
109
+ {
110
+ "alias": null,
111
+ "args": (v2/*:: as any*/),
112
+ "concreteType": "AchievementsDebug",
113
+ "kind": "LinkedField",
114
+ "name": "gameAchievementsDebug",
115
+ "plural": false,
116
+ "selections": [
117
+ {
118
+ "alias": null,
119
+ "args": null,
120
+ "concreteType": "AchievementMemberDebug",
121
+ "kind": "LinkedField",
122
+ "name": "members",
123
+ "plural": true,
124
+ "selections": [
125
+ (v3/*:: as any*/),
126
+ {
127
+ "alias": null,
128
+ "args": null,
129
+ "concreteType": "AchievementRoundTrace",
130
+ "kind": "LinkedField",
131
+ "name": "rounds",
132
+ "plural": true,
133
+ "selections": [
134
+ (v4/*:: as any*/),
135
+ (v5/*:: as any*/),
136
+ (v6/*:: as any*/),
137
+ (v7/*:: as any*/),
138
+ (v8/*:: as any*/)
139
+ ],
140
+ "storageKey": null
141
+ }
142
+ ],
143
+ "storageKey": null
144
+ }
145
+ ],
146
+ "storageKey": null
147
+ }
148
+ ],
149
+ "type": "Query",
150
+ "abstractKey": null
151
+ },
152
+ "kind": "Request",
153
+ "operation": {
154
+ "argumentDefinitions": [
155
+ (v1/*:: as any*/),
156
+ (v0/*:: as any*/)
157
+ ],
158
+ "kind": "Operation",
159
+ "name": "cliRoundFixturesQuery",
160
+ "selections": [
161
+ {
162
+ "alias": null,
163
+ "args": (v2/*:: as any*/),
164
+ "concreteType": "AchievementsDebug",
165
+ "kind": "LinkedField",
166
+ "name": "gameAchievementsDebug",
167
+ "plural": false,
168
+ "selections": [
169
+ {
170
+ "alias": null,
171
+ "args": null,
172
+ "concreteType": "AchievementMemberDebug",
173
+ "kind": "LinkedField",
174
+ "name": "members",
175
+ "plural": true,
176
+ "selections": [
177
+ (v3/*:: as any*/),
178
+ {
179
+ "alias": null,
180
+ "args": null,
181
+ "concreteType": "AchievementRoundTrace",
182
+ "kind": "LinkedField",
183
+ "name": "rounds",
184
+ "plural": true,
185
+ "selections": [
186
+ (v4/*:: as any*/),
187
+ (v5/*:: as any*/),
188
+ (v6/*:: as any*/),
189
+ (v7/*:: as any*/),
190
+ (v8/*:: as any*/),
191
+ {
192
+ "alias": null,
193
+ "args": null,
194
+ "kind": "ScalarField",
195
+ "name": "id",
196
+ "storageKey": null
197
+ }
198
+ ],
199
+ "storageKey": null
200
+ }
201
+ ],
202
+ "storageKey": null
203
+ }
204
+ ],
205
+ "storageKey": null
206
+ }
207
+ ]
208
+ },
209
+ "params": {
210
+ "cacheID": "cb33ad9d9ddc13040962cb0b33f440bc",
211
+ "id": null,
212
+ "metadata": {},
213
+ "name": "cliRoundFixturesQuery",
214
+ "operationKind": "query",
215
+ "text": "query cliRoundFixturesQuery(\n $token: String!\n $gameSlug: String!\n) {\n gameAchievementsDebug(token: $token, gameSlug: $gameSlug) {\n members {\n username\n rounds {\n at\n outcome\n verified\n hasLog\n fixture\n id\n }\n }\n }\n}\n"
216
+ }
217
+ };
218
+ })();
219
+
220
+ (node as any).hash = "8e55ffc09d8cf780e1e136991d939d8f";
221
+
222
+ export default node;
@@ -0,0 +1,32 @@
1
+ import { graphql, query } from "../util/belay.js"
2
+ import type { cliRoundFixturesQuery } from "./__generated__/cliRoundFixturesQuery.graphql.js"
3
+
4
+ const roundFixturesQuery = graphql`
5
+ query cliRoundFixturesQuery($token: String!, $gameSlug: String!) {
6
+ gameAchievementsDebug(token: $token, gameSlug: $gameSlug) {
7
+ members {
8
+ username
9
+ rounds {
10
+ at
11
+ outcome
12
+ verified
13
+ hasLog
14
+ fixture
15
+ }
16
+ }
17
+ }
18
+ }
19
+ `
20
+
21
+ export type TracedRound = { username: string; at: number; outcome: string; verified: boolean; hasLog: boolean; fixture: unknown }
22
+
23
+ /** Every round Puzzmo traced for the game's team (the last ten per member), each with its replay fixture when it kept the log */
24
+ export const fetchTracedRounds = async (apiURL: string, token: string, gameSlug: string): Promise<TracedRound[]> => {
25
+ const { data, errors } = await query<cliRoundFixturesQuery>(roundFixturesQuery, {
26
+ variables: { token, gameSlug },
27
+ url: `${apiURL}/graphql`,
28
+ })
29
+ if (errors?.length) throw new Error(errors.map((e) => e.message).join("; "))
30
+ if (!data?.gameAchievementsDebug) throw new Error(`No game named "${gameSlug}" is accessible with that token.`)
31
+ return data.gameAchievementsDebug.members.flatMap((member) => member.rounds.map((round) => ({ ...round, username: member.username })))
32
+ }
package/src/util/api.ts CHANGED
@@ -19,6 +19,8 @@ export type PuzzmoFile = {
19
19
  integrations?: Record<string, unknown>
20
20
  output?: {
21
21
  dir: string
22
+ /** The built server bundle, relative to puzzmo.json. Defaults to dist-server/server-bundle.js beside the dist folder */
23
+ serverBundle?: string
22
24
  }
23
25
  }
24
26
 
@@ -54,6 +56,10 @@ type CompleteResponse = {
54
56
  helpChanged: boolean
55
57
  gameURL: string | null
56
58
  versionsURL: string | null
59
+ /** What each capability of the build's server bundle offers, by name, when one was uploaded */
60
+ serverBundle: Record<string, string> | null
61
+ /** What Puzzmo noticed about the server bundle without refusing it, such as a live rule reading a fact it dropped */
62
+ serverBundleWarnings: string[]
57
63
  error?: string
58
64
  }
59
65
 
@@ -71,6 +77,8 @@ export type UploadFilesOptions = {
71
77
  iconSVG?: string | null
72
78
  /** Contents of the Markdown named by `game.helpPath`, synced onto the game's in-game help */
73
79
  helpMD?: string | null
80
+ /** The build's private server bundle (`output.serverBundle`, or dist-server/server-bundle.js), checked by Puzzmo then kept apart */
81
+ serverBundle?: string | null
74
82
  }
75
83
 
76
84
  /** Wraps fetch to surface the underlying network cause (DNS, ECONNREFUSED, TLS, etc.) */
@@ -102,11 +110,13 @@ const readResponse = async (res: Response, url: string, step: string, verbose: b
102
110
  throw new Error(`Invalid JSON response during ${step} (${url}): ${verbose ? text : text.slice(0, 200)}`)
103
111
  }
104
112
  if (!res.ok) {
105
- const body = json as { error?: string; validationErrors?: string[] }
113
+ const body = json as { error?: string; validationErrors?: string[]; logs?: string[] }
106
114
  const serverMsg = body.error || res.statusText || "Unknown error"
107
115
  const validation = body.validationErrors?.length ? `\n - ${body.validationErrors.join("\n - ")}` : ""
116
+ // A server bundle that fails its checks sends back what it logged, which is usually the clue
117
+ const logs = body.logs?.length ? `\n It logged:\n ${body.logs.join("\n ")}` : ""
108
118
  const detail = verbose ? `\n${JSON.stringify(json, null, 2)}` : ""
109
- throw new Error(`Server error during ${step} (${res.status} from ${url}): ${serverMsg}${validation}${detail}`)
119
+ throw new Error(`Server error during ${step} (${res.status} from ${url}): ${serverMsg}${validation}${logs}${detail}`)
110
120
  }
111
121
  return json
112
122
  }
@@ -175,7 +185,7 @@ export const uploadFiles = async (
175
185
  onProgress?: UploadProgress,
176
186
  options: UploadFilesOptions = {},
177
187
  ): Promise<CompleteResponse> => {
178
- const { verbose = false, description, repoURL, iconSVG, helpMD } = options
188
+ const { verbose = false, description, repoURL, iconSVG, helpMD, serverBundle } = options
179
189
  if (verbose) console.log(` API URL: ${apiURL}`)
180
190
 
181
191
  // Step 1: Init session (includes puzzmo.json metadata)
@@ -206,10 +216,31 @@ export const uploadFiles = async (
206
216
  onProgress?.(batchNum, totalBatches, totalUploaded)
207
217
  }
208
218
 
209
- // Step 3: Complete
219
+ // Step 3: The server bundle, before completing, so a bundle Puzzmo refuses fails the upload rather than live play
220
+ let serverBundleResult: Record<string, string> | null = null
221
+ let serverBundleWarnings: string[] = []
222
+ if (serverBundle) {
223
+ const step = "server bundle upload"
224
+ const bundleURL = `${apiURL}/cliUpload/${init.sessionID}/serverBundle?encoding=base64`
225
+ const res = await fetchWithContext(
226
+ bundleURL,
227
+ {
228
+ method: "POST",
229
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/octet-stream" },
230
+ body: Buffer.from(serverBundle).toString("base64"),
231
+ },
232
+ step,
233
+ verbose,
234
+ )
235
+ const checked = (await readResponse(res, bundleURL, step, verbose)) as { capabilities: Record<string, string>; warnings?: string[] }
236
+ serverBundleResult = checked.capabilities
237
+ serverBundleWarnings = checked.warnings ?? []
238
+ }
239
+
240
+ // Step 4: Complete
210
241
  const complete = (await jsonPost(`${apiURL}/cliUpload/${init.sessionID}/complete`, token, {}, "upload complete", verbose)) as Omit<
211
242
  CompleteResponse,
212
- "integrationsChanged" | "iconChanged" | "helpChanged" | "gameURL" | "versionsURL"
243
+ "integrationsChanged" | "iconChanged" | "helpChanged" | "gameURL" | "versionsURL" | "serverBundle" | "serverBundleWarnings"
213
244
  >
214
245
  if (verbose) console.log(` Assets base: ${complete.assetsBase}`)
215
246
  return {
@@ -219,5 +250,7 @@ export const uploadFiles = async (
219
250
  helpChanged: !!init.helpChanged,
220
251
  gameURL: init.gameURL ?? null,
221
252
  versionsURL: init.versionsURL ?? null,
253
+ serverBundle: serverBundleResult,
254
+ serverBundleWarnings,
222
255
  }
223
256
  }
@@ -29,6 +29,18 @@ export type DiscoveredGame = {
29
29
  iconPath: string | null
30
30
  /** Absolute path to the help Markdown named by `game.helpPath`, or null when the file sets no help */
31
31
  helpPath: string | null
32
+ /**
33
+ * Absolute path to the private server bundle to upload: `output.serverBundle` when set, otherwise dist-server/server-bundle.js beside
34
+ * the dist folder if that exists, otherwise null
35
+ */
36
+ serverBundlePath: string | null
37
+ }
38
+
39
+ /** Games which would all upload the same server bundle file */
40
+ export type SharedServerBundle = {
41
+ /** Absolute (real) path of the file they share */
42
+ serverBundlePath: string
43
+ slugs: string[]
32
44
  }
33
45
 
34
46
  /** A puzzmo.json that was found but could not be used (invalid JSON, schema errors, missing dist) */
@@ -108,17 +120,36 @@ export const discoverGames = async (rootDir: string, options: DiscoverOptions =
108
120
  }
109
121
  }
110
122
 
123
+ // Only an explicit path can be missing: the default is optional, as most games have no server bundle.
124
+ const serverBundlePath = resolveServerBundlePath(puzzmoFile, puzzmoJsonDir, distDir)
125
+ const configuredServerBundle = puzzmoFile.output?.serverBundle
126
+ if (requireDist && configuredServerBundle && serverBundlePath && !isFile(serverBundlePath))
127
+ fileErrors.push(
128
+ `Server bundle not found for ${puzzmoFile.game.slug}: "${configuredServerBundle}" (${serverBundlePath}) does not exist. Build the game first, or fix "output.serverBundle" in puzzmo.json.`,
129
+ )
130
+
111
131
  if (fileErrors.length) {
112
132
  errors.push({ puzzmoJsonPath, slug: puzzmoFile.game.slug, errors: fileErrors })
113
133
  continue
114
134
  }
115
135
 
116
- games.push({ puzzmoJsonPath, puzzmoJsonDir, puzzmoFile, distDir: distDir ?? "", iconPath, helpPath })
136
+ games.push({ puzzmoJsonPath, puzzmoJsonDir, puzzmoFile, distDir: distDir ?? "", iconPath, helpPath, serverBundlePath })
117
137
  }
118
138
 
119
139
  return { games, errors }
120
140
  }
121
141
 
142
+ /** Groups the games whose uploads would send the same server bundle file, so one game's bundle can't go up as another's */
143
+ export const findSharedServerBundles = (games: DiscoveredGame[]): SharedServerBundle[] => {
144
+ const slugsByPath = new Map<string, string[]>()
145
+ for (const game of games) {
146
+ if (!game.serverBundlePath) continue
147
+ const realPath = safeRealpath(game.serverBundlePath) ?? game.serverBundlePath
148
+ slugsByPath.set(realPath, [...(slugsByPath.get(realPath) ?? []), game.puzzmoFile.game.slug])
149
+ }
150
+ return [...slugsByPath].filter(([, slugs]) => slugs.length > 1).map(([serverBundlePath, slugs]) => ({ serverBundlePath, slugs }))
151
+ }
152
+
122
153
  /** Recursively finds puzzmo.json files under `dir`, skipping output / vendored folders. Tracks realpaths to avoid symlink cycles. */
123
154
  const findPuzzmoJsonFiles = (dir: string): string[] => {
124
155
  const found: string[] = []
@@ -171,6 +202,15 @@ const resolveDistDir = (puzzmoFile: PuzzmoFile, puzzmoJsonDir: string, repoRoot:
171
202
  return null
172
203
  }
173
204
 
205
+ /** Resolves `output.serverBundle` when set, otherwise the dist-server/server-bundle.js beside dist if one was built */
206
+ const resolveServerBundlePath = (puzzmoFile: PuzzmoFile, puzzmoJsonDir: string, distDir: string | null): string | null => {
207
+ if (puzzmoFile.output?.serverBundle) return path.resolve(puzzmoJsonDir, puzzmoFile.output.serverBundle)
208
+ if (!distDir) return null
209
+ // serverBundlePlugin writes it beside dist, never in it, so it can't be served to players
210
+ const sibling = path.join(path.dirname(distDir), "dist-server", "server-bundle.js")
211
+ return isFile(sibling) ? sibling : null
212
+ }
213
+
174
214
  /** Returns the directories from `start` walking up to (and including) `stop` */
175
215
  const walkUp = (start: string, stop: string): string[] => {
176
216
  const dirs: string[] = []
@@ -0,0 +1,12 @@
1
+ import { fetchGameSlugsForToken } from "../queries/puzzlePool.js"
2
+ import { getTokens, isServerReachable, sortByServerPriority, sourceToURL, type TokenEntry } from "./config.js"
3
+
4
+ /** Finds the first saved token, in server priority order, whose team owns the game */
5
+ export const findTokenForGame = async (gameSlug: string): Promise<TokenEntry | null> => {
6
+ for (const entry of sortByServerPriority(getTokens())) {
7
+ if (!(await isServerReachable(entry.source))) continue
8
+ const slugs = await fetchGameSlugsForToken(sourceToURL(entry.source), entry.token).catch(() => null)
9
+ if (slugs?.includes(gameSlug)) return entry
10
+ }
11
+ return null
12
+ }