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