@wildshard/upload 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.
@@ -0,0 +1,39 @@
1
+ import { installFormatHook } from '@wildshard/format/formatHook'
2
+
3
+ import { refusalHint, refusalNote } from '../../sharddev/refusals.ts'
4
+
5
+ import type { AudioReport } from '@wildshard/format/audioRules'
6
+
7
+ // AUDIO AU5 (meta docs/plans/AUDIO-PLAN.md, J299): format owns the audio
8
+ // rules. `pack` prints every finding as AMBER and still packs; `upload`
9
+ // refuses a red before it spends the upload, as api-server's admission
10
+ // will. A waiver lives in the shard source (`audio-waiver.json`).
11
+
12
+ /** The report as build prints it: totals, then one AMBER line per finding,
13
+ * each followed by its rule, fix and GUIDE.md link, named by its code (SA41). */
14
+ async function audioLines(report: Readonly<AudioReport>): Promise<string[]> {
15
+ installFormatHook()
16
+ const { audioReportLines } = await import('@wildshard/format/audioRules')
17
+ const [totals = '', ...findings] = audioReportLines(report)
18
+ return [
19
+ totals,
20
+ ...findings.flatMap((line: string, at: number): string[] => {
21
+ const finding = report.findings[at]
22
+ return finding === undefined
23
+ ? [line]
24
+ : [
25
+ line,
26
+ ` ${refusalHint(refusalNote('shardfile', finding.message, { code: finding.code }))}`,
27
+ ]
28
+ }),
29
+ ]
30
+ }
31
+
32
+ /** Refuse a red report, with format's reason. */
33
+ async function assertAudio(report: Readonly<AudioReport>): Promise<void> {
34
+ installFormatHook()
35
+ const { assertAudioAdmission } = await import('@wildshard/format/audioRules')
36
+ assertAudioAdmission(report)
37
+ }
38
+
39
+ export { assertAudio, audioLines }
@@ -0,0 +1,258 @@
1
+ import {
2
+ array,
3
+ boolean,
4
+ nullable,
5
+ number,
6
+ object,
7
+ optional,
8
+ safeParse,
9
+ string,
10
+ tuple,
11
+ } from 'valibot'
12
+
13
+ // `wildshard delete <slug>` (meta SHARD-DELETE DEL10, J307, J310): the
14
+ // owner's two calls back to back. Start (`POST /api/shards/:slug/delete`)
15
+ // answers a confirm token, good for 10 minutes, and a summary whose `note`
16
+ // says whether a signed release still plays the shard (DEL8); the author
17
+ // reads it and types the slug; finalize (`…/delete/finalize {confirm}`)
18
+ // spends the token. A typed slug that is not the slug finalizes nothing,
19
+ // and `yes` (`--yes`, for scripts) skips the typing. Both calls send the
20
+ // account key as `Authorization: Bearer`; the key and the token are never
21
+ // printed.
22
+
23
+ const OK = 200
24
+ const CONFLICT = 409
25
+ const SHORT_HASH = 8
26
+ const FIRST = 0
27
+
28
+ const ErrorSchema = object({ error: string() })
29
+ const VersionSchema = object({ version: string(), hash: string() })
30
+ const PointerSchema = object({ channel: string() })
31
+ const CellSchema = array(number())
32
+ const FreedSchema = tuple([number(), number()])
33
+ const PlacedSchema = object({ channel: string(), cells: array(CellSchema) })
34
+
35
+ const SummarySchema = object({
36
+ deleted: optional(boolean()),
37
+ versions: array(VersionSchema),
38
+ channels: array(PointerSchema),
39
+ grid: optional(array(PlacedSchema)),
40
+ note: optional(string()),
41
+ })
42
+
43
+ const StartSchema = object({
44
+ confirm: string(),
45
+ expiresAt: string(),
46
+ summary: SummarySchema,
47
+ })
48
+
49
+ const ChannelsSchema = array(string())
50
+
51
+ const FinalizeSchema = object({
52
+ deletedAt: string(),
53
+ channels: ChannelsSchema,
54
+ placements: ChannelsSchema,
55
+ /** The channels whose grid cells named the slug (api-server SA31). */
56
+ cells: optional(ChannelsSchema),
57
+ /** The slug's own grid cell, freed for the next new slug; null: it held none (SA31). */
58
+ freed: optional(nullable(FreedSchema)),
59
+ })
60
+
61
+ /** What finalize did, as the API answers it. */
62
+ type Finalized = Readonly<{
63
+ deletedAt: string
64
+ channels: readonly string[]
65
+ placements: readonly string[]
66
+ cells?: readonly string[] | undefined
67
+ freed?: readonly [number, number] | null | undefined
68
+ }>
69
+
70
+ type Started = Readonly<{
71
+ confirm: string
72
+ expiresAt: string
73
+ summary: Readonly<{
74
+ deleted?: boolean | undefined
75
+ versions: readonly Readonly<{ version: string; hash: string }>[]
76
+ channels: readonly Readonly<{ channel: string }>[]
77
+ grid?: readonly Placed[] | undefined
78
+ note?: string | undefined
79
+ }>
80
+ }>
81
+
82
+ type Placed = Readonly<{
83
+ channel: string
84
+ cells: readonly (readonly number[])[]
85
+ }>
86
+
87
+ interface DeleteOptions {
88
+ /** The api-server origin. */
89
+ readonly server: string
90
+ /** The owner's `wsk_` key. */
91
+ readonly apiKey: string
92
+ readonly slug: string
93
+ /** Skip the typed slug (`--yes`). */
94
+ readonly yes: boolean
95
+ /** Print the prompt and read one typed line; undefined when none comes. */
96
+ readonly ask: (prompt: string) => Promise<string | undefined>
97
+ readonly report: (line: string) => void
98
+ }
99
+
100
+ function jsonOf(text: string): unknown {
101
+ try {
102
+ const value: unknown = JSON.parse(text)
103
+ return value
104
+ } catch {
105
+ return undefined
106
+ }
107
+ }
108
+
109
+ function reasonOf(body: unknown): string {
110
+ const parsed = safeParse(ErrorSchema, body)
111
+ return parsed.success ? parsed.output.error : 'not an api-server reply'
112
+ }
113
+
114
+ /** One delete call: its status and parsed body. */
115
+ async function call(
116
+ options: DeleteOptions,
117
+ route: string,
118
+ body?: unknown,
119
+ ): Promise<Readonly<{ status: number; body: unknown }>> {
120
+ const slug = encodeURIComponent(options.slug)
121
+ const reply = await fetch(
122
+ new URL(`/api/shards/${slug}/${route}`, options.server),
123
+ {
124
+ method: 'POST',
125
+ headers: {
126
+ authorization: `Bearer ${options.apiKey}`,
127
+ 'content-type': 'application/json',
128
+ },
129
+ body: JSON.stringify(body ?? {}),
130
+ },
131
+ )
132
+ return { status: reply.status, body: jsonOf(await reply.text()) }
133
+ }
134
+
135
+ async function startDelete(options: DeleteOptions): Promise<Started> {
136
+ const reply = await call(options, 'delete')
137
+ const parsed = safeParse(StartSchema, reply.body)
138
+ if (reply.status !== OK || !parsed.success) {
139
+ throw new Error(
140
+ `delete ${options.slug}: start answered ${String(reply.status)}: ${reasonOf(reply.body)}`,
141
+ )
142
+ }
143
+ return parsed.output
144
+ }
145
+
146
+ function listed(names: readonly string[]): string {
147
+ return names.length === FIRST ? 'none' : names.join(', ')
148
+ }
149
+
150
+ /** Each grid cell placing the slug: `staging [2, 3]`. */
151
+ function gridCells(grid: readonly Placed[] | undefined): readonly string[] {
152
+ return (grid ?? []).flatMap((row: Placed): string[] =>
153
+ row.cells.map(
154
+ (cell: readonly number[]): string =>
155
+ `${row.channel} [${cell.join(', ')}]`,
156
+ ),
157
+ )
158
+ }
159
+
160
+ /** What start found, in the author's words. */
161
+ function summaryLines(slug: string, started: Started): readonly string[] {
162
+ const { summary } = started
163
+ const versions = summary.versions.map(
164
+ (row: Readonly<{ version: string; hash: string }>): string =>
165
+ `${row.version} ${row.hash.slice(FIRST, SHORT_HASH)}`,
166
+ )
167
+ const channels = summary.channels.map(
168
+ (row: Readonly<{ channel: string }>): string => row.channel,
169
+ )
170
+ return [
171
+ `delete ${slug}: ${String(versions.length)} versions (${listed(versions)})`,
172
+ `channels pointing at it: ${listed(channels)}`,
173
+ `grid cells placing it: ${listed(gridCells(summary.grid))}`,
174
+ ...(summary.note === undefined ? [] : [summary.note]),
175
+ ...(summary.deleted === true
176
+ ? [`${slug} is deleted already: finalize changes nothing`]
177
+ : []),
178
+ `the confirm token lasts until ${started.expiresAt} (10 minutes)`,
179
+ ]
180
+ }
181
+
182
+ /** What finalize did, in the author's words; the last line says deleted. */
183
+ function doneLines(slug: string, done: Finalized): readonly string[] {
184
+ const cells =
185
+ done.cells === undefined
186
+ ? ''
187
+ : `; grid cells dropped on: ${listed(done.cells)}`
188
+ const freed =
189
+ done.freed === undefined
190
+ ? ''
191
+ : `; grid cell freed: ${done.freed === null ? 'none' : `[${done.freed.join(', ')}]`}`
192
+ return [
193
+ `pointers dropped on: ${listed(done.channels)}; solo placements dropped on: ${listed(done.placements)}${cells}${freed}`,
194
+ `deleted ${slug} at ${done.deletedAt}: hidden from the catalogue and every grid`,
195
+ ]
196
+ }
197
+
198
+ async function finalizeDelete(
199
+ options: DeleteOptions,
200
+ confirm: string,
201
+ ): Promise<readonly string[]> {
202
+ const { slug } = options
203
+ const reply = await call(options, 'delete/finalize', { confirm })
204
+ const parsed = safeParse(FinalizeSchema, reply.body)
205
+ const reason = reasonOf(reply.body)
206
+ if (reply.status === CONFLICT && reason.includes('confirm token')) {
207
+ throw new Error(
208
+ `delete ${slug}: finalize answered 409: ${reason}. Nothing was deleted; start again with wildshard delete ${slug}`,
209
+ )
210
+ }
211
+ if (reply.status !== OK || !parsed.success) {
212
+ throw new Error(
213
+ `delete ${slug}: finalize answered ${String(reply.status)}: ${reason}`,
214
+ )
215
+ }
216
+ return doneLines(slug, parsed.output)
217
+ }
218
+
219
+ /** Why the author's answer does not confirm the delete, if it doesn't. */
220
+ async function notConfirmed(
221
+ options: DeleteOptions,
222
+ ): Promise<string | undefined> {
223
+ const { slug } = options
224
+ if (options.yes) {
225
+ return undefined
226
+ }
227
+ const typed = await options.ask(
228
+ `type ${slug} to delete it (anything else keeps it): `,
229
+ )
230
+ if (typed?.trim() === slug) {
231
+ return undefined
232
+ }
233
+ const what = typed === undefined ? 'nothing' : `"${typed.trim()}"`
234
+ return `delete ${slug} not confirmed: you typed ${what}, not ${slug}, so nothing was deleted`
235
+ }
236
+
237
+ /**
238
+ * Start, show the summary, take the typed slug (unless `yes`), finalize.
239
+ * Undefined once deleted, or why nothing was deleted.
240
+ */
241
+ async function deleteShard(
242
+ options: DeleteOptions,
243
+ ): Promise<string | undefined> {
244
+ const started = await startDelete(options)
245
+ for (const line of summaryLines(options.slug, started)) {
246
+ options.report(line)
247
+ }
248
+ const refused = await notConfirmed(options)
249
+ if (refused !== undefined) {
250
+ return refused
251
+ }
252
+ for (const line of await finalizeDelete(options, started.confirm)) {
253
+ options.report(line)
254
+ }
255
+ return undefined
256
+ }
257
+
258
+ export { type DeleteOptions, deleteShard }
@@ -0,0 +1,163 @@
1
+ import { readdir } from 'node:fs/promises'
2
+ import path from 'node:path'
3
+
4
+ import { isSceneShard } from './scene-card.ts'
5
+ import {
6
+ MANIFEST,
7
+ NONE,
8
+ STAMP,
9
+ UNKNOWN_TIME,
10
+ cardHashes,
11
+ heroState,
12
+ readJson,
13
+ } from './stamp.ts'
14
+
15
+ import type { HeroState } from './stamp.ts'
16
+
17
+ // The cut's hero check (`wildshard build`, as it writes the shard file, SA3): see stamp.ts for what the stamp
18
+ // records. Jake, 2026-11-12 17:14 Cancún: "you have to update the hero
19
+ // images for the templates."
20
+
21
+ const CAPTURE = 'pnpm exec wildshard hero'
22
+
23
+ /** The shard source as the author names it: `src` in a single-shard repo (J317), else `src/shards/<name>`. */
24
+ function sourceOperand(shard: string): string {
25
+ return path.basename(shard) === 'src'
26
+ ? 'src'
27
+ : `src/shards/${path.basename(shard)}`
28
+ }
29
+
30
+ /** The capture command a refusal names, run from the shard project root. */
31
+ function captureCommand(shard: string): string {
32
+ return `${CAPTURE} ${sourceOperand(shard)} --base <served-build-url>`
33
+ }
34
+
35
+ /** The no-capture stamp, for hero files that already show this content. */
36
+ function stampExistingCommand(shard: string): string {
37
+ return `${CAPTURE} ${sourceOperand(shard)} --stamp-existing`
38
+ }
39
+
40
+ /** The source shard folder of a product built at `<root>/out/<name>`. */
41
+ function sourceShard(product: string): string {
42
+ const resolved = path.resolve(product)
43
+ const root = path.dirname(path.dirname(resolved))
44
+ return path.join(root, 'src', 'shards', path.basename(resolved))
45
+ }
46
+
47
+ /** Every file name in the product, without its extension: blobs are named by hash. */
48
+ async function productHashes(product: string): Promise<ReadonlySet<string>> {
49
+ const entries = await readdir(product, { recursive: true })
50
+ return new Set(entries.map((entry: string): string => path.parse(entry).name))
51
+ }
52
+
53
+ /** Refuse a product built before the stamped hero was captured. */
54
+ async function assertProductCarries(
55
+ product: string,
56
+ shard: string,
57
+ ): Promise<void> {
58
+ const card = await cardHashes(shard)
59
+ const held = await productHashes(product)
60
+ const missing = Object.keys(card).filter(
61
+ (name: string): boolean => !held.has(card[name] ?? ''),
62
+ )
63
+ if (missing.length > NONE) {
64
+ throw new Error(
65
+ `the shard file folder ${product} does not carry the captured hero (${missing.join(', ')}); it was built before the capture: rebuild it (pnpm build:shards), then build its shard file`,
66
+ )
67
+ }
68
+ }
69
+
70
+ /** The string at `keys` in parsed JSON, if there is one. */
71
+ function stringAt(value: unknown, keys: readonly string[]): string | undefined {
72
+ let at = value
73
+ for (const key of keys) {
74
+ at =
75
+ typeof at === 'object' && at !== null ? Reflect.get(at, key) : undefined
76
+ }
77
+ return typeof at === 'string' ? at : undefined
78
+ }
79
+
80
+ /**
81
+ * SA51: the slug of a product built as one output of a source that emits several (Open Plots: 17 outputs, each with its
82
+ * own card), when it differs from the source's own slug; undefined for the source's own product. Such an output never
83
+ * carries the source's hero files, so the carry check does not apply to it.
84
+ */
85
+ async function otherOutput(
86
+ product: string,
87
+ shard: string,
88
+ ): Promise<string | undefined> {
89
+ const output = stringAt(await readJson(path.join(product, 'shard.json')), [
90
+ 'identity',
91
+ 'slug',
92
+ ])
93
+ const own = stringAt(await readJson(path.join(shard, MANIFEST)), ['slug'])
94
+ return output !== undefined && own !== undefined && output !== own
95
+ ? output
96
+ : undefined
97
+ }
98
+
99
+ /** A fresh hero's line: the product carries it, unless the product is another output of its source (SA51). */
100
+ async function freshLine(
101
+ product: string,
102
+ shard: string,
103
+ hero: HeroState,
104
+ ): Promise<string> {
105
+ const captured = `hero: current (captured ${hero.captured ?? UNKNOWN_TIME})`
106
+ const output = await otherOutput(product, shard)
107
+ if (output === undefined) {
108
+ await assertProductCarries(product, shard)
109
+ return captured
110
+ }
111
+ return `${captured}; ${output} is one output of this source and wears its own card, so the source's hero is not looked for in it`
112
+ }
113
+
114
+ /** Why a hero that is neither fresh nor generated stops the cut, and the fix. */
115
+ function refusal(shard: string, hero: HeroState): string {
116
+ const name = path.basename(shard)
117
+ const capture = `serve this candidate in an engine build, then capture it: ${captureCommand(shard)}`
118
+ const adopt = `; or, only if the images already there show this content, stamp them with no capture: ${stampExistingCommand(shard)}`
119
+ if (hero.curated === true) {
120
+ return `the hero of ${name} is curated (${STAMP} "curated": true) and its stamp does not match this content or these images; keep the art and re-stamp it with no capture: ${stampExistingCommand(shard)}`
121
+ }
122
+ if (hero.state === 'unstamped') {
123
+ return `the hero of ${name} has no ${STAMP} stamp, so nothing says it shows this content; ${capture}${adopt}`
124
+ }
125
+ const captured = hero.captured ?? UNKNOWN_TIME
126
+ return hero.stamped === hero.content
127
+ ? `the hero files of ${name} are not the ones stamped (captured ${captured}), though the content is unchanged; ${capture}${adopt}`
128
+ : `the hero of ${name} is older than its content (captured ${captured}); ${capture}`
129
+ }
130
+
131
+ /**
132
+ * The cut's check. A built product lives at `<root>/out/<name>` and its
133
+ * source at `<root>/src/shards/<name>`. Throws for a stale or unstamped
134
+ * hero; reports and passes a generated card or a product with no source.
135
+ */
136
+ async function assertHeroCurrent(
137
+ product: string,
138
+ report: (line: string) => void,
139
+ source?: string,
140
+ ): Promise<void> {
141
+ // SA3: `build` names the project it built; a bare folder is read by layout.
142
+ const shard = source ?? sourceShard(product)
143
+ // F28: a scene shard keeps no manifest; its folder (a shard.config.ts) is still the source a hero shows
144
+ if (
145
+ (await readJson(path.join(shard, MANIFEST))) === undefined &&
146
+ !(await isSceneShard(shard))
147
+ ) {
148
+ report(`hero: no source shard with a ${MANIFEST} at ${shard}; not checked`)
149
+ return
150
+ }
151
+ const hero = await heroState(shard)
152
+ if (hero.state === 'fresh') {
153
+ report(await freshLine(product, shard, hero))
154
+ } else if (hero.state === 'generated') {
155
+ report(
156
+ `hero: generated card, no captured hero; capture one: ${captureCommand(shard)}`,
157
+ )
158
+ } else {
159
+ throw new Error(refusal(shard, hero))
160
+ }
161
+ }
162
+
163
+ export { assertHeroCurrent }
@@ -0,0 +1,46 @@
1
+ import { stat } from 'node:fs/promises'
2
+ import path from 'node:path'
3
+
4
+ // Meta NEW-SHARD-E2E F28: a scene shard keeps no manifest.json (its discovery
5
+ // is generated), so its captured hero is `card/<slot>.jpg` in the shard
6
+ // folder, which the generated discovery card wears from the next build on
7
+ // (`authorManifest`).
8
+
9
+ const SCENE_CARD = 'card'
10
+ const SCENE_SLOTS = ['thumb', 'portrait', 'landscape'] as const
11
+
12
+ /** Whether a file is there; an unreadable path counts as absent. */
13
+ async function present(file: string): Promise<boolean> {
14
+ return await stat(file).then(
15
+ (): boolean => true,
16
+ (): boolean => false,
17
+ )
18
+ }
19
+
20
+ /** A scene shard's source folder: its `shard.config.ts`. */
21
+ async function isSceneShard(shard: string): Promise<boolean> {
22
+ return await present(path.join(shard, 'shard.config.ts'))
23
+ }
24
+
25
+ /** A scene shard's captured card files, by slot: only the ones on disk. */
26
+ async function sceneCardUrls(
27
+ shard: string,
28
+ ): Promise<Readonly<Record<string, string>>> {
29
+ const found = await Promise.all(
30
+ SCENE_SLOTS.map(
31
+ async (slot: string): Promise<readonly [string, string] | undefined> => {
32
+ const url = `${SCENE_CARD}/${slot}.jpg`
33
+ return (await present(path.join(shard, url))) ? [slot, url] : undefined
34
+ },
35
+ ),
36
+ )
37
+ return Object.fromEntries(
38
+ found.filter(
39
+ (
40
+ row: readonly [string, string] | undefined,
41
+ ): row is readonly [string, string] => row !== undefined,
42
+ ),
43
+ )
44
+ }
45
+
46
+ export { isSceneShard, sceneCardUrls }