@enslo/sd-metadata-lite 1.6.1 → 1.7.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.
package/dist/index.js CHANGED
@@ -1,79 +1,259 @@
1
+ // src/read.ts
2
+ const MAX_CABX = 8388608;
3
+ /**
4
+ * Extract text chunks from PNG data as keyword→text entries.
5
+ */
6
+ function readPng(data) {
7
+ const entries = {};
8
+ const dv = dataview(data);
9
+ let offset = 8;
10
+ while (offset + 8 <= data.length) {
11
+ const length = dv.getUint32(offset);
12
+ const type = str(data, offset + 4, 4);
13
+ offset += 8;
14
+ if (offset + length > data.length) break;
15
+ if (type === "caBX") entries.cabx = str(data, offset, Math.min(length, MAX_CABX));
16
+ if (type === "eXIf") Object.assign(entries, readExif(data.subarray(offset, offset + length)));
17
+ if (type === "tEXt" || type === "iTXt") {
18
+ const nullIdx = data.indexOf(0, offset);
19
+ if (nullIdx > offset && nullIdx < offset + length) {
20
+ const keyword = str(data, offset, nullIdx - offset);
21
+ if (type === "tEXt") entries[keyword] = tryUtf8(data.subarray(nullIdx + 1, offset + length)) ?? str(data, nullIdx + 1, offset + length - nullIdx - 1);
22
+ else {
23
+ const langEnd = data.indexOf(0, nullIdx + 3);
24
+ const transEnd = data.indexOf(0, langEnd + 1);
25
+ if (langEnd >= 0 && transEnd >= 0) entries[keyword] = tryUtf8(data.subarray(transEnd + 1, offset + length)) ?? "";
26
+ }
27
+ }
28
+ }
29
+ if (type === "IEND") break;
30
+ offset += length + 4;
31
+ }
32
+ return entries;
33
+ }
34
+ /**
35
+ * Extract metadata from JPEG: EXIF UserComment/ImageDescription/Make/Model,
36
+ * COM segment, and APP11 (C2PA) as `cabx`.
37
+ */
38
+ function readJpeg(data) {
39
+ const entries = {};
40
+ let offset = 2;
41
+ while (offset + 4 <= data.length) {
42
+ const marker = data[offset + 1];
43
+ if (data[offset] !== 255 || marker === 255) {
44
+ offset++;
45
+ continue;
46
+ }
47
+ if (marker > 216 && marker < 219) break;
48
+ const segLen = data[offset + 2] << 8 | data[offset + 3];
49
+ if (marker === 225 && str(data, offset + 4, 6) === "Exif\0\0") Object.assign(entries, readExif(data.subarray(offset + 10, offset + 2 + segLen)));
50
+ if (marker === 235) entries.cabx = (entries.cabx ?? "") + str(data, offset + 12, segLen - 10);
51
+ if (marker === 254) {
52
+ const text = tryUtf8(data.subarray(offset + 4, offset + 2 + segLen));
53
+ if (text) entries[COMMENT] = text;
54
+ }
55
+ offset += 2 + segLen;
56
+ }
57
+ return entries;
58
+ }
59
+ /**
60
+ * Extract metadata from WebP: EXIF chunk → same EXIF parsing as JPEG.
61
+ */
62
+ function readWebp(data) {
63
+ const dv = dataview(data);
64
+ let offset = 12;
65
+ while (offset + 8 <= data.length) {
66
+ const type = str(data, offset, 4);
67
+ const chunkSize = dv.getUint32(offset + 4, true);
68
+ offset += 8;
69
+ if (type === "EXIF" && offset + chunkSize <= data.length) return readExif(data.subarray(offset, offset + chunkSize));
70
+ offset += chunkSize + chunkSize % 2;
71
+ }
72
+ return {};
73
+ }
74
+ /**
75
+ * Parse EXIF/TIFF data and extract metadata entries.
76
+ */
77
+ function readExif(data) {
78
+ const entries = {};
79
+ const firstByte = data[0];
80
+ const le = firstByte === 73;
81
+ const dv = dataview(data);
82
+ const u16 = (o) => dv.getUint16(o, le);
83
+ const u32 = (o) => dv.getUint32(o, le);
84
+ if (data.length < 8 || !le && firstByte !== 77 || u16(2) !== 42) return entries;
85
+ const scanIfd = (ifdOffset, handler) => {
86
+ for (let pos = ifdOffset + 2, left = pos > data.length ? 0 : u16(ifdOffset); left-- && pos + 12 <= data.length; pos += 12) {
87
+ const typeSize = [
88
+ 0,
89
+ 1,
90
+ 1,
91
+ 2,
92
+ 4,
93
+ 8,
94
+ 0,
95
+ 1
96
+ ][u16(pos + 2)] ?? 1;
97
+ const size = u32(pos + 4) * typeSize;
98
+ const valOffset = size <= 4 ? pos + 8 : u32(pos + 8);
99
+ if (valOffset + size <= data.length) handler(u16(pos), data.subarray(valOffset, valOffset + size), valOffset);
100
+ }
101
+ };
102
+ let exifIfdOffset = 0;
103
+ const handleUserComment = (tagData) => {
104
+ const text = decodeUserComment(tagData);
105
+ if (text) entries[USER_COMMENT] = text;
106
+ };
107
+ scanIfd(u32(4), (tag, tagData, valOffset) => {
108
+ if (tag > 269 && tag < 273) {
109
+ const text = decodeAscii(tagData);
110
+ if (text) {
111
+ const prefixMatch = text.match(/^([A-Za-z]+):(?:\s|(?=\{))/);
112
+ if (prefixMatch) entries[prefixMatch[1]] = text.slice(prefixMatch[0].length);
113
+ else entries[[
114
+ IMAGE_DESCRIPTION,
115
+ "Make",
116
+ "Model"
117
+ ][tag - 270]] = text;
118
+ }
119
+ } else if (tag === 37510) handleUserComment(tagData);
120
+ else if (tag === 34665) exifIfdOffset = u32(valOffset);
121
+ });
122
+ if (exifIfdOffset && !entries["UserComment"]) scanIfd(exifIfdOffset, (tag, tagData) => {
123
+ if (tag === 37510) handleUserComment(tagData);
124
+ });
125
+ return entries;
126
+ }
127
+ function dataview(data) {
128
+ return new DataView(data.buffer, data.byteOffset, data.byteLength);
129
+ }
130
+ const utf8Dec = new TextDecoder("utf-8", { fatal: true });
131
+ const fromCharCode = String.fromCharCode;
132
+ const USER_COMMENT = "UserComment";
133
+ const COMMENT = "Comment";
134
+ const IMAGE_DESCRIPTION = "ImageDescription";
135
+ function str(data, offset, len) {
136
+ let s = "";
137
+ for (let i = 0; i < len; i++) s += fromCharCode(data[offset + i]);
138
+ return s;
139
+ }
140
+ function tryUtf8(data) {
141
+ try {
142
+ return utf8Dec.decode(data).replace(/\0$/, "");
143
+ } catch {
144
+ return null;
145
+ }
146
+ }
147
+ function decodeAscii(data) {
148
+ const nullIdx = data.indexOf(0);
149
+ return str(data, 0, nullIdx < 0 ? data.length : nullIdx).trim() || null;
150
+ }
151
+ /**
152
+ * Decode UserComment with encoding prefix detection.
153
+ */
154
+ function decodeUserComment(data) {
155
+ if (data.length < 8) return null;
156
+ const prefix = str(data, 0, 8);
157
+ const payload = data.subarray(8);
158
+ if (prefix === "UNICODE\0") return decodeUtf16(payload, payload[1] === 0);
159
+ if (prefix === "ASCII\0\0\0") return decodeAscii(payload);
160
+ return tryUtf8(data);
161
+ }
162
+ function decodeUtf16(data, le) {
163
+ let s = "";
164
+ for (let i = 0; i + 1 < data.length; i += 2) {
165
+ const code = le ? data[i] | data[i + 1] << 8 : data[i] << 8 | data[i + 1];
166
+ if (!code) break;
167
+ s += fromCharCode(code);
168
+ }
169
+ return s;
170
+ }
1
171
  // src/extract.ts
172
+ /**
173
+ * Unified detection, parsing, and A1111 text building engine.
174
+ *
175
+ * Architecture (two-stage pipeline):
176
+ *
177
+ * normalize(entries) — Pure channeling function. Identifies WHERE the
178
+ * generation data lives and routes it into a uniform
179
+ * `entries.parameters` field. Never parses content.
180
+ *
181
+ * extract(entries) — Reads `entries.parameters` (and other fields),
182
+ * detects the originating tool, extracts metadata,
183
+ * and builds A1111-format output text.
184
+ *
185
+ * Supported tools:
186
+ * A1111 / Forge / reForge, NovelAI, ComfyUI, SwarmUI, InvokeAI,
187
+ * Civitai, TensorArt, Fooocus, RuinedFooocus, EasyDiffusion, HF Space
188
+ */
2
189
  const CT = "class_type";
3
190
  const PARAMS = "parameters";
4
191
  const EASY_DIFF_KEY = "use_stable_diffusion_model";
192
+ const PROMPT = "prompt";
193
+ const SOURCE = "Source";
194
+ const SUI_PARAMS = "sui_image_params";
195
+ const NOISE_SCHEDULE = "noise_schedule";
196
+ const SAMPLER_NAME = "sampler_name";
197
+ const BASE_CAPTION = "base_caption";
5
198
  /**
6
- * Channel tool-specific entry keys into `entries.parameters`.
199
+ * Channel tool-specific keys of `src` into `entries.parameters`.
7
200
  *
8
- * Each key string appears exactly once in this loop to minimize IIFE size
9
- * (esbuild cannot mangle object property names).
201
+ * Each key string appears exactly once to minimize IIFE size (esbuild cannot
202
+ * mangle object property names).
10
203
  *
11
204
  * Matched keys and their tools:
12
205
  * - "extraMetadata" → Civitai (JPEG UserComment JSON)
13
206
  * - "invokeai_metadata" → InvokeAI (PNG tEXt / JPEG UserComment JSON)
14
207
  * - "generation_data" → TensorArt (JPEG UserComment JSON)
15
208
  *
16
- * Returns a NEW Entries with the matched value routed to `parameters`.
17
- * If no key matches, returns the original `entries` reference unchanged
18
- * (enables identity check with `!==`).
209
+ * Writes into `entries`, which is the copy normalize() works on, and tells
210
+ * whether a key matched. A value that is already there is kept.
19
211
  */
20
212
  function channelKnownKeys(src, entries) {
21
- for (const key of [
213
+ const key = [
22
214
  "extraMetadata",
23
215
  "invokeai_metadata",
24
216
  "generation_data"
25
- ]) if (src[key]) {
26
- const result = {
27
- ...entries,
28
- [PARAMS]: entries[PARAMS] ?? stringifyValue(src[key]).replace(/(?<!\0)\0+$/, "")
29
- };
30
- if (src.prompt) result.prompt ??= stringifyValue(src.prompt);
31
- return result;
217
+ ].find((k) => src[k]);
218
+ if (key) {
219
+ entries[PARAMS] ??= stringifyValue(src[key]).replace(/(?<!\0)\0+$/, "");
220
+ if (src[PROMPT]) entries[PROMPT] ??= stringifyValue(src[PROMPT]);
32
221
  }
33
- return entries;
222
+ return !!key;
34
223
  }
35
224
  /**
36
225
  * Normalize heterogeneous entry formats into a uniform shape.
37
226
  *
38
- * Pure function — returns a new Entries without mutating the input.
39
- * Only identifies WHERE data lives and channels it to `entries.parameters`.
40
- * All actual parsing/extraction is deferred to extract().
227
+ * Returns a copy of the entries with the generation data channeled to
228
+ * `parameters` (and a ComfyUI graph to `prompt`); the input is not modified.
229
+ * The copy is made once and filled with `??=`, which costs fewer bytes than
230
+ * spreading a new object in every branch. Only identifies WHERE data lives:
231
+ * all actual parsing/extraction is deferred to extract().
41
232
  *
42
233
  * Entry points by image format:
43
234
  * PNG → entries already has named keys (parameters, prompt, Comment, etc.)
44
235
  * JPEG → metadata is in EXIF UserComment (plain text or JSON blob)
45
236
  * WebP → same as JPEG (EXIF-based)
46
237
  */
47
- function normalize(entries) {
48
- if (entries.Software?.startsWith("NovelAI")) return {
49
- ...entries,
50
- [PARAMS]: entries[PARAMS] ?? entries.Comment
51
- };
52
- const uc = entries.UserComment;
53
- if (!uc) return channelKnownKeys(entries, entries);
54
- if (!uc.startsWith("{")) {
55
- if (uc.includes("Steps:")) return {
56
- ...entries,
57
- [PARAMS]: entries[PARAMS] ?? uc
58
- };
59
- return entries;
238
+ function normalize(rawEntries) {
239
+ const entries = { ...rawEntries };
240
+ const uc = entries[USER_COMMENT];
241
+ if (entries.Software?.startsWith("NovelAI")) entries[PARAMS] ??= entries[COMMENT];
242
+ else if (!uc) channelKnownKeys(entries, entries);
243
+ else if (!uc.startsWith("{")) {
244
+ if (uc.includes("Steps:")) entries[PARAMS] ??= uc;
245
+ } else {
246
+ const obj = parseJson(uc);
247
+ const comment = obj?.[COMMENT];
248
+ if (asText(obj?.Software).startsWith("NovelAI") && typeof comment === "string") {
249
+ entries[PARAMS] ??= comment;
250
+ entries[SOURCE] = obj[SOURCE];
251
+ } else if (obj && !channelKnownKeys(obj, entries)) {
252
+ if (PROMPT in obj && "workflow" in obj) entries[PROMPT] ??= stringifyValue(obj[PROMPT]);
253
+ else entries[PARAMS] ??= PARAMS in obj ? stringifyValue(obj[PARAMS]) : uc;
254
+ }
60
255
  }
61
- const obj = parseJson(uc);
62
- if (!obj) return entries;
63
- const channeled = channelKnownKeys(obj, entries);
64
- if (channeled !== entries) return channeled;
65
- if ("prompt" in obj && "workflow" in obj) return {
66
- ...entries,
67
- prompt: entries.prompt ?? stringifyValue(obj.prompt)
68
- };
69
- if (PARAMS in obj) return {
70
- ...entries,
71
- [PARAMS]: entries[PARAMS] ?? stringifyValue(obj[PARAMS])
72
- };
73
- return {
74
- ...entries,
75
- [PARAMS]: entries[PARAMS] ?? uc
76
- };
256
+ return entries;
77
257
  }
78
258
  /**
79
259
  * Main entry point: detect the originating tool, extract metadata from
@@ -82,55 +262,58 @@ function normalize(entries) {
82
262
  function extract(rawEntries) {
83
263
  const entries = normalize(rawEntries);
84
264
  const params = entries[PARAMS];
85
- const prompt = entries.prompt ?? entries.Prompt;
86
- if (params?.includes("sui_image_params")) {
87
- const obj = parseJson(params);
88
- if (obj) return buildA1111(extractCommon(obj.sui_image_params ?? obj));
89
- }
265
+ const prompt = entries[PROMPT] ?? entries.Prompt;
266
+ const obj = parseJson(params);
267
+ if (obj && params.includes(SUI_PARAMS)) return buildA1111(extractCommon(obj[SUI_PARAMS] ?? obj));
90
268
  if (params && !params.startsWith("{")) return params;
91
- if (params) {
92
- const obj = parseJson(params);
93
- if (obj) {
94
- if (entries.Source) obj.Source = entries.Source;
95
- const result = tryJsonTool(obj, params);
96
- if (result) return result;
97
- if (params.includes(CT)) return buildA1111(flatScan(params));
98
- const base = extractCommon(obj);
99
- if (prompt?.includes(CT)) return buildA1111({
100
- ...flatScan(prompt),
101
- p: base.p,
102
- n: base.n,
103
- md: base.md,
104
- mh: base.mh
105
- });
106
- return buildA1111(base);
107
- }
269
+ if (obj) {
270
+ if (entries[SOURCE]) obj[SOURCE] = entries[SOURCE];
271
+ if (NOISE_SCHEDULE in obj) return buildNovelAI(obj);
272
+ if (params.includes(CT)) return buildA1111(flatScan(params));
273
+ const base = extractCommon(obj);
274
+ if (prompt?.includes(CT)) return buildA1111({
275
+ ...flatScan(prompt),
276
+ p: base.p,
277
+ n: base.n,
278
+ md: base.md,
279
+ mh: base.mh
280
+ });
281
+ return buildA1111(base);
108
282
  }
109
283
  if (entries[EASY_DIFF_KEY]) return buildA1111({
110
284
  ...extractCommon(entries),
111
285
  cs: ""
112
286
  });
113
287
  if (prompt?.includes(CT)) return buildA1111(flatScan(prompt));
114
- return params ?? (readC2paName(entries.cabx) || (entries.UserComment ?? entries.Comment ?? entries.ImageDescription ?? ""));
288
+ return params ?? (readC2paName(entries.cabx) || (entries["UserComment"] ?? entries["Comment"] ?? entries["ImageDescription"] ?? ""));
115
289
  }
116
290
  /**
117
- * Recover `claim_generator_info.name` from a caBX manifest captured as a Latin-1
118
- * string (1:1 byte view, see readPng). Detection only — no JUMBF/CBOR decoder
119
- * and no signature verification.
291
+ * Recover the name of the tool that made the image from a caBX manifest
292
+ * captured as a Latin-1 string (1:1 byte view, see readPng): the
293
+ * `softwareAgent` of an action, which names the product (`Kling AI`,
294
+ * `Dreamina/7.5.0`), else `claim_generator_info.name`, the signing program.
295
+ * Detection only — no JUMBF/CBOR decoder and no signature verification.
120
296
  *
121
- * The `name` key is encoded as 0x64 ('d') + "name", i.e. the run "dname", so the
122
- * value's CBOR text-string header sits 5 bytes later. Generator names are short
123
- * ASCII, so only inline (0x60-0x77) and 1-byte (0x78) length headers are read.
124
- * charCodeAt yields NaN past the string end, which fails every comparison below,
125
- * so out-of-range offsets fall through to "".
297
+ * A `softwareAgent` is a text, or a map that starts with a `name`. The `name`
298
+ * key is encoded as 0x64 ('d') + "name", i.e. the run "dname", so its value
299
+ * sits 5 bytes later.
126
300
  */
127
301
  function readC2paName(manifest) {
128
302
  if (!manifest) return "";
129
- const cgi = manifest.indexOf("claim_generator_info");
130
- if (cgi < 0) return "";
131
- const p = manifest.indexOf("dname", cgi);
132
- if (p < 0 || p > cgi + 256) return "";
133
- const pos = p + 5;
303
+ const nameAfter = (at, max) => {
304
+ const p = manifest.indexOf("dname", at);
305
+ return at < 0 || p < 0 || p > at + max ? "" : readCborText(manifest, p + 5);
306
+ };
307
+ const agent = manifest.indexOf("softwareAgent");
308
+ return (agent < 0 ? "" : readCborText(manifest, agent + 13)) || nameAfter(agent, 14) || nameAfter(manifest.indexOf("claim_generator_info"), 256);
309
+ }
310
+ /**
311
+ * Read a CBOR text string at a position of the Latin-1 view. Names are short
312
+ * ASCII, so only inline (0x60-0x77) and 1-byte (0x78) length headers are
313
+ * read. charCodeAt yields NaN past the string end, which fails every
314
+ * comparison below, so out-of-range offsets fall through to "".
315
+ */
316
+ function readCborText(manifest, pos) {
134
317
  const head = manifest.charCodeAt(pos);
135
318
  if (!(head >= 96 && head <= 120)) return "";
136
319
  const oneByte = head === 120;
@@ -140,64 +323,39 @@ function readC2paName(manifest) {
140
323
  return manifest.slice(dataPos, dataPos + length);
141
324
  }
142
325
  /**
143
- * Attempt to identify specific tools from a parsed JSON object.
144
- * Returns A1111-format text if a tool is recognized, null otherwise.
145
- *
146
- * Detection is ordered from most specific to least specific signatures.
147
- */
148
- function tryJsonTool(obj, text) {
149
- if (asText(obj.software).includes("RuinedFooocus")) return buildA1111(extractCommon(obj));
150
- if (EASY_DIFF_KEY in obj) return buildA1111(extractCommon(obj));
151
- if (text.includes("\"Model\"") && text.includes("\"resolution\"")) {
152
- const [w, h] = parseDimensions(asText(obj.resolution), /(?<!\d)(\d+)\s*x\s*(\d+)/);
153
- return buildA1111({
154
- ...extractCommon(obj),
155
- w,
156
- h
157
- });
158
- }
159
- if ("base_model" in obj) {
160
- const [w, h] = parseDimensions(asText(obj.resolution), /\(\s*(\d+)\s*,\s*(\d+)\s*\)/);
161
- return buildA1111({
162
- ...extractCommon(obj),
163
- w,
164
- h
165
- });
166
- }
167
- if ("noise_schedule" in obj) return buildNovelAI(obj);
168
- return null;
169
- }
170
- /**
171
326
  * Extract GenerationParams from a JSON object using field name fallback chains.
172
327
  *
173
328
  * Each field tries multiple property names to cover all known JSON-based tools.
174
329
  * The fallback order generally goes: most common name → tool-specific aliases.
330
+ * No tool is detected first: a key one tool uses is simply absent from the
331
+ * others.
175
332
  *
176
333
  * Covered tools: A1111, NovelAI, SwarmUI, InvokeAI, Civitai, TensorArt,
177
334
  * Fooocus, RuinedFooocus, EasyDiffusion, HF Space.
178
335
  */
179
336
  function extractCommon(obj) {
180
- const sa = asText(obj.sampler ?? obj.sampler_name);
181
- const sc = asText(obj.scheduler ?? obj.noise_schedule);
337
+ const sa = asText(obj.sampler ?? obj[SAMPLER_NAME]);
338
+ const sc = asText(obj.scheduler ?? obj[NOISE_SCHEDULE]);
182
339
  const mod = obj.model;
183
340
  const base = obj.baseModel;
184
341
  const up = obj.use_upscaler;
342
+ const size = asText(obj.resolution).match(/(?<!\d)(\d+)\s*[x,]\s*(\d+)/);
185
343
  return {
186
- p: obj.full_prompt?.join?.(", ") || asText(obj.prompt ?? obj.Prompt ?? obj.positive_prompt),
344
+ p: obj.full_prompt?.join?.(", ") || asText(obj[PROMPT] ?? obj.Prompt ?? obj.positive_prompt),
187
345
  n: obj.full_negative_prompt?.join?.(", ") || asText(obj.negative_prompt ?? obj.Negative ?? obj.negativeprompt ?? obj.negativePrompt ?? obj.uc),
188
346
  se: asText(obj.seed),
189
347
  st: asText(obj.steps ?? obj.num_inference_steps),
190
348
  cf: asText(obj.cfg ?? obj.cfg_scale ?? obj.cfgScale ?? obj.cfgscale ?? obj.guidance_scale ?? obj.scale),
191
349
  sa: sa || sc,
192
- sc: sa ? sc : void 0,
193
- w: asText(obj.width),
194
- h: asText(obj.height),
195
- md: asText(mod) || asText(obj.Model) || asText(obj.base_model) || asText(obj.base_model_name) || asText(base) || asText(mod?.name) || asText(base?.modelFileName) || asText(obj[EASY_DIFF_KEY]).split(/[\\/]/).pop(),
196
- mh: asText(obj.base_model_hash) || asText(obj["Model hash"]) || asText(mod?.hash) || asText(base?.hash),
350
+ sc: sa && sc,
351
+ w: size?.[1] ?? asText(obj.width),
352
+ h: size?.[2] ?? asText(obj.height),
353
+ md: asText(mod, obj.Model, obj.base_model, obj.base_model_name, base, mod?.name, base?.modelFileName) || asText(obj[EASY_DIFF_KEY]).split(/[\\/]/).pop(),
354
+ mh: asText(obj.base_model_hash, obj["Model hash"], mod?.hash, base?.hash),
197
355
  cs: asText(obj.clip_skip ?? obj.clipSkip),
198
- hs: asText(up?.upscale_by) || asText(obj.refinerupscale),
199
- hu: asText(up?.upscale_method) || asText(obj.refinerupscalemethod),
200
- hd: asText(up?.upscaler_strength) || asText(obj.refinercontrolpercentage),
356
+ hs: asText(up?.upscale_by, obj.refinerupscale),
357
+ hu: asText(up?.upscale_method, obj.refinerupscalemethod),
358
+ hd: asText(up?.upscaler_strength, obj.refinercontrolpercentage),
201
359
  ht: asText(up?.upscale_steps)
202
360
  };
203
361
  }
@@ -211,13 +369,13 @@ function extractCommon(obj) {
211
369
  function buildNovelAI(obj) {
212
370
  const v4Caption = obj.v4_prompt?.caption;
213
371
  const v4NegCaption = obj.v4_negative_prompt?.caption;
214
- const src = /^(.+) ([0-9A-F]{8})$/.exec(asText(obj.Source));
372
+ const src = /^(.+) ([0-9A-F]{8})$/.exec(asText(obj[SOURCE]));
215
373
  return buildA1111({
216
374
  ...extractCommon(obj),
217
- p: (asText(v4Caption?.base_caption) || asText(obj.prompt)).replace(/(^|, )teXt:(?!:).*/s, ""),
218
- n: asText(v4NegCaption?.base_caption) || asText(obj.uc),
375
+ p: asText(v4Caption?.[BASE_CAPTION], obj[PROMPT]).replace(/(^|, )teXt:(?!:).*/s, ""),
376
+ n: asText(v4NegCaption?.[BASE_CAPTION], obj.uc),
219
377
  dn: asText(obj.strength),
220
- md: src?.[1] ?? asText(obj.Source),
378
+ md: src?.[1] ?? asText(obj[SOURCE]),
221
379
  mh: src?.[2]
222
380
  });
223
381
  }
@@ -238,13 +396,12 @@ function flatScan(json) {
238
396
  if (!nodes) return result;
239
397
  for (const key in nodes) {
240
398
  const node = nodes[key];
241
- if (!node || typeof node !== "object") continue;
242
- const classType = asText(node[CT]);
243
- const inputs = node.inputs;
399
+ const inputs = node?.inputs;
244
400
  if (!inputs) continue;
401
+ const classType = asText(node[CT]);
245
402
  if (/User Prompt/.test(asText(node._meta?.title))) up ||= asText(inputs.value);
246
403
  if (/Text(Encode|.?Box)|ShowText|PromptStash/.test(classType)) {
247
- const txt = asText(inputs.text) || asText(inputs.prompt) || asText(inputs.Text) || asText(inputs.prompt_text) || asText(inputs.text_0);
404
+ const txt = asText(inputs.text, inputs[PROMPT], inputs.Text, inputs.prompt_text, inputs.text_0);
248
405
  if (txt) {
249
406
  if (/neg/i.test(classType)) result.n ??= txt;
250
407
  else if (!result.p) result.p = txt;
@@ -252,13 +409,13 @@ function flatScan(json) {
252
409
  }
253
410
  }
254
411
  if (classType.includes("Sampler")) {
255
- result.se ||= asText(inputs.seed) || asText(inputs.noise_seed);
412
+ result.se ||= asText(inputs.seed, inputs.noise_seed);
256
413
  result.st ||= asText(inputs.steps);
257
414
  result.cf ||= asText(inputs.cfg);
258
- result.sa ||= asText(inputs.sampler_name);
415
+ result.sa ||= asText(inputs[SAMPLER_NAME]);
259
416
  result.sc ||= asText(inputs.scheduler);
260
417
  }
261
- result.md ||= asText(inputs.ckpt_name) || asText(inputs.unet_name);
418
+ result.md ||= asText(inputs.ckpt_name, inputs.unet_name);
262
419
  result.w ||= asText(inputs.width);
263
420
  result.h ||= asText(inputs.height);
264
421
  }
@@ -274,28 +431,26 @@ function flatScan(json) {
274
431
  * Line 3: comma-separated key-value pairs (Steps, Sampler, CFG, etc.)
275
432
  */
276
433
  function buildA1111(params) {
277
- const lines = [];
278
- if (params.p) lines.push(params.p);
279
- if (params.n) lines.push(`Negative prompt: ${params.n}`);
280
- const fields = [];
281
- const addField = (key, value) => {
282
- if (value) fields.push(`${key}: ${value}`);
283
- };
284
- addField("Steps", params.st);
285
- addField("Sampler", params.sa);
286
- addField("Schedule type", params.sc);
287
- addField("CFG scale", params.cf);
288
- addField("Seed", params.se);
289
- if (params.w && params.h) addField("Size", `${params.w}x${params.h}`);
290
- addField("Model hash", params.mh);
291
- addField("Model", params.md);
292
- addField("Clip skip", params.cs);
293
- addField("Denoising strength", params.dn ?? params.hd);
294
- addField("Hires upscale", params.hs);
295
- addField("Hires steps", params.ht);
296
- addField("Hires upscaler", params.hu);
297
- if (fields.length) lines.push(fields.join(", "));
298
- return lines.join("\n");
434
+ const field = (key, value) => value ? `${key}: ${value}` : "";
435
+ return [
436
+ params.p,
437
+ field("Negative prompt", params.n),
438
+ [
439
+ field("Steps", params.st),
440
+ field("Sampler", params.sa),
441
+ field("Schedule type", params.sc),
442
+ field("CFG scale", params.cf),
443
+ field("Seed", params.se),
444
+ field("Size", params.w && params.h && `${params.w}x${params.h}`),
445
+ field("Model hash", params.mh),
446
+ field("Model", params.md),
447
+ field("Clip skip", params.cs),
448
+ field("Denoising strength", params.dn ?? params.hd),
449
+ field("Hires upscale", params.hs),
450
+ field("Hires steps", params.ht),
451
+ field("Hires upscaler", params.hu)
452
+ ].filter(Boolean).join(", ")
453
+ ].filter(Boolean).join("\n");
299
454
  }
300
455
  /** Safely parse JSON, returning null on failure. */
301
456
  function parseJson(text) {
@@ -314,11 +469,15 @@ function parseJson(text) {
314
469
  * ["95", 0] — becomes "".
315
470
  *
316
471
  * Every value ends up interpolated into A1111 text, so there is no reason to
317
- * hold numbers as numbers. Returning "" (falsy) enables `||` fallback chains:
318
- * `asText(a) || asText(b)`.
472
+ * hold numbers as numbers.
473
+ *
474
+ * Given several candidates, returns the first one that yields text, so
475
+ * `asText(a, b)` reads like `asText(a) || asText(b)` at a fraction of the
476
+ * bytes. An empty string is skipped like a missing value; a number never is
477
+ * (0 gives "0").
319
478
  */
320
- function asText(v) {
321
- return typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
479
+ function asText(...values) {
480
+ return `${values.find((v) => typeof v === "string" && v || typeof v === "number") ?? ""}`;
322
481
  }
323
482
  /**
324
483
  * Convert a value to its string representation for channeling.
@@ -331,215 +490,6 @@ function stringifyValue(v) {
331
490
  if (v && typeof v === "object") return JSON.stringify(v);
332
491
  return "";
333
492
  }
334
- /**
335
- * Extract width/height from a dimension string using the given regex.
336
- * Different tools use different formats:
337
- * - Fooocus: "1024x1024" → /(\d+)\s*x\s*(\d+)/
338
- * - HF Space: "(1024, 1024)" → /\(\s*(\d+)\s*,\s*(\d+)\s*\)/
339
- */
340
- function parseDimensions(text, pattern) {
341
- if (!text) return [];
342
- const match = text.match(pattern);
343
- return match ? [match[1], match[2]] : [];
344
- }
345
- // src/read.ts
346
- const MAX_CABX = 8388608;
347
- /**
348
- * Extract text chunks from PNG data as keyword→text entries.
349
- */
350
- function readPng(data) {
351
- const entries = {};
352
- const dv = dataview(data);
353
- let offset = 8;
354
- while (offset + 8 <= data.length) {
355
- const length = dv.getUint32(offset);
356
- const type = str(data, offset + 4, 4);
357
- offset += 8;
358
- if (offset + length > data.length) break;
359
- if (type === "caBX") entries.cabx = str(data, offset, Math.min(length, MAX_CABX));
360
- if (type === "eXIf") Object.assign(entries, readExif(data.subarray(offset, offset + length)));
361
- if (type === "tEXt" || type === "iTXt") {
362
- const nullIdx = data.indexOf(0, offset);
363
- if (nullIdx > offset && nullIdx < offset + length) {
364
- const keyword = str(data, offset, nullIdx - offset);
365
- if (type === "tEXt") entries[keyword] = tryUtf8(data.subarray(nullIdx + 1, offset + length)) ?? str(data, nullIdx + 1, offset + length - nullIdx - 1);
366
- else {
367
- const pos = nullIdx + 3;
368
- const langEnd = data.indexOf(0, pos);
369
- const transEnd = langEnd < 0 ? -1 : data.indexOf(0, langEnd + 1);
370
- if (langEnd < 0 || transEnd < 0) {
371
- offset += length + 4;
372
- continue;
373
- }
374
- entries[keyword] = tryUtf8(data.subarray(transEnd + 1, offset + length)) ?? "";
375
- }
376
- }
377
- }
378
- if (type === "IEND") break;
379
- offset += length + 4;
380
- }
381
- return entries;
382
- }
383
- /**
384
- * Extract metadata from JPEG: EXIF UserComment/ImageDescription/Make/Model,
385
- * COM segment, and APP11 (C2PA) as `cabx`.
386
- */
387
- function readJpeg(data) {
388
- const entries = {};
389
- let offset = 2;
390
- while (offset + 4 <= data.length) {
391
- const marker = data[offset + 1];
392
- if (data[offset] !== 255 || marker === 255) {
393
- offset++;
394
- continue;
395
- }
396
- if (marker > 216 && marker < 219) break;
397
- const segLen = data[offset + 2] << 8 | data[offset + 3];
398
- if (marker === 225 && offset + 10 <= data.length && str(data, offset + 4, 6) === "Exif\0\0") Object.assign(entries, readExif(data.subarray(offset + 10, offset + 2 + segLen)));
399
- if (marker === 235) entries.cabx = (entries.cabx ?? "") + str(data, offset + 12, segLen - 10);
400
- if (marker === 254) {
401
- const text = tryUtf8(data.subarray(offset + 4, offset + 2 + segLen));
402
- if (text) entries.Comment = text;
403
- }
404
- offset += 2 + segLen;
405
- }
406
- return entries;
407
- }
408
- /**
409
- * Extract metadata from WebP: EXIF chunk → same EXIF parsing as JPEG.
410
- */
411
- function readWebp(data) {
412
- const dv = dataview(data);
413
- let offset = 12;
414
- while (offset + 8 <= data.length) {
415
- const type = str(data, offset, 4);
416
- const chunkSize = dv.getUint32(offset + 4, true);
417
- offset += 8;
418
- if (type === "EXIF" && offset + chunkSize <= data.length) return readExif(data.subarray(offset, offset + chunkSize));
419
- offset += chunkSize + chunkSize % 2;
420
- }
421
- return {};
422
- }
423
- /**
424
- * Parse EXIF/TIFF data and extract metadata entries.
425
- */
426
- function readExif(data) {
427
- if (data.length < 8) return {};
428
- const firstByte = data[0];
429
- const le = firstByte === 73;
430
- if (!le && firstByte !== 77) return {};
431
- const dv = dataview(data);
432
- if (dv.getUint16(2, le) !== 42) return {};
433
- const entries = {};
434
- const ifd0 = dv.getUint32(4, le);
435
- let exifIfdOffset = 0;
436
- const handleUserComment = (tagData) => {
437
- const text = decodeUserComment(tagData);
438
- if (text) {
439
- if (text.startsWith("{")) try {
440
- const obj = JSON.parse(text);
441
- const software = obj.Software;
442
- const comment = obj.Comment;
443
- if (typeof software === "string" && software.startsWith("NovelAI") && typeof comment === "string") {
444
- entries.Software = software;
445
- entries.Comment = comment;
446
- entries.Source = obj.Source;
447
- return;
448
- }
449
- } catch {}
450
- entries.UserComment = text;
451
- }
452
- };
453
- scanIfd(data, dv, ifd0, le, (tag, tagData) => {
454
- if (tag > 269 && tag < 273) {
455
- const text = decodeAscii(tagData);
456
- if (text) {
457
- const prefixMatch = text.match(/^([A-Za-z]+):(?:\s|(?=\{))/);
458
- if (prefixMatch) {
459
- const key = prefixMatch[1];
460
- if (key) entries[key] = text.slice(prefixMatch[0].length);
461
- } else entries[tag === 270 ? "ImageDescription" : tag === 271 ? "Make" : "Model"] = text;
462
- }
463
- } else if (tag === 37510) handleUserComment(tagData);
464
- else if (tag === 34665) exifIfdOffset = dv.getUint32(tagData.byteOffset - data.byteOffset, le);
465
- });
466
- if (exifIfdOffset && !entries.UserComment && !entries.Software) scanIfd(data, dv, exifIfdOffset, le, (tag, tagData) => {
467
- if (tag === 37510) handleUserComment(tagData);
468
- });
469
- return entries;
470
- }
471
- /**
472
- * Scan IFD entries and call handler for each tag.
473
- */
474
- function scanIfd(data, dv, ifdOffset, le, handler) {
475
- const u16 = (o) => dv.getUint16(o, le);
476
- const u32 = (o) => dv.getUint32(o, le);
477
- if (ifdOffset + 2 > data.length) return;
478
- const count = u16(ifdOffset);
479
- let pos = ifdOffset + 2;
480
- for (let i = 0; i < count; i++) {
481
- if (pos + 12 > data.length) return;
482
- const tag = u16(pos);
483
- const type = u16(pos + 2);
484
- const size = u32(pos + 4) * ([
485
- 0,
486
- 1,
487
- 1,
488
- 2,
489
- 4,
490
- 8,
491
- 0,
492
- 1
493
- ][type] ?? 1);
494
- const valOffset = size <= 4 ? pos + 8 : u32(pos + 8);
495
- if (valOffset + size <= data.length) handler(tag, data.subarray(valOffset, valOffset + size));
496
- pos += 12;
497
- }
498
- }
499
- function dataview(data) {
500
- return new DataView(data.buffer, data.byteOffset, data.byteLength);
501
- }
502
- const utf8Dec = new TextDecoder("utf-8", { fatal: true });
503
- const fromCharCode = String.fromCharCode;
504
- function str(data, offset, len) {
505
- let s = "";
506
- for (let i = 0; i < len; i++) s += fromCharCode(data[offset + i]);
507
- return s;
508
- }
509
- function tryUtf8(data) {
510
- try {
511
- return utf8Dec.decode(data).replace(/\0$/, "");
512
- } catch {
513
- return null;
514
- }
515
- }
516
- function decodeAscii(data) {
517
- const nullIdx = data.indexOf(0);
518
- return str(data, 0, nullIdx < 0 ? data.length : nullIdx).trim() || null;
519
- }
520
- /**
521
- * Decode UserComment with encoding prefix detection.
522
- */
523
- function decodeUserComment(data) {
524
- if (data.length < 8) return null;
525
- const prefix = str(data, 0, 8);
526
- const payload = data.subarray(8);
527
- if (prefix === "UNICODE\0") {
528
- if (payload.length < 2) return null;
529
- return decodeUtf16(payload, payload[0] !== 0 && payload[1] === 0);
530
- }
531
- if (prefix === "ASCII\0\0\0") return decodeAscii(payload);
532
- return tryUtf8(data);
533
- }
534
- function decodeUtf16(data, le) {
535
- let s = "";
536
- for (let i = 0; i + 1 < data.length; i += 2) {
537
- const code = le ? data[i] | data[i + 1] << 8 : data[i] << 8 | data[i + 1];
538
- if (!code) break;
539
- s += fromCharCode(code);
540
- }
541
- return s;
542
- }
543
493
  // src/index.ts
544
494
  /**
545
495
  * @enslo/sd-metadata-lite
@@ -551,19 +501,19 @@ function decodeUtf16(data, le) {
551
501
  * Parse AI-generated image metadata and return A1111-format text.
552
502
  *
553
503
  * Supports PNG, JPEG, and WebP formats across 18+ generation tools. For PNG
554
- * images with no generation parameters, falls back to C2PA Content Credentials
555
- * and returns the generator name (e.g. ChatGPT / Gemini exports).
504
+ * and JPEG images with no generation parameters, falls back to C2PA Content
505
+ * Credentials and returns the name of the tool that made the image
506
+ * (`ChatGPT`, `Kling AI`, `Grok Imagine`), or of the program that signed it
507
+ * when the manifest names no tool (Gemini exports).
556
508
  * Returns empty string if no metadata is found.
557
509
  *
558
510
  * @param input - Image file data
559
- * @returns A1111-format metadata text, the C2PA generator name, or empty string
511
+ * @returns A1111-format metadata text, a C2PA tool name, or empty string
560
512
  */
561
513
  function parse(input) {
562
514
  const data = input instanceof ArrayBuffer ? new Uint8Array(input) : input;
563
- if (data[0] === 137 && data[1] === 80) return extract(readPng(data));
564
- if (data[0] === 255 && data[1] === 216) return extract(readJpeg(data));
565
- if (data[0] === 82 && data[1] === 73) return extract(readWebp(data));
566
- return "";
515
+ const magic = data[0] << 8 | data[1];
516
+ return extract(magic === 35152 ? readPng(data) : magic === 65496 ? readJpeg(data) : magic === 21065 ? readWebp(data) : {});
567
517
  }
568
518
  export { parse };
569
519