@wildshard/dev 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/bin/wildshard.mjs +75 -0
  2. package/lint/host-callbacks.d.mts +6 -0
  3. package/lint/host-callbacks.mjs +123 -0
  4. package/lint/ratchet.json +3 -0
  5. package/package.json +101 -3
  6. package/scripts/audit-assets.d.mts +10 -0
  7. package/scripts/audit-assets.mjs +151 -0
  8. package/scripts/bake/coatFiles.d.mts +6 -0
  9. package/scripts/bake/coatFiles.mjs +37 -0
  10. package/scripts/bake/navmeshGround.ts +22 -0
  11. package/scripts/bake/near-placeholder.mjs +331 -0
  12. package/scripts/bake/viewmodelBytes.ts +26 -0
  13. package/scripts/bake/viewmodelPage.ts +11 -0
  14. package/scripts/bake-catalogue.mjs +44 -0
  15. package/scripts/bake-check.mjs +54 -0
  16. package/scripts/bake-chunk.mjs +124 -0
  17. package/scripts/bake-cloud-field.mjs +24 -0
  18. package/scripts/bake-coats.mjs +110 -0
  19. package/scripts/bake-data-maps.d.mts +24 -0
  20. package/scripts/bake-data-maps.mjs +78 -0
  21. package/scripts/bake-entry-programs.mjs +126 -0
  22. package/scripts/bake-geometry.mjs +106 -0
  23. package/scripts/bake-ktx2.mjs +477 -0
  24. package/scripts/bake-map-glb.mjs +127 -0
  25. package/scripts/bake-map-rest.d.mts +7 -0
  26. package/scripts/bake-map-rest.mjs +50 -0
  27. package/scripts/bake-maps.mjs +200 -0
  28. package/scripts/bake-navmesh.mjs +259 -0
  29. package/scripts/bake-packs.mjs +129 -0
  30. package/scripts/bake-pickups.mjs +102 -0
  31. package/scripts/bake-query-terrain.mjs +64 -0
  32. package/scripts/bake-textures.mjs +80 -0
  33. package/scripts/bake-viewmodel-sets.mjs +137 -0
  34. package/scripts/bake-voxel-ao.mjs +119 -0
  35. package/scripts/bake-water-ripples.mjs +25 -0
  36. package/scripts/browser-imports.d.mts +2 -0
  37. package/scripts/browser-imports.mjs +40 -0
  38. package/scripts/browser-machine-loader-proof.mjs +39 -0
  39. package/scripts/browser-machine-loader.d.mts +8 -0
  40. package/scripts/browser-machine-loader.mjs +87 -0
  41. package/scripts/browser-playwright.d.mts +10 -0
  42. package/scripts/browser-playwright.mjs +5 -0
  43. package/scripts/browser-test.d.mts +4 -0
  44. package/scripts/browser-test.mjs +18 -0
  45. package/scripts/build-sdk.mjs +95 -0
  46. package/scripts/build-shardfiles.d.mts +7 -0
  47. package/scripts/build-shardfiles.mjs +230 -0
  48. package/scripts/capture-hero.mjs +211 -0
  49. package/scripts/chromium-keychain.d.mts +1 -0
  50. package/scripts/chromium-keychain.mjs +7 -0
  51. package/scripts/entry-reads/crawl.ts +152 -0
  52. package/scripts/gen-host-catalogue.d.mts +14 -0
  53. package/scripts/gen-host-catalogue.mjs +108 -0
  54. package/scripts/gen-shards.d.mts +17 -0
  55. package/scripts/gen-shards.mjs +311 -0
  56. package/scripts/goldens/plot-inputs.d.mts +12 -0
  57. package/scripts/goldens/plot-inputs.mjs +46 -0
  58. package/scripts/gpu-texmem.mjs +98 -0
  59. package/scripts/ktx2-ab.mjs +111 -0
  60. package/scripts/map-bake-frames.d.mts +4 -0
  61. package/scripts/map-bake-frames.mjs +23 -0
  62. package/scripts/map-world.mjs +162 -0
  63. package/scripts/memory-product.mjs +62 -0
  64. package/scripts/music/export-midi.mjs +69 -0
  65. package/scripts/named-blob-output.d.mts +8 -0
  66. package/scripts/named-blob-output.mjs +48 -0
  67. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  68. package/scripts/preparation-browser.mjs +25 -0
  69. package/scripts/preparation-seed.mjs +15 -0
  70. package/scripts/prepare-product.d.mts +14 -0
  71. package/scripts/prepare-product.mjs +133 -0
  72. package/scripts/prove-walk.mjs +83 -0
  73. package/scripts/push-tables.d.mts +1 -0
  74. package/scripts/push-tables.mjs +28 -0
  75. package/scripts/record-shard-mounts.mjs +133 -0
  76. package/scripts/section-inventory.ts +209 -0
  77. package/scripts/shard-build-pool.d.mts +4 -0
  78. package/scripts/shard-build-pool.mjs +53 -0
  79. package/scripts/shard-milestones.d.mts +15 -0
  80. package/scripts/shard-milestones.mjs +105 -0
  81. package/scripts/shard-progress.mjs +212 -0
  82. package/scripts/shardfile-cold-boot.mjs +79 -0
  83. package/scripts/shardfile-rolldown.d.mts +2 -0
  84. package/scripts/shardfile-rolldown.mjs +32 -0
  85. package/scripts/shardfile-vite.d.mts +4 -0
  86. package/scripts/shardfile-vite.mjs +20 -0
  87. package/scripts/site-facts.mjs +88 -0
  88. package/scripts/test-template-gate.mjs +44 -0
  89. package/scripts/tex-tiers.mjs +240 -0
  90. package/scripts/unused-assets.mjs +173 -0
  91. package/scripts/wildshard.d.mts +4 -0
  92. package/scripts/wildshard.mjs +146 -0
  93. package/scripts/witness-generation.d.mts +10 -0
  94. package/scripts/witness-generation.mjs +45 -0
  95. package/src/.oxlintrc.json +12 -0
  96. package/src/cli/bin.mjs +8 -0
  97. package/src/cli/content-command.ts +44 -0
  98. package/src/cli/content.ts +287 -0
  99. package/src/cli/grid/command.ts +48 -0
  100. package/src/cli/grid/grid.ts +155 -0
  101. package/src/cli/help.ts +262 -0
  102. package/src/cli/hero/adopt.ts +109 -0
  103. package/src/cli/install-home.ts +40 -0
  104. package/src/cli/main.ts +142 -0
  105. package/src/cli/version.ts +63 -0
  106. package/src/server/app.ts +19 -0
  107. package/src/server/serve.ts +49 -0
  108. package/src/sharddev/bake/json.mjs +84 -0
  109. package/src/sharddev/bake/mapRest.ts +57 -0
  110. package/src/sharddev/bake/nativeRaster.ts +106 -0
  111. package/src/sharddev/bake/source-loader.mjs +55 -0
  112. package/src/sharddev/bake/splatLayers.ts +29 -0
  113. package/src/sharddev/bootInventory.ts +132 -0
  114. package/src/sharddev/check.ts +125 -0
  115. package/src/sharddev/checkProject.ts +134 -0
  116. package/src/sharddev/cli.ts +207 -0
  117. package/src/sharddev/dev.ts +150 -0
  118. package/src/sharddev/devClient.ts +120 -0
  119. package/src/sharddev/devRoot.ts +6 -0
  120. package/src/sharddev/engineMusic.ts +23 -0
  121. package/src/sharddev/projectEntryProof.ts +32 -0
  122. package/src/sharddev/test/diskScriptScenario.ts +88 -0
  123. package/src/sharddev/test/scriptScenario.ts +254 -0
  124. package/src/sharddev/tsconfig.json +3 -0
  125. package/src/sharddev/watch/page.ts +288 -0
  126. package/src/sharddev/watch/pageEntry.ts +44 -0
  127. package/src/sharddev/watch/parity-baseline.json +22 -0
  128. package/src/sharddev/watch/parity.mjs +194 -0
  129. package/src/sharddev/watch/proof.mjs +199 -0
  130. package/src/sharddev/watch/socket.ts +57 -0
  131. package/src/sharddev/watch/watch.ts +382 -0
  132. package/src/shared/health.ts +10 -0
  133. package/src/tools/build-web.ts +59 -0
  134. package/src/web/app.tsx +53 -0
  135. package/src/web/index.html +12 -0
  136. package/src/web/main.tsx +10 -0
  137. package/tsconfig.author.json +25 -0
  138. package/tsconfig.json +47 -0
  139. package/README.md +0 -3
@@ -0,0 +1,12 @@
1
+ {
2
+ "$schema": "../../sdk/node_modules/oxlint/configuration_schema.json",
3
+ "extends": ["../../../kit/.oxlintrc.json"],
4
+ // oxlint does not inherit ignorePatterns through extends (K11, J329).
5
+ "ignorePatterns": [
6
+ "scripts/**",
7
+ "dist/**",
8
+ "test/fixtures/**",
9
+ "test-results/**",
10
+ "playwright-report/**"
11
+ ]
12
+ }
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { installFormatHook } from '@wildshard/format/formatHook'
3
+
4
+ // The `wildshard` bin. Node will not strip types under node_modules (J53), so
5
+ // an installed CLI needs format's hook before its first .ts. The hook covers
6
+ // everything under node_modules/@wildshard/, this package too.
7
+ installFormatHook()
8
+ await import('./main.ts')
@@ -0,0 +1,44 @@
1
+ /* eslint-disable no-magic-numbers */
2
+ import { formatContent, readContent } from './content.ts'
3
+
4
+ const EXIT_OK = 0
5
+ const EXIT_USAGE = 1
6
+ const EXIT_ERROR = 2
7
+ const EXIT_FAILED = 3
8
+ const [dir, ...options] = process.argv.slice(2)
9
+ const flags: { bar?: string; unknown?: string } = {}
10
+ for (let index = 0; index < options.length; index += 1) {
11
+ const option = options[index]
12
+ if (option === '--bar') {
13
+ index += 1
14
+ flags.bar = options[index] ?? ''
15
+ } else if (option?.startsWith('--bar=') === true) {
16
+ flags.bar = option.slice('--bar='.length)
17
+ } else {
18
+ flags.unknown = option ?? ''
19
+ }
20
+ }
21
+
22
+ const { bar, unknown } = flags
23
+
24
+ if (dir === undefined) {
25
+ process.stderr.write('wildshard: content needs a built shard directory\n')
26
+ process.exitCode = EXIT_USAGE
27
+ } else if (
28
+ unknown !== undefined ||
29
+ (bar !== undefined && bar !== 'templates')
30
+ ) {
31
+ process.stderr.write(
32
+ `wildshard: content does not know ${unknown ?? `--bar=${bar}`}\n`,
33
+ )
34
+ process.exitCode = EXIT_USAGE
35
+ } else {
36
+ try {
37
+ const report = readContent(dir, bar)
38
+ process.stdout.write(formatContent(report, bar))
39
+ process.exitCode = report.short.length === 0 ? EXIT_OK : EXIT_FAILED
40
+ } catch (error: unknown) {
41
+ process.stderr.write(`wildshard: content failed: ${String(error)}\n`)
42
+ process.exitCode = EXIT_ERROR
43
+ }
44
+ }
@@ -0,0 +1,287 @@
1
+ /* eslint-disable max-lines-per-function, max-statements, no-magic-numbers, node/no-sync, unicorn/explicit-length-check, unicorn/import-style, unicorn/max-nested-calls, unicorn/no-array-callback-reference, unicorn/no-nested-ternary, typescript/array-type, typescript/explicit-function-return-type, typescript/no-unsafe-type-assertion, typescript/prefer-readonly-parameter-types */
2
+ import { readFileSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+
5
+ type Json = Record<string, unknown>
6
+
7
+ interface ContentCounts {
8
+ readonly weapons: number
9
+ readonly loadoutWeapons: number
10
+ readonly pickups: number
11
+ readonly hostileSpecies: number
12
+ readonly bodies: number
13
+ readonly groups: number
14
+ readonly brainKinds: number
15
+ readonly creatureStrikes: number
16
+ readonly bossHp: number
17
+ readonly bossStrikes: number
18
+ readonly npcs: number
19
+ readonly dialogueStates: number
20
+ readonly quests: number
21
+ readonly questSteps: number
22
+ readonly interactables: number
23
+ readonly movers: number
24
+ readonly achievements: number
25
+ readonly pois: number
26
+ }
27
+
28
+ interface ContentReport {
29
+ readonly slug: string
30
+ readonly counts: ContentCounts
31
+ readonly short: readonly string[]
32
+ }
33
+
34
+ const TEMPLATE_BAR: ReadonlyArray<
35
+ readonly [keyof ContentCounts, number, string]
36
+ > = [
37
+ ['loadoutWeapons', 1, 'weapons in loadout'],
38
+ ['pickups', 2, 'placed pickups'],
39
+ ['hostileSpecies', 4, 'hostile species'],
40
+ ['bodies', 12, 'bodies'],
41
+ ['groups', 1, 'creature groups'],
42
+ ['brainKinds', 3, 'brain kinds'],
43
+ ['creatureStrikes', 4, 'creature strikes'],
44
+ ['bossHp', 400, 'boss hp'],
45
+ ['bossStrikes', 3, 'boss strikes'],
46
+ ['npcs', 1, 'NPCs'],
47
+ ['dialogueStates', 2, 'dialogue states'],
48
+ ['quests', 1, 'quests'],
49
+ ['questSteps', 4, 'quest steps'],
50
+ ['interactables', 3, 'interactables'],
51
+ ['movers', 1, 'movers'],
52
+ ['achievements', 2, 'achievements'],
53
+ ['pois', 8, 'POIs'],
54
+ ]
55
+
56
+ function record(value: unknown): Json {
57
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
58
+ ? (value as Json)
59
+ : {}
60
+ }
61
+ function array(value: unknown): readonly unknown[] {
62
+ return Array.isArray(value) ? value : []
63
+ }
64
+ function number(value: unknown): number {
65
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0
66
+ }
67
+ function text(value: unknown): string {
68
+ return typeof value === 'string' ? value : ''
69
+ }
70
+ function get(value: unknown, key: string): unknown {
71
+ return record(value)[key]
72
+ }
73
+
74
+ function section(dir: string, name: string): Json {
75
+ try {
76
+ return record(
77
+ JSON.parse(
78
+ readFileSync(resolve(dir, 'sections', `${name}.json`), 'utf8'),
79
+ ),
80
+ )
81
+ } catch (error: unknown) {
82
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
83
+ return {}
84
+ }
85
+ throw error
86
+ }
87
+ }
88
+
89
+ function itemRows(items: Json): readonly Json[] {
90
+ return array(get(get(items, 'items'), 'rows')).map(record)
91
+ }
92
+ function speciesRows(species: Json): readonly Json[] {
93
+ return array(get(get(species, 'rows'), 'species')).map(record)
94
+ }
95
+ function creaturesOf(creatures: Json): Json {
96
+ return record(get(creatures, 'creatures'))
97
+ }
98
+ function maxHp(species: readonly Json[]): number {
99
+ return Math.max(
100
+ 0,
101
+ ...species.flatMap(row =>
102
+ array(get(row, 'variants'))
103
+ .map(record)
104
+ .map(variant => number(get(variant, 'hp'))),
105
+ ),
106
+ )
107
+ }
108
+
109
+ /** Count both row-authored and native platform-section shapes without reading source. */
110
+ function readContent(dir: string, bar?: string): ContentReport {
111
+ const index = record(
112
+ JSON.parse(readFileSync(resolve(dir, 'shard.json'), 'utf8')),
113
+ )
114
+ const items = section(dir, 'combat/items')
115
+ const creatures = creaturesOf(section(dir, 'actors/creatures'))
116
+ const species = speciesRows(section(dir, 'actors/species'))
117
+ const strikes = array(
118
+ get(get(record(section(dir, 'combat/strikes')), 'rows'), 'strikes'),
119
+ ).map(record)
120
+ const nativeStrikes = array(section(dir, 'actors/strikes')).map(record)
121
+ const questSection = record(section(dir, 'quests/quests'))
122
+ const questData = record(get(questSection, 'quests'))
123
+ const quests = (
124
+ Array.isArray(get(questData, 'quests'))
125
+ ? array(get(questData, 'quests'))
126
+ : array(get(questSection, 'quests'))
127
+ ).map(record)
128
+ const host = section(dir, 'quests/host')
129
+ const npcs = array(get(record(section(dir, 'actors/npcs')), 'questNpcs')).map(
130
+ record,
131
+ )
132
+ const ledger = array(
133
+ get(record(section(dir, 'economy/ledger')), 'ledger'),
134
+ ).map(record)
135
+ const movers = array(get(record(section(dir, 'world/movers')), 'movers'))
136
+ const targets = record(section(dir, 'world/targets'))
137
+ const ui = section(dir, 'ui/ui')
138
+ const sourceItems = itemRows(items)
139
+ const weapons = sourceItems.filter(row => text(get(row, 'kind')) === 'weapon')
140
+ const itemData = record(get(items, 'items'))
141
+ const loadout = record(get(itemData, 'loadout'))
142
+ const loadoutIds = [
143
+ text(get(loadout, 'primary')),
144
+ text(get(loadout, 'secondary')),
145
+ ...array(get(loadout, 'weapons')).map(text),
146
+ ].filter(Boolean)
147
+ const spawns = array(get(creatures, 'spawns')).map(record)
148
+ const brains = array(get(creatures, 'brains')).map(record)
149
+ const groups = array(get(creatures, 'groups'))
150
+ const targetRows = record(get(targets, 'rows'))
151
+ const uiTargets = record(get(ui, 'targets'))
152
+ const interactionRows = [
153
+ ...array(get(targetRows, 'itemActions')),
154
+ ...array(get(targetRows, 'interactables')),
155
+ ...array(get(ui, 'interaction')),
156
+ ...array(get(ui, 'braziers')),
157
+ ...array(get(ui, 'talk')),
158
+ ...array(get(uiTargets, 'interactions')),
159
+ ...array(get(uiTargets, 'itemActions')),
160
+ ]
161
+ const nativePrograms = record(section(dir, 'actors/species-programs'))
162
+ const nativeSpecies = array(get(nativePrograms, 'species')).map(record)
163
+ const allSpecies = [...species, ...nativeSpecies]
164
+ const nativeBodies = array(section(dir, 'sim/bodies'))
165
+ // A talk is an NPC too: a row-authored shard's NPCs are its `targets.talks` (Mossgate's Lamplighter and Pond Hermit)
166
+ const talks = array(get(uiTargets, 'talks')).map(record)
167
+ const questNpcs = [...npcs, ...array(get(host, 'npcs')).map(record), ...talks]
168
+ // A placed pickup is a prompt whose scene hands over or refills an item (a rack's sword, a chest's oil)
169
+ const itemActionScenes = new Set(
170
+ [
171
+ ...array(get(targetRows, 'itemActions')),
172
+ ...array(get(uiTargets, 'itemActions')),
173
+ ]
174
+ .map(record)
175
+ .map(row => text(get(row, 'scene')))
176
+ .filter(Boolean),
177
+ )
178
+ const itemPrompts = array(get(uiTargets, 'interactions'))
179
+ .map(record)
180
+ .filter(row => itemActionScenes.has(text(get(row, 'scene'))))
181
+ // A brain's own strike (a ram, a dive) is its species' strike as much as a spawn's
182
+ // a brain names its strike (`strike`), or a challenge pair (`charge`, `close`)
183
+ const brainStrikes = new Map(
184
+ brains.map(row => [
185
+ text(get(row, 'id')),
186
+ text(get(row, 'strike')) ||
187
+ text(get(row, 'charge')) ||
188
+ text(get(row, 'close')),
189
+ ]),
190
+ )
191
+ const dialogue = [
192
+ ...array(get(host, 'dialogue')).map(record),
193
+ ...array(get(questData, 'dialogue')).map(record),
194
+ ...array(get(questSection, 'dialogue')).map(record),
195
+ ]
196
+ const manifest = get(record(section(dir, 'ui/level')), 'manifest')
197
+ const manifestPois = array(get(manifest, 'pois'))
198
+ const targetPois = [
199
+ ...array(get(targets, 'pois')),
200
+ ...array(get(targetRows, 'pois')),
201
+ ]
202
+ const count: ContentCounts = {
203
+ weapons: weapons.length,
204
+ loadoutWeapons: loadoutIds.filter(id =>
205
+ weapons.some(row => text(get(row, 'id')) === id),
206
+ ).length,
207
+ pickups:
208
+ array(get(itemData, 'pickups')).length +
209
+ array(get(targetRows, 'itemScenes')).length +
210
+ array(get(targetRows, 'loot')).length +
211
+ itemPrompts.length,
212
+ hostileSpecies: allSpecies.filter(
213
+ row => get(row, 'aggressive') === true || get(row, 'hostile') === true,
214
+ ).length,
215
+ bodies: Math.max(spawns.length, nativeBodies.length),
216
+ groups: groups.length,
217
+ brainKinds: new Set(
218
+ brains.map(row => text(get(row, 'kind'))).filter(Boolean),
219
+ ).size,
220
+ creatureStrikes:
221
+ new Set(
222
+ spawns
223
+ .filter(
224
+ row =>
225
+ text(get(row, 'strike')) !== '' ||
226
+ (brainStrikes.get(text(get(row, 'brain'))) ?? '') !== '',
227
+ )
228
+ .map(row => text(get(row, 'species'))),
229
+ ).size ||
230
+ new Set(
231
+ [...strikes, ...nativeStrikes]
232
+ .map(row => text(get(row, 'id')))
233
+ .filter(Boolean),
234
+ ).size,
235
+ bossHp: maxHp(allSpecies),
236
+ bossStrikes: [...strikes, ...nativeStrikes].filter(row =>
237
+ /boss|warden|wyrm/u.test(text(get(row, 'id'))),
238
+ ).length,
239
+ npcs: questNpcs.length,
240
+ dialogueStates: dialogue.reduce(
241
+ (total, row) => total + array(get(row, 'nodes')).length,
242
+ 0,
243
+ ),
244
+ quests: quests.length,
245
+ questSteps: quests.reduce(
246
+ (total, row) => total + array(get(row, 'steps')).length,
247
+ 0,
248
+ ),
249
+ interactables: interactionRows.length,
250
+ movers: movers.length,
251
+ achievements: ledger.reduce(
252
+ (total, row) =>
253
+ total +
254
+ array(get(row, 'rewards')).filter(
255
+ reward => text(get(reward, 'kind')) === 'achievement',
256
+ ).length,
257
+ 0,
258
+ ),
259
+ pois: manifestPois.length + targetPois.length,
260
+ }
261
+ const short =
262
+ bar === 'templates'
263
+ ? TEMPLATE_BAR.filter(([key, minimum]) => count[key] < minimum).map(
264
+ ([key, minimum, label]) => `${label}: ${count[key]}/${minimum}`,
265
+ )
266
+ : []
267
+ return {
268
+ slug: text(get(record(get(index, 'identity')), 'slug')) || dir,
269
+ counts: count,
270
+ short,
271
+ }
272
+ }
273
+
274
+ function formatContent(report: ContentReport, bar?: string): string {
275
+ const values = Object.entries(report.counts)
276
+ .map(([name, value]) => ` ${name}: ${value}`)
277
+ .join('\n')
278
+ const verdict =
279
+ bar === undefined
280
+ ? ''
281
+ : report.short.length === 0
282
+ ? `\nbar ${bar}: pass`
283
+ : `\nbar ${bar}: fail\n${report.short.map(line => ` short ${line}`).join('\n')}`
284
+ return `content ${report.slug}\n${values}${verdict}\n`
285
+ }
286
+
287
+ export { formatContent, readContent }
@@ -0,0 +1,48 @@
1
+ import { parseArgs } from 'node:util'
2
+
3
+ import { showGrid } from './grid.ts'
4
+
5
+ // `wildshard grid [--channel staging|prod|preview] [--server <url>]` (meta
6
+ // NEW-SHARD-E2E F29). bin/wildshard.mjs runs this file with the verb's
7
+ // arguments after it. Reads WILDSHARD_API_URL when --server is absent.
8
+
9
+ const EXIT_OK = 0
10
+ const EXIT_USAGE = 1
11
+ const EXIT_FAILED = 3
12
+ /** Where the verb's arguments start in process.argv: [node, this script, ...them]. */
13
+ const FIRST_ARG = 2
14
+ /** The verb takes no positional arguments. */
15
+ const NO_ARGS = 0
16
+
17
+ // oxlint-disable-next-line node/no-process-env -- the CLI is the env boundary
18
+ const fromEnv = process.env['WILDSHARD_API_URL'] ?? ''
19
+
20
+ function messageOf(error: unknown): string {
21
+ return error instanceof Error ? error.message : String(error)
22
+ }
23
+
24
+ try {
25
+ const { values, positionals } = parseArgs({
26
+ args: process.argv.slice(FIRST_ARG),
27
+ options: { channel: { type: 'string' }, server: { type: 'string' } },
28
+ allowPositionals: true,
29
+ })
30
+ if (positionals.length > NO_ARGS) {
31
+ process.stderr.write(
32
+ 'usage: wildshard grid [--channel staging|prod|preview] [--server <url>]\n',
33
+ )
34
+ process.exitCode = EXIT_USAGE
35
+ } else {
36
+ await showGrid({
37
+ server: values.server ?? fromEnv,
38
+ channel: values.channel,
39
+ report: (line: string): void => {
40
+ process.stdout.write(`${line}\n`)
41
+ },
42
+ })
43
+ process.exitCode = EXIT_OK
44
+ }
45
+ } catch (error: unknown) {
46
+ process.stderr.write(`wildshard: grid: ${messageOf(error)}\n`)
47
+ process.exitCode = EXIT_FAILED
48
+ }
@@ -0,0 +1,155 @@
1
+ import { installFormatHook } from '@wildshard/format/formatHook'
2
+
3
+ // Meta NEW-SHARD-E2E F29: `wildshard grid` reads the world grid a channel's
4
+ // page builds from, read-only and with no key: the public
5
+ // `GET /api/catalogue.json?channel=<channel>` (api-server
6
+ // `routes/catalogue-reads.ts`). It prints each taken cell with its shard,
7
+ // then the free cells inside the grid's radius (format's GRID_RADIUS), so
8
+ // an author sees where a new shard can go without reading source.
9
+
10
+ /** The API upload talks to when neither --server nor WILDSHARD_API_URL is set. */
11
+ const DEFAULT_SERVER = 'https://api.wildshard.io'
12
+
13
+ /** `--channel`'s name to the API's (J301): `prod` is `production`. */
14
+ const CHANNELS: Readonly<Record<string, string>> = {
15
+ preview: 'preview',
16
+ staging: 'staging',
17
+ prod: 'production',
18
+ }
19
+
20
+ type Cell = readonly [east: number, north: number]
21
+
22
+ /** One cell to the next along a grid row or column. */
23
+ const STEP = 1
24
+
25
+ interface GridCell {
26
+ readonly slug: string
27
+ readonly cell: Cell
28
+ }
29
+
30
+ interface GridOptions {
31
+ /** --server, else WILDSHARD_API_URL, else empty (then the default API). */
32
+ readonly server: string
33
+ /** --channel as typed; staging when absent. */
34
+ readonly channel: string | undefined
35
+ readonly report: (line: string) => void
36
+ }
37
+
38
+ /** The API's channel name, or undefined for one `--channel` does not take. */
39
+ function channelOf(raw = 'staging'): string | undefined {
40
+ return Object.hasOwn(CHANNELS, raw) ? CHANNELS[raw] : undefined
41
+ }
42
+
43
+ /** One catalogue grid row as a cell, or nothing for a row of another shape. */
44
+ function cellOf(row: unknown): GridCell[] {
45
+ if (typeof row !== 'object' || row === null) {
46
+ return []
47
+ }
48
+ const { slug, cell } = row as { slug?: unknown; cell?: unknown }
49
+ if (typeof slug !== 'string' || !Array.isArray(cell)) {
50
+ return []
51
+ }
52
+ const [east, north] = cell as unknown[]
53
+ return typeof east === 'number' && typeof north === 'number'
54
+ ? [{ slug, cell: [east, north] }]
55
+ : []
56
+ }
57
+
58
+ /** The cells of a catalogue.json document's `grid`. */
59
+ function cellsOf(document: unknown): readonly GridCell[] {
60
+ const grid =
61
+ typeof document === 'object' && document !== null && 'grid' in document
62
+ ? document.grid
63
+ : undefined
64
+ const cells =
65
+ typeof grid === 'object' && grid !== null && 'cells' in grid
66
+ ? grid.cells
67
+ : undefined
68
+ if (!Array.isArray(cells)) {
69
+ throw new TypeError('the catalogue has no grid cells')
70
+ }
71
+ return cells.flatMap((row: unknown): GridCell[] => cellOf(row))
72
+ }
73
+
74
+ const at = ([east, north]: Cell): string => `(${String(east)},${String(north)})`
75
+
76
+ const byRow = (left: GridCell, right: GridCell): number => {
77
+ const [leftEast, leftNorth] = left.cell
78
+ const [rightEast, rightNorth] = right.cell
79
+ return leftNorth - rightNorth || leftEast - rightEast
80
+ }
81
+
82
+ /** Every cell inside the radius that no shard holds, row by row. */
83
+ function freeCells(taken: ReadonlySet<string>, radius: number): string[] {
84
+ const free: string[] = []
85
+ for (let north = -radius; north <= radius; north += STEP) {
86
+ for (let east = -radius; east <= radius; east += STEP) {
87
+ if (!taken.has(at([east, north]))) {
88
+ free.push(at([east, north]))
89
+ }
90
+ }
91
+ }
92
+ return free
93
+ }
94
+
95
+ /** The channel's grid document from the API. */
96
+ async function fetchGrid(
97
+ server: string,
98
+ channel: string,
99
+ ): Promise<{ readonly url: string; readonly cells: readonly GridCell[] }> {
100
+ const url = new URL(
101
+ '/api/catalogue.json',
102
+ server === '' ? DEFAULT_SERVER : server,
103
+ )
104
+ url.searchParams.set('channel', channel)
105
+ const reply = await fetch(url)
106
+ if (!reply.ok) {
107
+ throw new Error(`GET ${url.href} answered ${String(reply.status)}`)
108
+ }
109
+ return {
110
+ url: url.href,
111
+ cells: cellsOf(await reply.json()).toSorted(
112
+ (left: GridCell, right: GridCell): number => byRow(left, right),
113
+ ),
114
+ }
115
+ }
116
+
117
+ /** The API channel `--channel` names, or a refusal for one it does not take. */
118
+ function requireChannel(raw: string | undefined): string {
119
+ const channel = channelOf(raw)
120
+ if (channel === undefined) {
121
+ throw new Error(
122
+ `grid takes --channel staging, prod or preview, not --channel ${String(raw)}`,
123
+ )
124
+ }
125
+ return channel
126
+ }
127
+
128
+ /** The grid's radius in cells from its centre (format's GRID_RADIUS). */
129
+ async function gridRadius(): Promise<number> {
130
+ installFormatHook()
131
+ const { GRID_RADIUS: radius } =
132
+ await import('@wildshard/format/contentBounds')
133
+ return radius
134
+ }
135
+
136
+ /** Print the channel's grid: every taken cell, then the free ones. */
137
+ async function showGrid(options: GridOptions): Promise<void> {
138
+ const channel = requireChannel(options.channel)
139
+ const radius = await gridRadius()
140
+ const { url, cells } = await fetchGrid(options.server, channel)
141
+ const side = String(radius + radius + STEP)
142
+ options.report(
143
+ `grid on ${channel}: ${side}x${side} cells, x and z from -${String(radius)} to ${String(radius)} (from ${url})`,
144
+ )
145
+ for (const row of cells) {
146
+ options.report(`taken ${at(row.cell)} ${row.slug}`)
147
+ }
148
+ const free = freeCells(
149
+ new Set(cells.map((row: GridCell): string => at(row.cell))),
150
+ radius,
151
+ )
152
+ options.report(`free ${String(free.length)}: ${free.join(' ')}`)
153
+ }
154
+
155
+ export { cellsOf, channelOf, showGrid }