@enslo/sd-metadata-lite 1.6.0 → 1.6.1
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/CHANGELOG.md +20 -0
- package/README.ja.md +3 -3
- package/README.md +3 -3
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.js +13 -15
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,26 @@ All notable changes to `@enslo/sd-metadata-lite` will be documented in this file
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
7
7
|
|
|
8
|
+
## [1.6.1] - 2026-11-09
|
|
9
|
+
|
|
10
|
+
Steady on Unexpected Text
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **No throw or stall on odd text** (#326): non-JSON `parameters`, long NUL
|
|
15
|
+
runs and unusual Fooocus size strings are handled.
|
|
16
|
+
- **Seed note** (#337): 1.6.0 overstated it. String seeds keep every digit;
|
|
17
|
+
JSON-number seeds are rounded past 2^53 by `JSON.parse`. No behaviour change.
|
|
18
|
+
|
|
19
|
+
### Demo Site
|
|
20
|
+
|
|
21
|
+
- Security headers (#331); read errors shown (#336).
|
|
22
|
+
|
|
23
|
+
### Maintenance
|
|
24
|
+
|
|
25
|
+
- IIFE bundle size: 7,259 → 7,257 bytes (#326)
|
|
26
|
+
- Update development dependencies (#320)
|
|
27
|
+
|
|
8
28
|
## [1.6.0] - 2026-11-04
|
|
9
29
|
|
|
10
30
|
### Added
|
package/README.ja.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
AI生成画像のメタデータを読み取る軽量パーサーです。
|
|
11
11
|
バンドルサイズが重要なブックマークレットやユーザースクリプト向けに設計されています。
|
|
12
12
|
|
|
13
|
-
- **超軽量**: **7,
|
|
13
|
+
- **超軽量**: **7,257 bytes** のminified IIFEビルド
|
|
14
14
|
- **読み取り専用**: メタデータを抽出し、A1111形式のテキストで返却
|
|
15
15
|
- **ゼロ依存**: Node.jsとブラウザの両方で動作
|
|
16
16
|
- **18以上のツール対応**: 主要なAI画像生成ツールをサポート
|
|
@@ -66,7 +66,7 @@ if (text) {
|
|
|
66
66
|
// ==UserScript==
|
|
67
67
|
// @name My Script
|
|
68
68
|
// @namespace https://example.com
|
|
69
|
-
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.
|
|
69
|
+
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.1/dist/index.global.js
|
|
70
70
|
// ==/UserScript==
|
|
71
71
|
|
|
72
72
|
const response = await fetch(imageUrl);
|
|
@@ -85,7 +85,7 @@ if (text) {
|
|
|
85
85
|
|
|
86
86
|
多くのサイトではCSPにより外部スクリプトの読み込みがブロックされます。代わりに、IIFEバンドルをインラインで貼り付けてください:
|
|
87
87
|
|
|
88
|
-
1. `dist/index.global.js` の内容をコピー(または[npm](https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.
|
|
88
|
+
1. `dist/index.global.js` の内容をコピー(または[npm](https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.1/dist/index.global.js)からダウンロード)
|
|
89
89
|
2. コードをインラインでブックマークレットに組み込みます:
|
|
90
90
|
|
|
91
91
|
```javascript
|
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
A lightweight, read-only metadata parser for AI-generated images.
|
|
11
11
|
Designed for bookmarklets and userscripts where bundle size matters.
|
|
12
12
|
|
|
13
|
-
- **Tiny**: **7,
|
|
13
|
+
- **Tiny**: **7,257 bytes** minified IIFE build
|
|
14
14
|
- **Read-only**: Extracts metadata and returns A1111-format text
|
|
15
15
|
- **Zero dependencies**: Works in Node.js and browsers
|
|
16
16
|
- **18+ tools**: Supports all major AI image generation tools
|
|
@@ -66,7 +66,7 @@ Load the IIFE build via `@require`:
|
|
|
66
66
|
// ==UserScript==
|
|
67
67
|
// @name My Script
|
|
68
68
|
// @namespace https://example.com
|
|
69
|
-
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.
|
|
69
|
+
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.1/dist/index.global.js
|
|
70
70
|
// ==/UserScript==
|
|
71
71
|
|
|
72
72
|
const response = await fetch(imageUrl);
|
|
@@ -85,7 +85,7 @@ if (text) {
|
|
|
85
85
|
|
|
86
86
|
Most sites block external script loading via CSP. Instead, paste the IIFE bundle inline:
|
|
87
87
|
|
|
88
|
-
1. Copy the contents of `dist/index.global.js` (or download from [npm](https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.
|
|
88
|
+
1. Copy the contents of `dist/index.global.js` (or download from [npm](https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.1/dist/index.global.js))
|
|
89
89
|
2. Build your bookmarklet with the code inlined:
|
|
90
90
|
|
|
91
91
|
```javascript
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/index.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* @enslo/sd-metadata-lite
|
|
4
3
|
*
|
|
@@ -17,5 +16,4 @@
|
|
|
17
16
|
* @returns A1111-format metadata text, the C2PA generator name, or empty string
|
|
18
17
|
*/
|
|
19
18
|
export declare function parse(input: Uint8Array | ArrayBuffer): string;
|
|
20
|
-
//#endregion
|
|
21
19
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;wBAqBgB,MAAM,OAAO,aAAa"}
|
package/dist/index.global.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var sdml=(()=>{var e="class_type",t="parameters",r="use_stable_diffusion_model";function n(e,r){for(let n of["extraMetadata","invokeai_metadata","generation_data"])if(e[n]){let i={...r,[t]:r[t]??f(e[n]).replace(
|
|
1
|
+
var sdml=(()=>{var e="class_type",t="parameters",r="use_stable_diffusion_model";function n(e,r){for(let n of["extraMetadata","invokeai_metadata","generation_data"])if(e[n]){let i={...r,[t]:r[t]??f(e[n]).replace(/(?<!\0)\0+$/,"")};return e.prompt&&(i.prompt??=f(e.prompt)),i}return r}function i(i){let p=function(e){if(e.Software?.startsWith("NovelAI"))return{...e,[t]:e[t]??e.Comment};let r=e.UserComment;if(!r)return n(e,e);if(!r.startsWith("{"))return r.includes("Steps:")?{...e,[t]:e[t]??r}:e;let i=o(r);if(!i)return e;let l=n(i,e);return l!==e?l:"prompt"in i&&"workflow"in i?{...e,prompt:e.prompt??f(i.prompt)}:t in i?{...e,[t]:e[t]??f(i[t])}:{...e,[t]:e[t]??r}}(i),m=p[t],h=p.prompt??p.Prompt;if(m?.includes("sui_image_params")){let e=o(m);if(e)return u(l(e.sui_image_params??e))}if(m&&!m.startsWith("{"))return m;if(m){let t=o(m);if(t){p.Source&&(t.Source=p.Source);let n=function(e,t){if(a(e.software).includes("RuinedFooocus")||r in e)return u(l(e));if(t.includes('"Model"')&&t.includes('"resolution"')){let[t,r]=c(a(e.resolution),/(?<!\d)(\d+)\s*x\s*(\d+)/);return u({...l(e),w:t,h:r})}if("base_model"in e){let[t,r]=c(a(e.resolution),/\(\s*(\d+)\s*,\s*(\d+)\s*\)/);return u({...l(e),w:t,h:r})}return"noise_schedule"in e?function(e){let t=e.v4_prompt?.caption,r=e.v4_negative_prompt?.caption,n=/^(.+) ([0-9A-F]{8})$/.exec(a(e.Source));return u({...l(e),p:(a(t?.base_caption)||a(e.prompt)).replace(/(^|, )teXt:(?!:).*/s,""),n:a(r?.base_caption)||a(e.uc),dn:a(e.strength),md:n?.[1]??a(e.Source),mh:n?.[2]})}(e):null}(t,m);if(n)return n;if(m.includes(e))return u(s(m));let i=l(t);return h?.includes(e)?u({...s(h),p:i.p,n:i.n,md:i.md,mh:i.mh}):u(i)}}return p[r]?u({...l(p),cs:""}):h?.includes(e)?u(s(h)):m??(function(e){if(!e)return"";let t=e.indexOf("claim_generator_info");if(t<0)return"";let r=e.indexOf("dname",t);if(r<0||r>t+256)return"";let n=r+5,i=e.charCodeAt(n);if(!(i>=96&&i<=120))return"";let l=120===i,s=l?e.charCodeAt(n+1)||0:i-96,u=n+(l?2:1);return u+s>e.length?"":e.slice(u,u+s)}(p.cabx)||(p.UserComment??p.Comment??p.ImageDescription??""))}function l(e){let t=a(e.sampler??e.sampler_name),n=a(e.scheduler??e.noise_schedule),i=e.model,l=e.baseModel,s=e.use_upscaler;return{p:e.full_prompt?.join?.(", ")||a(e.prompt??e.Prompt??e.positive_prompt),n:e.full_negative_prompt?.join?.(", ")||a(e.negative_prompt??e.Negative??e.negativeprompt??e.negativePrompt??e.uc),se:a(e.seed),st:a(e.steps??e.num_inference_steps),cf:a(e.cfg??e.cfg_scale??e.cfgScale??e.cfgscale??e.guidance_scale??e.scale),sa:t||n,sc:t?n:void 0,w:a(e.width),h:a(e.height),md:a(i)||a(e.Model)||a(e.base_model)||a(e.base_model_name)||a(l)||a(i?.name)||a(l?.modelFileName)||a(e[r]).split(/[\\/]/).pop(),mh:a(e.base_model_hash)||a(e["Model hash"])||a(i?.hash)||a(l?.hash),cs:a(e.clip_skip??e.clipSkip),hs:a(s?.upscale_by)||a(e.refinerupscale),hu:a(s?.upscale_method)||a(e.refinerupscalemethod),hd:a(s?.upscaler_strength)||a(e.refinercontrolpercentage),ht:a(s?.upscale_steps)}}function s(t){let r={},n="",i=o(t.replace(/(?<!\0)\0+$/,"").replace(/\bNaN\b/g,"null"));if(!i)return r;for(let t in i){let l=i[t];if(!l||"object"!=typeof l)continue;let s=a(l[e]),u=l.inputs;if(u){if(/User Prompt/.test(a(l._meta?.title))&&(n||=a(u.value)),/Text(Encode|.?Box)|ShowText|PromptStash/.test(s)){let e=a(u.text)||a(u.prompt)||a(u.Text)||a(u.prompt_text)||a(u.text_0);e&&(/neg/i.test(s)?r.n??=e:r.p?r.n||(r.n=e):r.p=e)}s.includes("Sampler")&&(r.se||=a(u.seed)||a(u.noise_seed),r.st||=a(u.steps),r.cf||=a(u.cfg),r.sa||=a(u.sampler_name),r.sc||=a(u.scheduler)),r.md||=a(u.ckpt_name)||a(u.unet_name),r.w||=a(u.width),r.h||=a(u.height)}}return r.p||=n,r}function u(e){let t=[];e.p&&t.push(e.p),e.n&&t.push("Negative prompt: "+e.n);let r=[],n=(e,t)=>{t&&r.push(`${e}: ${t}`)};return n("Steps",e.st),n("Sampler",e.sa),n("Schedule type",e.sc),n("CFG scale",e.cf),n("Seed",e.se),e.w&&e.h&&n("Size",`${e.w}x${e.h}`),n("Model hash",e.mh),n("Model",e.md),n("Clip skip",e.cs),n("Denoising strength",e.dn??e.hd),n("Hires upscale",e.hs),n("Hires steps",e.ht),n("Hires upscaler",e.hu),r.length&&t.push(r.join(", ")),t.join("\n")}function o(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function a(e){return"string"==typeof e?e:"number"==typeof e?e+"":""}function f(e){return"string"==typeof e?e:e&&"object"==typeof e?JSON.stringify(e):""}function c(e,t){if(!e)return[];let r=e.match(t);return r?[r[1],r[2]]:[]}function p(e){if(e.length<8)return{};let t=e[0],r=73===t;if(!r&&77!==t)return{};let n=h(e);if(42!==n.getUint16(2,r))return{};let i={},l=n.getUint32(4,r),s=0,u=e=>{let t=function(e){if(e.length<8)return null;let t=_(e,0,8),r=e.subarray(8);return"UNICODE\0"===t?r.length<2?null:function(e,t){let r="";for(let n=0;n+1<e.length;n+=2){let i=t?e[n]|e[n+1]<<8:e[n]<<8|e[n+1];if(!i)break;r+=g(i)}return r}(r,0!==r[0]&&0===r[1]):"ASCII\0\0\0"===t?y(r):b(e)}(e);if(t){if(t.startsWith("{"))try{let e=JSON.parse(t),r=e.Software,n=e.Comment;if("string"==typeof r&&r.startsWith("NovelAI")&&"string"==typeof n)return i.Software=r,i.Comment=n,void(i.Source=e.Source)}catch{}i.UserComment=t}};return m(e,n,l,r,(t,l)=>{if(t>269&&t<273){let e=y(l);if(e){let r=e.match(/^([A-Za-z]+):(?:\s|(?=\{))/);if(r){let t=r[1];t&&(i[t]=e.slice(r[0].length))}else i[270===t?"ImageDescription":271===t?"Make":"Model"]=e}}else 37510===t?u(l):34665===t&&(s=n.getUint32(l.byteOffset-e.byteOffset,r))}),s&&!i.UserComment&&!i.Software&&m(e,n,s,r,(e,t)=>{37510===e&&u(t)}),i}function m(e,t,r,n,i){let l=e=>t.getUint16(e,n),s=e=>t.getUint32(e,n);if(r+2>e.length)return;let u=l(r),o=r+2;for(let t=0;t<u;t++){if(o+12>e.length)return;let t=l(o),r=l(o+2),n=s(o+4)*([0,1,1,2,4,8,0,1][r]??1),u=n<=4?o+8:s(o+8);u+n<=e.length&&i(t,e.subarray(u,u+n)),o+=12}}function h(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var d=new TextDecoder("utf-8",{fatal:!0}),g=String.fromCharCode;function _(e,t,r){let n="";for(let i=0;i<r;i++)n+=g(e[t+i]);return n}function b(e){try{return d.decode(e).replace(/\0$/,"")}catch{return null}}function y(e){let t=e.indexOf(0);return _(e,0,t<0?e.length:t).trim()||null}return{parse:function(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):e;return 137===t[0]&&80===t[1]?i(function(e){let t={},r=h(e),n=8;for(;n+8<=e.length;){let i=r.getUint32(n),l=_(e,n+4,4);if(n+=8,n+i>e.length)break;if("caBX"===l&&(t.cabx=_(e,n,Math.min(i,8388608))),"eXIf"===l&&Object.assign(t,p(e.subarray(n,n+i))),"tEXt"===l||"iTXt"===l){let r=e.indexOf(0,n);if(r>n&&r<n+i){let s=_(e,n,r-n);if("tEXt"===l){let l=e.subarray(r+1,n+i);t[s]=b(l)??_(e,r+1,n+i-r-1)}else{let l=r+3,u=e.indexOf(0,l),o=u<0?-1:e.indexOf(0,u+1);if(u<0||o<0){n+=i+4;continue}t[s]=b(e.subarray(o+1,n+i))??""}}}if("IEND"===l)break;n+=i+4}return t}(t)):255===t[0]&&216===t[1]?i(function(e){let t={},r=2;for(;r+4<=e.length;){let n=e[r+1];if(255!==e[r]||255===n){r++;continue}if(n>216&&n<219)break;let i=e[r+2]<<8|e[r+3];if(225===n&&r+10<=e.length&&"Exif\0\0"===_(e,r+4,6)&&Object.assign(t,p(e.subarray(r+10,r+2+i))),235===n&&(t.cabx=(t.cabx??"")+_(e,r+12,i-10)),254===n){let n=b(e.subarray(r+4,r+2+i));n&&(t.Comment=n)}r+=2+i}return t}(t)):82===t[0]&&73===t[1]?i(function(e){let t=h(e),r=12;for(;r+8<=e.length;){let n=_(e,r,4),i=t.getUint32(r+4,!0);if(r+=8,"EXIF"===n&&r+i<=e.length)return p(e.subarray(r,r+i));r+=i+i%2}return{}}(t)):""}}})();
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/extract.ts
|
|
2
2
|
const CT = "class_type";
|
|
3
3
|
const PARAMS = "parameters";
|
|
4
4
|
const EASY_DIFF_KEY = "use_stable_diffusion_model";
|
|
@@ -25,7 +25,7 @@ function channelKnownKeys(src, entries) {
|
|
|
25
25
|
]) if (src[key]) {
|
|
26
26
|
const result = {
|
|
27
27
|
...entries,
|
|
28
|
-
[PARAMS]: entries[PARAMS] ?? stringifyValue(src[key]).replace(
|
|
28
|
+
[PARAMS]: entries[PARAMS] ?? stringifyValue(src[key]).replace(/(?<!\0)\0+$/, "")
|
|
29
29
|
};
|
|
30
30
|
if (src.prompt) result.prompt ??= stringifyValue(src.prompt);
|
|
31
31
|
return result;
|
|
@@ -85,12 +85,11 @@ function extract(rawEntries) {
|
|
|
85
85
|
const prompt = entries.prompt ?? entries.Prompt;
|
|
86
86
|
if (params?.includes("sui_image_params")) {
|
|
87
87
|
const obj = parseJson(params);
|
|
88
|
-
return buildA1111(extractCommon(obj.sui_image_params ?? obj));
|
|
88
|
+
if (obj) return buildA1111(extractCommon(obj.sui_image_params ?? obj));
|
|
89
89
|
}
|
|
90
90
|
if (params && !params.startsWith("{")) return params;
|
|
91
91
|
if (params) {
|
|
92
|
-
const
|
|
93
|
-
const obj = typeof raw === "string" ? parseJson(raw) : raw;
|
|
92
|
+
const obj = parseJson(params);
|
|
94
93
|
if (obj) {
|
|
95
94
|
if (entries.Source) obj.Source = entries.Source;
|
|
96
95
|
const result = tryJsonTool(obj, params);
|
|
@@ -150,7 +149,7 @@ function tryJsonTool(obj, text) {
|
|
|
150
149
|
if (asText(obj.software).includes("RuinedFooocus")) return buildA1111(extractCommon(obj));
|
|
151
150
|
if (EASY_DIFF_KEY in obj) return buildA1111(extractCommon(obj));
|
|
152
151
|
if (text.includes("\"Model\"") && text.includes("\"resolution\"")) {
|
|
153
|
-
const [w, h] = parseDimensions(asText(obj.resolution), /(\d+)\s*x\s*(\d+)/);
|
|
152
|
+
const [w, h] = parseDimensions(asText(obj.resolution), /(?<!\d)(\d+)\s*x\s*(\d+)/);
|
|
154
153
|
return buildA1111({
|
|
155
154
|
...extractCommon(obj),
|
|
156
155
|
w,
|
|
@@ -235,7 +234,7 @@ function buildNovelAI(obj) {
|
|
|
235
234
|
function flatScan(json) {
|
|
236
235
|
const result = {};
|
|
237
236
|
let up = "";
|
|
238
|
-
const nodes = parseJson(json.replace(
|
|
237
|
+
const nodes = parseJson(json.replace(/(?<!\0)\0+$/, "").replace(/\bNaN\b/g, "null"));
|
|
239
238
|
if (!nodes) return result;
|
|
240
239
|
for (const key in nodes) {
|
|
241
240
|
const node = nodes[key];
|
|
@@ -308,9 +307,11 @@ function parseJson(text) {
|
|
|
308
307
|
}
|
|
309
308
|
}
|
|
310
309
|
/**
|
|
311
|
-
* Coerce a scalar to text. Strings pass through unchanged (
|
|
312
|
-
*
|
|
313
|
-
*
|
|
310
|
+
* Coerce a scalar to text. Strings pass through unchanged (a 64-bit seed
|
|
311
|
+
* written as a string keeps every digit), numbers are stringified (one
|
|
312
|
+
* written as a JSON number was already rounded past 2^53 by JSON.parse),
|
|
313
|
+
* and anything else — missing, null, objects, ComfyUI node references like
|
|
314
|
+
* ["95", 0] — becomes "".
|
|
314
315
|
*
|
|
315
316
|
* Every value ends up interpolated into A1111 text, so there is no reason to
|
|
316
317
|
* hold numbers as numbers. Returning "" (falsy) enables `||` fallback chains:
|
|
@@ -341,8 +342,7 @@ function parseDimensions(text, pattern) {
|
|
|
341
342
|
const match = text.match(pattern);
|
|
342
343
|
return match ? [match[1], match[2]] : [];
|
|
343
344
|
}
|
|
344
|
-
|
|
345
|
-
//#region src/read.ts
|
|
345
|
+
// src/read.ts
|
|
346
346
|
const MAX_CABX = 8388608;
|
|
347
347
|
/**
|
|
348
348
|
* Extract text chunks from PNG data as keyword→text entries.
|
|
@@ -540,8 +540,7 @@ function decodeUtf16(data, le) {
|
|
|
540
540
|
}
|
|
541
541
|
return s;
|
|
542
542
|
}
|
|
543
|
-
|
|
544
|
-
//#region src/index.ts
|
|
543
|
+
// src/index.ts
|
|
545
544
|
/**
|
|
546
545
|
* @enslo/sd-metadata-lite
|
|
547
546
|
*
|
|
@@ -566,7 +565,6 @@ function parse(input) {
|
|
|
566
565
|
if (data[0] === 82 && data[1] === 73) return extract(readWebp(data));
|
|
567
566
|
return "";
|
|
568
567
|
}
|
|
569
|
-
//#endregion
|
|
570
568
|
export { parse };
|
|
571
569
|
|
|
572
570
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/extract.ts","../src/read.ts","../src/index.ts"],"sourcesContent":["/**\n * Unified detection, parsing, and A1111 text building engine.\n *\n * Architecture (two-stage pipeline):\n *\n * normalize(entries) — Pure channeling function. Identifies WHERE the\n * generation data lives and routes it into a uniform\n * `entries.parameters` field. Never parses content.\n *\n * extract(entries) — Reads `entries.parameters` (and other fields),\n * detects the originating tool, extracts metadata,\n * and builds A1111-format output text.\n *\n * Supported tools:\n * A1111 / Forge / reForge, NovelAI, ComfyUI, SwarmUI, InvokeAI,\n * Civitai, TensorArt, Fooocus, RuinedFooocus, EasyDiffusion, HF Space\n */\n\nimport type { Entries } from './read';\n\ntype JsonObject = Record<string, unknown>;\n\n/**\n * Internal parameter bag for generation metadata.\n *\n * Every field is text: the output is A1111-format text and lite never does\n * arithmetic on these values, so numbers are kept exactly as the tool wrote\n * them (64-bit seeds included). An empty string means \"not found\".\n *\n * Property names are kept to 1-2 characters because esbuild does not\n * mangle object properties — shorter keys keep the IIFE bundle small.\n * Hover over each field for its full description via JSDoc.\n */\ninterface GenerationParams {\n /** Positive prompt text */\n p?: string;\n /** Negative prompt text */\n n?: string;\n /** Random seed */\n se?: string;\n /** Sampling steps */\n st?: string;\n /** CFG scale (classifier-free guidance) */\n cf?: string;\n /** Sampler algorithm name */\n sa?: string;\n /** Noise scheduler */\n sc?: string;\n /** Image width in pixels */\n w?: string;\n /** Image height in pixels */\n h?: string;\n /** Model filename */\n md?: string;\n /** Model hash */\n mh?: string;\n /** CLIP skip */\n cs?: string;\n /** Denoising strength */\n dn?: string;\n /** Hires upscale factor */\n hs?: string;\n /** Hires upscaler name */\n hu?: string;\n /** Hires denoising strength */\n hd?: string;\n /** Hires sampling steps */\n ht?: string;\n}\n\n// ComfyUI node-graph key. Extracted as a constant so the string literal\n// appears only once in the minified IIFE (used in both extract and flatScan).\nconst CT = 'class_type';\n\n// Extracted as a constant so the 10-character string literal appears only\n// once in the minified IIFE (used 13× across normalize, channelKnownKeys,\n// and extract).\nconst PARAMS = 'parameters';\n\n// EasyDiffusion stores metadata as flat PNG tEXt entries keyed by this name.\n// Extracted as a constant because the 27-character string appears in three\n// places: detection (tryJsonTool, extract) and extraction (extractCommon).\nconst EASY_DIFF_KEY = 'use_stable_diffusion_model';\n\n// ============================================================================\n// Normalize — Pure Channeling (no parsing, no mutation)\n// ============================================================================\n\n/**\n * Channel tool-specific entry keys into `entries.parameters`.\n *\n * Each key string appears exactly once in this loop to minimize IIFE size\n * (esbuild cannot mangle object property names).\n *\n * Matched keys and their tools:\n * - \"extraMetadata\" → Civitai (JPEG UserComment JSON)\n * - \"invokeai_metadata\" → InvokeAI (PNG tEXt / JPEG UserComment JSON)\n * - \"generation_data\" → TensorArt (JPEG UserComment JSON)\n *\n * Returns a NEW Entries with the matched value routed to `parameters`.\n * If no key matches, returns the original `entries` reference unchanged\n * (enables identity check with `!==`).\n */\nfunction channelKnownKeys(\n src: Record<string, unknown>,\n entries: Entries,\n): Entries {\n for (const key of ['extraMetadata', 'invokeai_metadata', 'generation_data']) {\n if (src[key]) {\n const result: Entries = {\n ...entries,\n // PNG tEXt chunks can have trailing null bytes — strip them.\n [PARAMS]:\n entries[PARAMS] ?? stringifyValue(src[key]).replace(/\\0+$/, ''),\n };\n // TensorArt stores ComfyUI workflow JSON in a separate \"prompt\" key.\n // Preserve it so extract() can merge ComfyUI nodes with TensorArt metadata.\n if (src.prompt) result.prompt ??= stringifyValue(src.prompt);\n return result;\n }\n }\n return entries;\n}\n\n/**\n * Normalize heterogeneous entry formats into a uniform shape.\n *\n * Pure function — returns a new Entries without mutating the input.\n * Only identifies WHERE data lives and channels it to `entries.parameters`.\n * All actual parsing/extraction is deferred to extract().\n *\n * Entry points by image format:\n * PNG → entries already has named keys (parameters, prompt, Comment, etc.)\n * JPEG → metadata is in EXIF UserComment (plain text or JSON blob)\n * WebP → same as JPEG (EXIF-based)\n */\nfunction normalize(entries: Entries): Entries {\n // NovelAI (PNG/WebP): metadata is in the Comment field.\n // When Software starts with \"NovelAI\", Comment is always present.\n if (entries.Software?.startsWith('NovelAI'))\n return { ...entries, [PARAMS]: entries[PARAMS] ?? entries.Comment! };\n\n // All remaining JPEG/WebP paths go through UserComment.\n const uc = entries.UserComment;\n\n // No UserComment: check top-level entries for tool-specific keys.\n // This handles PNG images from InvokeAI, Civitai, TensorArt where\n // the data is stored in named PNG tEXt chunks.\n if (!uc) return channelKnownKeys(entries, entries);\n\n // Plain-text UserComment (not JSON).\n if (!uc.startsWith('{')) {\n // A1111 / Forge / reForge (JPEG): UserComment contains A1111-format\n // text with \"Steps:\" marker. Channel it directly to parameters.\n if (uc.includes('Steps:'))\n return { ...entries, [PARAMS]: entries[PARAMS] ?? uc };\n // Unknown plain text — return unchanged.\n return entries;\n }\n\n // JSON UserComment — parse the envelope to inspect keys.\n const obj = parseJson(uc);\n if (!obj) return entries;\n\n // Check for tool-specific keys inside the JSON envelope.\n // Civitai, InvokeAI, TensorArt (JPEG) embed their data as nested JSON.\n const channeled = channelKnownKeys(obj, entries);\n if (channeled !== entries) return channeled;\n\n // ComfyUI (JPEG): UserComment has both \"prompt\" (node graph) and\n // \"workflow\" keys. Extract the prompt for flatScan in extract().\n if ('prompt' in obj && 'workflow' in obj)\n return { ...entries, prompt: entries.prompt ?? stringifyValue(obj.prompt) };\n\n // A1111 / Forge (JPEG variant): some tools wrap A1111-format text\n // inside a JSON object with a \"parameters\" key.\n if (PARAMS in obj)\n return {\n ...entries,\n [PARAMS]: entries[PARAMS] ?? stringifyValue(obj[PARAMS]),\n };\n\n // Unknown JSON structure — treat the entire UserComment as parameters\n // so extract() can attempt tool detection on it.\n return { ...entries, [PARAMS]: entries[PARAMS] ?? uc };\n}\n\n// ============================================================================\n// Extract — Detection, Extraction, and A1111 Text Building\n// ============================================================================\n\n/**\n * Main entry point: detect the originating tool, extract metadata from\n * normalized entries, and return human-readable A1111-format text.\n */\nexport function extract(rawEntries: Entries): string {\n const entries = normalize(rawEntries);\n const params = entries[PARAMS];\n // Hoisted: used in both the JSON block and the ComfyUI-only fallback below.\n const prompt = entries.prompt ?? entries.Prompt;\n\n // --- SwarmUI ---------------------------------------------------------\n // SwarmUI wraps its metadata in a \"sui_image_params\" key.\n if (params?.includes('sui_image_params')) {\n const obj = parseJson(params)!;\n return buildA1111(\n extractCommon((obj.sui_image_params ?? obj) as JsonObject),\n );\n }\n\n // --- Plain text (A1111 / Forge / reForge) ----------------------------\n // Already in A1111 format — return as-is.\n if (params && !params.startsWith('{')) return params;\n\n // --- JSON parameters -------------------------------------------------\n if (params) {\n // First parse: Civitai's extraMetadata can be double-encoded\n // (JSON string containing another JSON string), so we check if\n // the parsed result is itself a string and parse again.\n const raw = parseJson(params) as unknown;\n const obj = (\n typeof raw === 'string' ? parseJson(raw) : raw\n ) as JsonObject | null;\n if (obj) {\n // Try specific tool detectors (RuinedFooocus, EasyDiffusion,\n // Fooocus, HF Space, NovelAI).\n // NovelAI keeps the model in Source, outside the Comment JSON.\n if (entries.Source) obj.Source = entries.Source;\n const result = tryJsonTool(obj, params);\n if (result) return result;\n\n // ComfyUI (PNG): node graph stored directly in parameters.\n if (params.includes(CT)) return buildA1111(flatScan(params));\n\n // Generic JSON fallback: extract common fields.\n // Handles InvokeAI, Civitai, TensorArt, and other tools that\n // use standard field names (prompt, seed, steps, cfg, etc.).\n const base = extractCommon(obj);\n\n // TensorArt + ComfyUI hybrid: TensorArt stores generation\n // metadata in generation_data (→ params), but the ComfyUI\n // node graph is in a separate prompt field. Merge them:\n // flatScan provides seed/steps/cfg/sampler from ComfyUI nodes,\n // base provides prompt/negative/model/hash from TensorArt.\n if (prompt?.includes(CT))\n return buildA1111({\n ...flatScan(prompt),\n p: base.p,\n n: base.n,\n md: base.md,\n mh: base.mh,\n });\n\n return buildA1111(base);\n }\n }\n\n // --- EasyDiffusion (PNG, non-JSON parameters) ------------------------\n // EasyDiffusion stores fields as top-level PNG tEXt entries with a\n // distinctive \"use_stable_diffusion_model\" key. Its clip_skip is a boolean\n // written as \"False\"/\"True\", not an A1111 layer count, so the field is\n // dropped (the JSON form is `false` and already comes out blank).\n if (entries[EASY_DIFF_KEY])\n return buildA1111({ ...extractCommon(entries), cs: '' });\n\n // --- ComfyUI (PNG, no parameters field) ------------------------------\n // Some ComfyUI outputs only have a \"prompt\" PNG tEXt chunk\n // containing the node graph (no \"parameters\" chunk).\n if (prompt?.includes(CT)) return buildA1111(flatScan(prompt));\n\n // --- Final fallback --------------------------------------------------\n // Return whatever text is available, trying the most likely fields first.\n // C2PA Content Credentials (ChatGPT / Gemini / Grok) carry no generation\n // params, so their generator name is the fallback. It comes before the\n // EXIF text, which a vendor image only uses for its own markers (Grok\n // writes a signature there).\n return (\n params ??\n (readC2paName(entries.cabx) ||\n (entries.UserComment ??\n entries.Comment ??\n entries.ImageDescription ??\n ''))\n );\n}\n\n// ============================================================================\n// C2PA (Content Credentials)\n// ============================================================================\n\n/**\n * Recover `claim_generator_info.name` from a caBX manifest captured as a Latin-1\n * string (1:1 byte view, see readPng). Detection only — no JUMBF/CBOR decoder\n * and no signature verification.\n *\n * The `name` key is encoded as 0x64 ('d') + \"name\", i.e. the run \"dname\", so the\n * value's CBOR text-string header sits 5 bytes later. Generator names are short\n * ASCII, so only inline (0x60-0x77) and 1-byte (0x78) length headers are read.\n * charCodeAt yields NaN past the string end, which fails every comparison below,\n * so out-of-range offsets fall through to \"\".\n */\nfunction readC2paName(manifest: string | undefined): string {\n if (!manifest) return '';\n\n const cgi = manifest.indexOf('claim_generator_info');\n if (cgi < 0) return '';\n\n // Require the key within a short window of the marker so a stray \"...name\"\n // elsewhere cannot be misread as the generator name.\n const p = manifest.indexOf('dname', cgi);\n if (p < 0 || p > cgi + 256) return '';\n\n const pos = p + 5;\n const head = manifest.charCodeAt(pos);\n if (!(head >= 0x60 && head <= 0x78)) return '';\n\n const oneByte = head === 0x78;\n const length = oneByte ? manifest.charCodeAt(pos + 1) || 0 : head - 0x60;\n const dataPos = pos + (oneByte ? 2 : 1);\n if (dataPos + length > manifest.length) return '';\n\n return manifest.slice(dataPos, dataPos + length);\n}\n\n// ============================================================================\n// JSON Tool Detector\n// ============================================================================\n\n/**\n * Attempt to identify specific tools from a parsed JSON object.\n * Returns A1111-format text if a tool is recognized, null otherwise.\n *\n * Detection is ordered from most specific to least specific signatures.\n */\nfunction tryJsonTool(obj: JsonObject, text: string): string | null {\n // RuinedFooocus: identified by \"software\" field containing \"RuinedFooocus\".\n if (asText(obj.software).includes('RuinedFooocus'))\n return buildA1111(extractCommon(obj));\n\n // EasyDiffusion (JSON variant): identified by \"use_stable_diffusion_model\".\n if (EASY_DIFF_KEY in obj) return buildA1111(extractCommon(obj));\n\n // Fooocus: identified by having both \"Model\" (capital M) and \"resolution\"\n // keys. Resolution format: \"1024x1024\". Also has optional upscaler data.\n if (text.includes('\"Model\"') && text.includes('\"resolution\"')) {\n const [w, h] = parseDimensions(asText(obj.resolution), /(\\d+)\\s*x\\s*(\\d+)/);\n return buildA1111({ ...extractCommon(obj), w, h });\n }\n\n // HF Space / Civitai generator / Fooocus JSON scheme: identified by\n // \"base_model\" key.\n // Resolution format: \"(1024, 1024)\" (Python tuple string).\n if ('base_model' in obj) {\n const [w, h] = parseDimensions(\n asText(obj.resolution),\n /\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/,\n );\n return buildA1111({ ...extractCommon(obj), w, h });\n }\n\n // NovelAI (PNG/WebP JSON): identified by \"noise_schedule\" key.\n // Has special v4 prompt format that needs dedicated handling.\n if ('noise_schedule' in obj) return buildNovelAI(obj);\n\n return null;\n}\n\n// ============================================================================\n// Common JSON Extractor\n// ============================================================================\n\n/**\n * Extract GenerationParams from a JSON object using field name fallback chains.\n *\n * Each field tries multiple property names to cover all known JSON-based tools.\n * The fallback order generally goes: most common name → tool-specific aliases.\n *\n * Covered tools: A1111, NovelAI, SwarmUI, InvokeAI, Civitai, TensorArt,\n * Fooocus, RuinedFooocus, EasyDiffusion, HF Space.\n */\nfunction extractCommon(obj: Record<string, unknown>): GenerationParams {\n const sa = asText(obj.sampler ?? obj.sampler_name);\n const sc = asText(obj.scheduler ?? obj.noise_schedule);\n const mod = obj.model as JsonObject | undefined;\n const base = obj.baseModel as JsonObject | undefined;\n const up = obj.use_upscaler as JsonObject | undefined;\n return {\n // Prompt: Fooocus \"full_prompt\" (style-resolved parts, joined with \", \"\n // like its own a1111 scheme) → \"prompt\" (most tools) → \"Prompt\" (Fooocus)\n // → \"positive_prompt\" (RuinedFooocus)\n p:\n (obj.full_prompt as string[] | undefined)?.join?.(', ') ||\n asText(obj.prompt ?? obj.Prompt ?? obj.positive_prompt),\n // Negative: multiple naming conventions across tools\n // \"uc\" = NovelAI's \"undesired content\"\n n:\n (obj.full_negative_prompt as string[] | undefined)?.join?.(', ') ||\n asText(\n obj.negative_prompt ??\n obj.Negative ??\n obj.negativeprompt ??\n obj.negativePrompt ??\n obj.uc,\n ),\n se: asText(obj.seed),\n // \"num_inference_steps\" = HF Space / Civitai generator\n st: asText(obj.steps ?? obj.num_inference_steps),\n // CFG: many naming variants across tools\n // \"scale\" = NovelAI, \"guidance_scale\" = HF Space\n cf: asText(\n obj.cfg ??\n obj.cfg_scale ??\n obj.cfgScale ??\n obj.cfgscale ??\n obj.guidance_scale ??\n obj.scale,\n ),\n // InvokeAI quirk: stores the sampler name in the \"scheduler\" field\n // and has no separate sampler field. If sa is empty, use sc as sa.\n sa: sa || sc,\n sc: sa ? sc : undefined,\n w: asText(obj.width),\n h: asText(obj.height),\n // Model name: extensive fallback chain covering all known patterns.\n // \"model\" (string) → InvokeAI, SwarmUI, Civitai\n // \"Model\" (capital) → Fooocus\n // \"base_model\" → HF Space\n // \"base_model_name\" → Civitai generator\n // \"baseModel\" (string) → TensorArt (when stored as string)\n // \"model.name\" → Civitai (nested object)\n // \"baseModel.modelFileName\" → TensorArt (nested object)\n // \"use_stable_diffusion_model\" → EasyDiffusion (full path, take filename)\n md:\n asText(mod) ||\n asText(obj.Model) ||\n asText(obj.base_model) ||\n asText(obj.base_model_name) ||\n asText(base) ||\n asText(mod?.name) ||\n asText(base?.modelFileName) ||\n asText(obj[EASY_DIFF_KEY]).split(/[\\\\/]/).pop(),\n // Model hash: similar multi-tool fallback chain.\n // \"Model hash\" → Fooocus\n // \"model.hash\" → Civitai (nested)\n // \"baseModel.hash\" → TensorArt (nested)\n mh:\n asText(obj.base_model_hash) ||\n asText(obj['Model hash']) ||\n asText(mod?.hash) ||\n asText(base?.hash),\n cs: asText(obj.clip_skip ?? obj.clipSkip),\n // Hires/upscaler: use_upscaler (Fooocus, HF Space) → refiner* (SwarmUI)\n hs: asText(up?.upscale_by) || asText(obj.refinerupscale),\n hu: asText(up?.upscale_method) || asText(obj.refinerupscalemethod),\n hd: asText(up?.upscaler_strength) || asText(obj.refinercontrolpercentage),\n ht: asText(up?.upscale_steps),\n };\n}\n\n// ============================================================================\n// Tool-Specific Builders\n// ============================================================================\n\n/**\n * Build A1111 text from NovelAI JSON metadata.\n *\n * NovelAI v4+ uses a nested prompt structure:\n * { v4_prompt: { caption: { base_caption: \"...\" } } }\n * Falls back to flat \"prompt\" / \"uc\" fields for older versions.\n */\nfunction buildNovelAI(obj: JsonObject): string {\n const v4Caption = (obj.v4_prompt as JsonObject)?.caption as\n | JsonObject\n | undefined;\n const v4NegCaption = (obj.v4_negative_prompt as JsonObject)?.caption as\n | JsonObject\n | undefined;\n // Source is \"<model name> <8-digit hex hash>\"\n const src = /^(.+) ([0-9A-F]{8})$/.exec(asText(obj.Source));\n return buildA1111({\n ...extractCommon(obj),\n // Prefer v4 captions, fall back to legacy flat fields. The V5 web\n // client appends quoted texts as \", teXt: ...\"; drop that block.\n p: (asText(v4Caption?.base_caption) || asText(obj.prompt)).replace(\n /(^|, )teXt:(?!:).*/s,\n '',\n ),\n n: asText(v4NegCaption?.base_caption) || asText(obj.uc),\n // img2img strength (Img2ImgRequest only)\n dn: asText(obj.strength),\n md: src?.[1] ?? asText(obj.Source),\n mh: src?.[2],\n });\n}\n\n// ============================================================================\n// ComfyUI Flat Scanner\n// ============================================================================\n\n/**\n * Scan a ComfyUI node graph (flat JSON) and extract generation parameters.\n *\n * ComfyUI stores metadata as a dictionary of nodes, each with a \"class_type\"\n * and \"inputs\" object. This function iterates all nodes and extracts\n * relevant parameters based on the node's class type.\n *\n * The \"first match wins\" strategy (??= / ||=) ensures we pick the primary\n * node when multiple nodes of the same type exist (e.g. two KSamplers).\n */\nfunction flatScan(json: string): GenerationParams {\n const result: GenerationParams = {};\n // User-prompt fallback: official enhancer templates (e.g. Krea-2 Turbo)\n // hold the user's input in a PrimitiveStringMultiline titled\n // \"... (User Prompt)\" while CLIPTextEncode only carries node references.\n // Collected during the scan, applied only when no text node yielded a\n // prompt literal.\n let up = '';\n // Pre-clean: strip trailing null bytes (PNG chunks) and replace NaN\n // literals that some ComfyUI versions emit (invalid JSON).\n const nodes = parseJson(json.replace(/\\0+$/, '').replace(/\\bNaN\\b/g, 'null'));\n if (!nodes) return result;\n\n for (const key in nodes) {\n const node = nodes[key] as JsonObject;\n if (!node || typeof node !== 'object') continue;\n const classType = asText(node[CT]);\n const inputs = node.inputs as JsonObject | undefined;\n if (!inputs) continue;\n\n if (/User Prompt/.test(asText((node._meta as JsonObject)?.title)))\n up ||= asText(inputs.value);\n\n // --- Prompt text nodes -------------------------------------------\n // Matches CLIPTextEncode (and variants like SDXL, Flux) via \"TextEncode\",\n // text box nodes (DF_Text_Box, TextBox) via \".?Box\", ShowText|pysssss\n // (pythongosssss/ComfyUI-Custom-Scripts) which caches composed prompts in\n // inputs.text_0, and PromptStashSaver which holds user-authored prompts in\n // inputs.prompt_text.\n // Unified classification: if class name contains \"neg\" → negative prompt,\n // otherwise first-come-first-served (1st → positive, 2nd → negative).\n if (/Text(Encode|.?Box)|ShowText|PromptStash/.test(classType)) {\n const txt =\n asText(inputs.text) ||\n asText(inputs.prompt) ||\n asText(inputs.Text) ||\n asText(inputs.prompt_text) ||\n asText(inputs.text_0);\n if (txt) {\n if (/neg/i.test(classType)) {\n result.n ??= txt;\n } else {\n if (!result.p) result.p = txt;\n else if (!result.n) result.n = txt;\n }\n }\n }\n\n // --- Sampler nodes (KSampler, KSamplerAdvanced, etc.) ------------\n // Class-type guard is required here: \"steps\" and \"seed\" also appear\n // on non-sampler nodes (BasicScheduler, RandomNoise, etc.).\n if (classType.includes('Sampler')) {\n result.se ||= asText(inputs.seed) || asText(inputs.noise_seed);\n result.st ||= asText(inputs.steps);\n result.cf ||= asText(inputs.cfg);\n result.sa ||= asText(inputs.sampler_name);\n result.sc ||= asText(inputs.scheduler);\n }\n\n // --- Model loader nodes ------------------------------------------\n // ckpt_name / unet_name are unique to checkpoint and UNET loaders —\n // no class_type guard needed; unconditional ||= is safe here.\n result.md ||= asText(inputs.ckpt_name) || asText(inputs.unet_name);\n\n // --- Latent image nodes (for dimensions) -------------------------\n result.w ||= asText(inputs.width);\n result.h ||= asText(inputs.height);\n }\n result.p ||= up;\n return result;\n}\n\n// ============================================================================\n// A1111 Text Builder\n// ============================================================================\n\n/**\n * Build human-readable text in A1111 (Stable Diffusion WebUI) format.\n *\n * Output structure:\n * Line 1: positive prompt\n * Line 2: \"Negative prompt: <negative prompt>\"\n * Line 3: comma-separated key-value pairs (Steps, Sampler, CFG, etc.)\n */\nfunction buildA1111(params: GenerationParams): string {\n const lines: string[] = [];\n if (params.p) lines.push(params.p);\n if (params.n) lines.push(`Negative prompt: ${params.n}`);\n\n const fields: string[] = [];\n // addField only appends when value is non-empty (skips undefined and \"\").\n const addField = (key: string, value: string | undefined) => {\n if (value) fields.push(`${key}: ${value}`);\n };\n\n addField('Steps', params.st);\n addField('Sampler', params.sa);\n addField('Schedule type', params.sc);\n addField('CFG scale', params.cf);\n addField('Seed', params.se);\n if (params.w && params.h) addField('Size', `${params.w}x${params.h}`);\n addField('Model hash', params.mh);\n addField('Model', params.md);\n addField('Clip skip', params.cs);\n // Denoising strength: dn (standard) or hd (Fooocus refiner percentage).\n addField('Denoising strength', params.dn ?? params.hd);\n addField('Hires upscale', params.hs);\n addField('Hires steps', params.ht);\n addField('Hires upscaler', params.hu);\n\n if (fields.length) lines.push(fields.join(', '));\n return lines.join('\\n');\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Safely parse JSON, returning null on failure. */\nfunction parseJson(text: string | undefined): JsonObject | null {\n if (!text) return null;\n try {\n return JSON.parse(text) as JsonObject;\n } catch {\n return null;\n }\n}\n\n/**\n * Coerce a scalar to text. Strings pass through unchanged (so 64-bit seeds\n * keep every digit), numbers are stringified, and anything else — missing,\n * null, objects, ComfyUI node references like [\"95\", 0] — becomes \"\".\n *\n * Every value ends up interpolated into A1111 text, so there is no reason to\n * hold numbers as numbers. Returning \"\" (falsy) enables `||` fallback chains:\n * `asText(a) || asText(b)`.\n */\nfunction asText(v: unknown): string {\n return typeof v === 'string' ? v : typeof v === 'number' ? String(v) : '';\n}\n\n/**\n * Convert a value to its string representation for channeling.\n * Strings pass through unchanged; objects are JSON-serialized.\n * Used by channelKnownKeys to convert nested JSON objects to strings\n * that extract() can later re-parse.\n */\nfunction stringifyValue(v: unknown): string {\n if (typeof v === 'string') return v;\n if (v && typeof v === 'object') return JSON.stringify(v);\n return '';\n}\n\n/**\n * Extract width/height from a dimension string using the given regex.\n * Different tools use different formats:\n * - Fooocus: \"1024x1024\" → /(\\d+)\\s*x\\s*(\\d+)/\n * - HF Space: \"(1024, 1024)\" → /\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/\n */\nfunction parseDimensions(\n text: string | undefined,\n pattern: RegExp,\n): [string?, string?] {\n if (!text) return [];\n const match = text.match(pattern);\n return match ? [match[1], match[2]] : [];\n}\n","/**\n * Lightweight binary readers for PNG, JPEG, and WebP metadata extraction.\n * Uses DataView API for endian-aware integer reading.\n */\n\n// Entry record: keyword → text value\nexport type Entries = Record<string, string>;\n\n// Maximum caBX (C2PA) bytes captured. The generator marker sits near the start\n// of the box, so clamping bounds memory against a maliciously oversized chunk.\nconst MAX_CABX = 8 * 1024 * 1024;\n\n// ============================================================================\n// PNG Reader\n// ============================================================================\n\n/**\n * Extract text chunks from PNG data as keyword→text entries.\n */\nexport function readPng(data: Uint8Array): Entries {\n const entries: Entries = {};\n const dv = dataview(data);\n let offset = 8; // Skip PNG signature\n\n while (offset + 8 <= data.length) {\n const length = dv.getUint32(offset);\n const type = str(data, offset + 4, 4);\n offset += 8;\n\n if (offset + length > data.length) break;\n\n // caBX: C2PA Content Credentials. Capture the manifest as a Latin-1 string\n // (1:1 byte view) so extract() can recover the generator name from it.\n if (type === 'caBX') {\n entries.cabx = str(data, offset, Math.min(length, MAX_CABX));\n }\n\n // eXIf: a TIFF structure like a JPEG APP1 payload (CivitAI PNGs)\n if (type === 'eXIf')\n Object.assign(entries, readExif(data.subarray(offset, offset + length)));\n\n if (type === 'tEXt' || type === 'iTXt') {\n const nullIdx = data.indexOf(0, offset);\n if (nullIdx > offset && nullIdx < offset + length) {\n const keyword = str(data, offset, nullIdx - offset);\n if (type === 'tEXt') {\n const textData = data.subarray(nullIdx + 1, offset + length);\n entries[keyword] =\n tryUtf8(textData) ??\n str(data, nullIdx + 1, offset + length - nullIdx - 1);\n } else {\n // Skip null + compression flag (1) + method (1), then two null-terminated strings\n const pos = nullIdx + 3;\n const langEnd = data.indexOf(0, pos);\n const transEnd = langEnd < 0 ? -1 : data.indexOf(0, langEnd + 1);\n if (langEnd < 0 || transEnd < 0) {\n offset += length + 4;\n continue;\n }\n entries[keyword] =\n tryUtf8(data.subarray(transEnd + 1, offset + length)) ?? '';\n }\n }\n }\n\n if (type === 'IEND') break;\n offset += length + 4; // Skip data + CRC\n }\n\n return entries;\n}\n\n// ============================================================================\n// JPEG Reader\n// ============================================================================\n\n/**\n * Extract metadata from JPEG: EXIF UserComment/ImageDescription/Make/Model,\n * COM segment, and APP11 (C2PA) as `cabx`.\n */\nexport function readJpeg(data: Uint8Array): Entries {\n const entries: Entries = {};\n let offset = 2; // Skip SOI\n\n while (offset + 4 <= data.length) {\n const marker = data[offset + 1]!;\n if (data[offset] !== 0xff || marker === 0xff) {\n offset++;\n continue;\n }\n\n // SOS (0xDA) or EOI (0xD9) — stop scanning\n if (marker > 0xd8 && marker < 0xdb) break;\n\n const segLen = (data[offset + 2]! << 8) | data[offset + 3]!;\n\n // APP1 (EXIF)\n if (\n marker === 0xe1 &&\n offset + 10 <= data.length &&\n str(data, offset + 4, 6) === 'Exif\\0\\0'\n ) {\n Object.assign(\n entries,\n readExif(data.subarray(offset + 10, offset + 2 + segLen)),\n );\n }\n\n // APP11 (JUMBF): C2PA Content Credentials, captured like the PNG caBX chunk.\n // The 8 bytes after the length are the \"JP\" identifier, box instance and\n // packet number; continuation packets are appended as they come.\n if (marker === 0xeb)\n entries.cabx = (entries.cabx ?? '') + str(data, offset + 12, segLen - 10);\n\n // COM segment\n if (marker === 0xfe) {\n const comData = data.subarray(offset + 4, offset + 2 + segLen);\n const text = tryUtf8(comData);\n if (text) entries.Comment = text;\n }\n\n offset += 2 + segLen;\n }\n\n return entries;\n}\n\n// ============================================================================\n// WebP Reader\n// ============================================================================\n\n/**\n * Extract metadata from WebP: EXIF chunk → same EXIF parsing as JPEG.\n */\nexport function readWebp(data: Uint8Array): Entries {\n const dv = dataview(data);\n let offset = 12; // Skip RIFF header\n\n while (offset + 8 <= data.length) {\n const type = str(data, offset, 4);\n const chunkSize = dv.getUint32(offset + 4, true); // little-endian\n offset += 8;\n\n if (type === 'EXIF' && offset + chunkSize <= data.length) {\n return readExif(data.subarray(offset, offset + chunkSize));\n }\n\n // RIFF chunks are padded to even byte boundaries\n offset += chunkSize + (chunkSize % 2);\n }\n\n return {};\n}\n\n// ============================================================================\n// EXIF / TIFF Parser\n// ============================================================================\n\n/**\n * Parse EXIF/TIFF data and extract metadata entries.\n */\nfunction readExif(data: Uint8Array): Entries {\n if (data.length < 8) return {};\n\n const firstByte = data[0];\n const le = firstByte === 0x49; // \"II\" = little-endian (both bytes are identical per TIFF spec)\n if (!le && firstByte !== 0x4d) return {}; // Not \"MM\" either\n\n const dv = dataview(data);\n if (dv.getUint16(2, le) !== 42) return {}; // TIFF magic\n\n const entries: Entries = {};\n const ifd0 = dv.getUint32(4, le);\n\n // Scan IFD0 for ImageDescription, Make, Model, UserComment, and Exif IFD pointer\n let exifIfdOffset = 0;\n const handleUserComment = (tagData: Uint8Array) => {\n const text = decodeUserComment(tagData);\n if (text) {\n if (text.startsWith('{')) {\n try {\n const obj = JSON.parse(text) as Record<string, unknown>;\n const software = obj.Software;\n const comment = obj.Comment;\n if (\n typeof software === 'string' &&\n software.startsWith('NovelAI') &&\n typeof comment === 'string'\n ) {\n entries.Software = software;\n entries.Comment = comment;\n // Model name and hash, as in the PNG Source chunk\n entries.Source = obj.Source as string;\n return;\n }\n } catch {\n // Not valid JSON — fall through to UserComment assignment.\n }\n }\n entries.UserComment = text;\n }\n };\n scanIfd(data, dv, ifd0, le, (tag, tagData) => {\n // ImageDescription (0x010E) through Model (0x0110). Tools label the value\n // with the PNG chunk keyword it stands in for, so the label decides the\n // entry key: save-image-extended writes ImageDescription \"Workflow: {...}\"\n // and Make \"Prompt: {...}\", while ComfyUI's built-in Save Animated WEBP\n // writes Make \"workflow:{...}\" and Model \"prompt:{...}\".\n if (tag > 0x010d && tag < 0x0111) {\n const text = decodeAscii(tagData);\n if (text) {\n // The space after the colon is optional, but a bare colon only counts\n // in front of JSON so values like \"http://...\" keep their text.\n const prefixMatch = text.match(/^([A-Za-z]+):(?:\\s|(?=\\{))/);\n if (prefixMatch) {\n const key = prefixMatch[1];\n if (key) entries[key] = text.slice(prefixMatch[0].length);\n } else {\n entries[\n tag === 0x010e\n ? 'ImageDescription'\n : tag === 0x010f\n ? 'Make'\n : 'Model'\n ] = text;\n }\n }\n } else if (tag === 0x9286) {\n // UserComment\n handleUserComment(tagData);\n } else if (tag === 0x8769) {\n // Exif IFD pointer\n exifIfdOffset = dv.getUint32(tagData.byteOffset - data.byteOffset, le);\n }\n });\n\n // Scan Exif IFD for UserComment (if not already found in IFD0)\n if (exifIfdOffset && !entries.UserComment && !entries.Software) {\n scanIfd(data, dv, exifIfdOffset, le, (tag, tagData) => {\n if (tag === 0x9286) handleUserComment(tagData); // UserComment\n });\n }\n\n return entries;\n}\n\n/**\n * Scan IFD entries and call handler for each tag.\n */\nfunction scanIfd(\n data: Uint8Array,\n dv: DataView,\n ifdOffset: number,\n le: boolean,\n handler: (tag: number, tagData: Uint8Array) => void,\n): void {\n const u16 = (o: number) => dv.getUint16(o, le);\n const u32 = (o: number) => dv.getUint32(o, le);\n if (ifdOffset + 2 > data.length) return;\n const count = u16(ifdOffset);\n let pos = ifdOffset + 2;\n\n for (let i = 0; i < count; i++) {\n if (pos + 12 > data.length) return;\n const tag = u16(pos);\n const type = u16(pos + 2);\n const valueCount = u32(pos + 4);\n const typeSize = [0, 1, 1, 2, 4, 8, 0, 1][type] ?? 1;\n const size = valueCount * typeSize;\n const valOffset = size <= 4 ? pos + 8 : u32(pos + 8);\n\n if (valOffset + size <= data.length) {\n handler(tag, data.subarray(valOffset, valOffset + size));\n }\n pos += 12;\n }\n}\n\n// ============================================================================\n// String Decoders\n// ============================================================================\n\n// Shared DataView constructor — the 48-character expression appears 3x\n// (readPng, readWebp, readExif). A helper saves ~61 bytes minified.\nfunction dataview(data: Uint8Array): DataView {\n return new DataView(data.buffer, data.byteOffset, data.byteLength);\n}\n\nconst utf8Dec = new TextDecoder('utf-8', { fatal: true });\n\n// Alias for String.fromCharCode — used in str and decodeUtf16.\n// Saves ~38 bytes in the minified IIFE.\nconst fromCharCode = String.fromCharCode;\n\nfunction str(data: Uint8Array, offset: number, len: number): string {\n let s = '';\n for (let i = 0; i < len; i++) s += fromCharCode(data[offset + i]!);\n return s;\n}\n\nfunction tryUtf8(data: Uint8Array): string | null {\n try {\n return utf8Dec.decode(data).replace(/\\0$/, '');\n } catch {\n return null;\n }\n}\n\nfunction decodeAscii(data: Uint8Array): string | null {\n const nullIdx = data.indexOf(0);\n return str(data, 0, nullIdx < 0 ? data.length : nullIdx).trim() || null;\n}\n\n/**\n * Decode UserComment with encoding prefix detection.\n */\nfunction decodeUserComment(data: Uint8Array): string | null {\n if (data.length < 8) return null;\n\n const prefix = str(data, 0, 8);\n const payload = data.subarray(8);\n\n if (prefix === 'UNICODE\\0') {\n if (payload.length < 2) return null;\n const isLE = payload[0] !== 0 && payload[1] === 0;\n return decodeUtf16(payload, isLE);\n }\n\n if (prefix === 'ASCII\\0\\0\\0') {\n return decodeAscii(payload);\n }\n\n // Try raw UTF-8\n return tryUtf8(data);\n}\n\nfunction decodeUtf16(data: Uint8Array, le: boolean): string {\n let s = '';\n for (let i = 0; i + 1 < data.length; i += 2) {\n const code = le\n ? data[i]! | (data[i + 1]! << 8)\n : (data[i]! << 8) | data[i + 1]!;\n if (!code) break;\n s += fromCharCode(code);\n }\n return s;\n}\n","/**\n * @enslo/sd-metadata-lite\n *\n * Lightweight AI image metadata reader for bookmarklets.\n * Reads PNG/JPEG/WebP files and returns A1111-format plain text.\n */\n\nimport { extract } from './extract';\nimport { readJpeg, readPng, readWebp } from './read';\n\n/**\n * Parse AI-generated image metadata and return A1111-format text.\n *\n * Supports PNG, JPEG, and WebP formats across 18+ generation tools. For PNG\n * images with no generation parameters, falls back to C2PA Content Credentials\n * and returns the generator name (e.g. ChatGPT / Gemini exports).\n * Returns empty string if no metadata is found.\n *\n * @param input - Image file data\n * @returns A1111-format metadata text, the C2PA generator name, or empty string\n */\nexport function parse(input: Uint8Array | ArrayBuffer): string {\n const data = input instanceof ArrayBuffer ? new Uint8Array(input) : input;\n\n // Format detection is intentionally loose (first 2 bytes only) to\n // minimize bundle size. False positives are harmless: the reader\n // will find no metadata and extract() returns \"\".\n\n // PNG: 89 50 (full signature: 89 50 4E 47 0D 0A 1A 0A)\n if (data[0] === 0x89 && data[1] === 0x50) {\n return extract(readPng(data));\n }\n\n // JPEG: FF D8\n if (data[0] === 0xff && data[1] === 0xd8) {\n return extract(readJpeg(data));\n }\n\n // WebP: 52 49 (full signature: RIFF....WEBP)\n if (data[0] === 0x52 && data[1] === 0x49) {\n return extract(readWebp(data));\n }\n\n return '';\n}\n"],"mappings":";AAwEA,MAAM,KAAK;AAKX,MAAM,SAAS;AAKf,MAAM,gBAAgB;;;;;;;;;;;;;;;;AAqBtB,SAAS,iBACP,KACA,SACS;CACT,KAAK,MAAM,OAAO;EAAC;EAAiB;EAAqB;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O,IAClC,OAAO,QAAQ,SAAS,IAAI,CAAC;CAG/B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/extract.ts","../src/read.ts","../src/index.ts"],"sourcesContent":["/**\n * Unified detection, parsing, and A1111 text building engine.\n *\n * Architecture (two-stage pipeline):\n *\n * normalize(entries) — Pure channeling function. Identifies WHERE the\n * generation data lives and routes it into a uniform\n * `entries.parameters` field. Never parses content.\n *\n * extract(entries) — Reads `entries.parameters` (and other fields),\n * detects the originating tool, extracts metadata,\n * and builds A1111-format output text.\n *\n * Supported tools:\n * A1111 / Forge / reForge, NovelAI, ComfyUI, SwarmUI, InvokeAI,\n * Civitai, TensorArt, Fooocus, RuinedFooocus, EasyDiffusion, HF Space\n */\n\nimport type { Entries } from './read';\n\ntype JsonObject = Record<string, unknown>;\n\n/**\n * Internal parameter bag for generation metadata.\n *\n * Every field is text: the output is A1111-format text and lite never does\n * arithmetic on these values. Text is kept exactly as the tool wrote it,\n * so a 64-bit seed written as a string keeps every digit; one written as a\n * JSON number has already been rounded past 2^53 by JSON.parse, the same\n * limit the core library has. An empty string means \"not found\".\n *\n * Property names are kept to 1-2 characters because esbuild does not\n * mangle object properties — shorter keys keep the IIFE bundle small.\n * Hover over each field for its full description via JSDoc.\n */\ninterface GenerationParams {\n /** Positive prompt text */\n p?: string;\n /** Negative prompt text */\n n?: string;\n /** Random seed */\n se?: string;\n /** Sampling steps */\n st?: string;\n /** CFG scale (classifier-free guidance) */\n cf?: string;\n /** Sampler algorithm name */\n sa?: string;\n /** Noise scheduler */\n sc?: string;\n /** Image width in pixels */\n w?: string;\n /** Image height in pixels */\n h?: string;\n /** Model filename */\n md?: string;\n /** Model hash */\n mh?: string;\n /** CLIP skip */\n cs?: string;\n /** Denoising strength */\n dn?: string;\n /** Hires upscale factor */\n hs?: string;\n /** Hires upscaler name */\n hu?: string;\n /** Hires denoising strength */\n hd?: string;\n /** Hires sampling steps */\n ht?: string;\n}\n\n// ComfyUI node-graph key. Extracted as a constant so the string literal\n// appears only once in the minified IIFE (used in both extract and flatScan).\nconst CT = 'class_type';\n\n// Extracted as a constant so the 10-character string literal appears only\n// once in the minified IIFE (used 13× across normalize, channelKnownKeys,\n// and extract).\nconst PARAMS = 'parameters';\n\n// EasyDiffusion stores metadata as flat PNG tEXt entries keyed by this name.\n// Extracted as a constant because the 27-character string appears in three\n// places: detection (tryJsonTool, extract) and extraction (extractCommon).\nconst EASY_DIFF_KEY = 'use_stable_diffusion_model';\n\n// ============================================================================\n// Normalize — Pure Channeling (no parsing, no mutation)\n// ============================================================================\n\n/**\n * Channel tool-specific entry keys into `entries.parameters`.\n *\n * Each key string appears exactly once in this loop to minimize IIFE size\n * (esbuild cannot mangle object property names).\n *\n * Matched keys and their tools:\n * - \"extraMetadata\" → Civitai (JPEG UserComment JSON)\n * - \"invokeai_metadata\" → InvokeAI (PNG tEXt / JPEG UserComment JSON)\n * - \"generation_data\" → TensorArt (JPEG UserComment JSON)\n *\n * Returns a NEW Entries with the matched value routed to `parameters`.\n * If no key matches, returns the original `entries` reference unchanged\n * (enables identity check with `!==`).\n */\nfunction channelKnownKeys(\n src: Record<string, unknown>,\n entries: Entries,\n): Entries {\n for (const key of ['extraMetadata', 'invokeai_metadata', 'generation_data']) {\n if (src[key]) {\n const result: Entries = {\n ...entries,\n // PNG tEXt chunks can have trailing null bytes — strip them. The\n // lookbehind starts the match at the first NUL of the run only, so a\n // byte after the run does not make the regex retry from every NUL.\n [PARAMS]:\n entries[PARAMS] ??\n stringifyValue(src[key]).replace(/(?<!\\0)\\0+$/, ''),\n };\n // TensorArt stores ComfyUI workflow JSON in a separate \"prompt\" key.\n // Preserve it so extract() can merge ComfyUI nodes with TensorArt metadata.\n if (src.prompt) result.prompt ??= stringifyValue(src.prompt);\n return result;\n }\n }\n return entries;\n}\n\n/**\n * Normalize heterogeneous entry formats into a uniform shape.\n *\n * Pure function — returns a new Entries without mutating the input.\n * Only identifies WHERE data lives and channels it to `entries.parameters`.\n * All actual parsing/extraction is deferred to extract().\n *\n * Entry points by image format:\n * PNG → entries already has named keys (parameters, prompt, Comment, etc.)\n * JPEG → metadata is in EXIF UserComment (plain text or JSON blob)\n * WebP → same as JPEG (EXIF-based)\n */\nfunction normalize(entries: Entries): Entries {\n // NovelAI (PNG/WebP): metadata is in the Comment field.\n // When Software starts with \"NovelAI\", Comment is always present.\n if (entries.Software?.startsWith('NovelAI'))\n return { ...entries, [PARAMS]: entries[PARAMS] ?? entries.Comment! };\n\n // All remaining JPEG/WebP paths go through UserComment.\n const uc = entries.UserComment;\n\n // No UserComment: check top-level entries for tool-specific keys.\n // This handles PNG images from InvokeAI, Civitai, TensorArt where\n // the data is stored in named PNG tEXt chunks.\n if (!uc) return channelKnownKeys(entries, entries);\n\n // Plain-text UserComment (not JSON).\n if (!uc.startsWith('{')) {\n // A1111 / Forge / reForge (JPEG): UserComment contains A1111-format\n // text with \"Steps:\" marker. Channel it directly to parameters.\n if (uc.includes('Steps:'))\n return { ...entries, [PARAMS]: entries[PARAMS] ?? uc };\n // Unknown plain text — return unchanged.\n return entries;\n }\n\n // JSON UserComment — parse the envelope to inspect keys.\n const obj = parseJson(uc);\n if (!obj) return entries;\n\n // Check for tool-specific keys inside the JSON envelope.\n // Civitai, InvokeAI, TensorArt (JPEG) embed their data as nested JSON.\n const channeled = channelKnownKeys(obj, entries);\n if (channeled !== entries) return channeled;\n\n // ComfyUI (JPEG): UserComment has both \"prompt\" (node graph) and\n // \"workflow\" keys. Extract the prompt for flatScan in extract().\n if ('prompt' in obj && 'workflow' in obj)\n return { ...entries, prompt: entries.prompt ?? stringifyValue(obj.prompt) };\n\n // A1111 / Forge (JPEG variant): some tools wrap A1111-format text\n // inside a JSON object with a \"parameters\" key.\n if (PARAMS in obj)\n return {\n ...entries,\n [PARAMS]: entries[PARAMS] ?? stringifyValue(obj[PARAMS]),\n };\n\n // Unknown JSON structure — treat the entire UserComment as parameters\n // so extract() can attempt tool detection on it.\n return { ...entries, [PARAMS]: entries[PARAMS] ?? uc };\n}\n\n// ============================================================================\n// Extract — Detection, Extraction, and A1111 Text Building\n// ============================================================================\n\n/**\n * Main entry point: detect the originating tool, extract metadata from\n * normalized entries, and return human-readable A1111-format text.\n */\nexport function extract(rawEntries: Entries): string {\n const entries = normalize(rawEntries);\n const params = entries[PARAMS];\n // Hoisted: used in both the JSON block and the ComfyUI-only fallback below.\n const prompt = entries.prompt ?? entries.Prompt;\n\n // --- SwarmUI ---------------------------------------------------------\n // SwarmUI wraps its metadata in a \"sui_image_params\" key.\n if (params?.includes('sui_image_params')) {\n // A1111 text may mention the key too; such text is returned below\n const obj = parseJson(params);\n if (obj)\n return buildA1111(\n extractCommon((obj.sui_image_params ?? obj) as JsonObject),\n );\n }\n\n // --- Plain text (A1111 / Forge / reForge) ----------------------------\n // Already in A1111 format — return as-is.\n if (params && !params.startsWith('{')) return params;\n\n // --- JSON parameters -------------------------------------------------\n if (params) {\n const obj = parseJson(params);\n if (obj) {\n // Try specific tool detectors (RuinedFooocus, EasyDiffusion,\n // Fooocus, HF Space, NovelAI).\n // NovelAI keeps the model in Source, outside the Comment JSON.\n if (entries.Source) obj.Source = entries.Source;\n const result = tryJsonTool(obj, params);\n if (result) return result;\n\n // ComfyUI (PNG): node graph stored directly in parameters.\n if (params.includes(CT)) return buildA1111(flatScan(params));\n\n // Generic JSON fallback: extract common fields.\n // Handles InvokeAI, Civitai, TensorArt, and other tools that\n // use standard field names (prompt, seed, steps, cfg, etc.).\n const base = extractCommon(obj);\n\n // TensorArt + ComfyUI hybrid: TensorArt stores generation\n // metadata in generation_data (→ params), but the ComfyUI\n // node graph is in a separate prompt field. Merge them:\n // flatScan provides seed/steps/cfg/sampler from ComfyUI nodes,\n // base provides prompt/negative/model/hash from TensorArt.\n if (prompt?.includes(CT))\n return buildA1111({\n ...flatScan(prompt),\n p: base.p,\n n: base.n,\n md: base.md,\n mh: base.mh,\n });\n\n return buildA1111(base);\n }\n }\n\n // --- EasyDiffusion (PNG, non-JSON parameters) ------------------------\n // EasyDiffusion stores fields as top-level PNG tEXt entries with a\n // distinctive \"use_stable_diffusion_model\" key. Its clip_skip is a boolean\n // written as \"False\"/\"True\", not an A1111 layer count, so the field is\n // dropped (the JSON form is `false` and already comes out blank).\n if (entries[EASY_DIFF_KEY])\n return buildA1111({ ...extractCommon(entries), cs: '' });\n\n // --- ComfyUI (PNG, no parameters field) ------------------------------\n // Some ComfyUI outputs only have a \"prompt\" PNG tEXt chunk\n // containing the node graph (no \"parameters\" chunk).\n if (prompt?.includes(CT)) return buildA1111(flatScan(prompt));\n\n // --- Final fallback --------------------------------------------------\n // Return whatever text is available, trying the most likely fields first.\n // C2PA Content Credentials (ChatGPT / Gemini / Grok) carry no generation\n // params, so their generator name is the fallback. It comes before the\n // EXIF text, which a vendor image only uses for its own markers (Grok\n // writes a signature there).\n return (\n params ??\n (readC2paName(entries.cabx) ||\n (entries.UserComment ??\n entries.Comment ??\n entries.ImageDescription ??\n ''))\n );\n}\n\n// ============================================================================\n// C2PA (Content Credentials)\n// ============================================================================\n\n/**\n * Recover `claim_generator_info.name` from a caBX manifest captured as a Latin-1\n * string (1:1 byte view, see readPng). Detection only — no JUMBF/CBOR decoder\n * and no signature verification.\n *\n * The `name` key is encoded as 0x64 ('d') + \"name\", i.e. the run \"dname\", so the\n * value's CBOR text-string header sits 5 bytes later. Generator names are short\n * ASCII, so only inline (0x60-0x77) and 1-byte (0x78) length headers are read.\n * charCodeAt yields NaN past the string end, which fails every comparison below,\n * so out-of-range offsets fall through to \"\".\n */\nfunction readC2paName(manifest: string | undefined): string {\n if (!manifest) return '';\n\n const cgi = manifest.indexOf('claim_generator_info');\n if (cgi < 0) return '';\n\n // Require the key within a short window of the marker so a stray \"...name\"\n // elsewhere cannot be misread as the generator name.\n const p = manifest.indexOf('dname', cgi);\n if (p < 0 || p > cgi + 256) return '';\n\n const pos = p + 5;\n const head = manifest.charCodeAt(pos);\n if (!(head >= 0x60 && head <= 0x78)) return '';\n\n const oneByte = head === 0x78;\n const length = oneByte ? manifest.charCodeAt(pos + 1) || 0 : head - 0x60;\n const dataPos = pos + (oneByte ? 2 : 1);\n if (dataPos + length > manifest.length) return '';\n\n return manifest.slice(dataPos, dataPos + length);\n}\n\n// ============================================================================\n// JSON Tool Detector\n// ============================================================================\n\n/**\n * Attempt to identify specific tools from a parsed JSON object.\n * Returns A1111-format text if a tool is recognized, null otherwise.\n *\n * Detection is ordered from most specific to least specific signatures.\n */\nfunction tryJsonTool(obj: JsonObject, text: string): string | null {\n // RuinedFooocus: identified by \"software\" field containing \"RuinedFooocus\".\n if (asText(obj.software).includes('RuinedFooocus'))\n return buildA1111(extractCommon(obj));\n\n // EasyDiffusion (JSON variant): identified by \"use_stable_diffusion_model\".\n if (EASY_DIFF_KEY in obj) return buildA1111(extractCommon(obj));\n\n // Fooocus: identified by having both \"Model\" (capital M) and \"resolution\"\n // keys. Resolution format: \"1024x1024\". Also has optional upscaler data.\n if (text.includes('\"Model\"') && text.includes('\"resolution\"')) {\n // The lookbehind starts a match at the first digit of a run only, so a\n // long run of digits without an \"x\" is tried once, not from every digit\n const [w, h] = parseDimensions(\n asText(obj.resolution),\n /(?<!\\d)(\\d+)\\s*x\\s*(\\d+)/,\n );\n return buildA1111({ ...extractCommon(obj), w, h });\n }\n\n // HF Space / Civitai generator / Fooocus JSON scheme: identified by\n // \"base_model\" key.\n // Resolution format: \"(1024, 1024)\" (Python tuple string).\n if ('base_model' in obj) {\n const [w, h] = parseDimensions(\n asText(obj.resolution),\n /\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/,\n );\n return buildA1111({ ...extractCommon(obj), w, h });\n }\n\n // NovelAI (PNG/WebP JSON): identified by \"noise_schedule\" key.\n // Has special v4 prompt format that needs dedicated handling.\n if ('noise_schedule' in obj) return buildNovelAI(obj);\n\n return null;\n}\n\n// ============================================================================\n// Common JSON Extractor\n// ============================================================================\n\n/**\n * Extract GenerationParams from a JSON object using field name fallback chains.\n *\n * Each field tries multiple property names to cover all known JSON-based tools.\n * The fallback order generally goes: most common name → tool-specific aliases.\n *\n * Covered tools: A1111, NovelAI, SwarmUI, InvokeAI, Civitai, TensorArt,\n * Fooocus, RuinedFooocus, EasyDiffusion, HF Space.\n */\nfunction extractCommon(obj: Record<string, unknown>): GenerationParams {\n const sa = asText(obj.sampler ?? obj.sampler_name);\n const sc = asText(obj.scheduler ?? obj.noise_schedule);\n const mod = obj.model as JsonObject | undefined;\n const base = obj.baseModel as JsonObject | undefined;\n const up = obj.use_upscaler as JsonObject | undefined;\n return {\n // Prompt: Fooocus \"full_prompt\" (style-resolved parts, joined with \", \"\n // like its own a1111 scheme) → \"prompt\" (most tools) → \"Prompt\" (Fooocus)\n // → \"positive_prompt\" (RuinedFooocus)\n p:\n (obj.full_prompt as string[] | undefined)?.join?.(', ') ||\n asText(obj.prompt ?? obj.Prompt ?? obj.positive_prompt),\n // Negative: multiple naming conventions across tools\n // \"uc\" = NovelAI's \"undesired content\"\n n:\n (obj.full_negative_prompt as string[] | undefined)?.join?.(', ') ||\n asText(\n obj.negative_prompt ??\n obj.Negative ??\n obj.negativeprompt ??\n obj.negativePrompt ??\n obj.uc,\n ),\n se: asText(obj.seed),\n // \"num_inference_steps\" = HF Space / Civitai generator\n st: asText(obj.steps ?? obj.num_inference_steps),\n // CFG: many naming variants across tools\n // \"scale\" = NovelAI, \"guidance_scale\" = HF Space\n cf: asText(\n obj.cfg ??\n obj.cfg_scale ??\n obj.cfgScale ??\n obj.cfgscale ??\n obj.guidance_scale ??\n obj.scale,\n ),\n // InvokeAI quirk: stores the sampler name in the \"scheduler\" field\n // and has no separate sampler field. If sa is empty, use sc as sa.\n sa: sa || sc,\n sc: sa ? sc : undefined,\n w: asText(obj.width),\n h: asText(obj.height),\n // Model name: extensive fallback chain covering all known patterns.\n // \"model\" (string) → InvokeAI, SwarmUI, Civitai\n // \"Model\" (capital) → Fooocus\n // \"base_model\" → HF Space\n // \"base_model_name\" → Civitai generator\n // \"baseModel\" (string) → TensorArt (when stored as string)\n // \"model.name\" → Civitai (nested object)\n // \"baseModel.modelFileName\" → TensorArt (nested object)\n // \"use_stable_diffusion_model\" → EasyDiffusion (full path, take filename)\n md:\n asText(mod) ||\n asText(obj.Model) ||\n asText(obj.base_model) ||\n asText(obj.base_model_name) ||\n asText(base) ||\n asText(mod?.name) ||\n asText(base?.modelFileName) ||\n asText(obj[EASY_DIFF_KEY]).split(/[\\\\/]/).pop(),\n // Model hash: similar multi-tool fallback chain.\n // \"Model hash\" → Fooocus\n // \"model.hash\" → Civitai (nested)\n // \"baseModel.hash\" → TensorArt (nested)\n mh:\n asText(obj.base_model_hash) ||\n asText(obj['Model hash']) ||\n asText(mod?.hash) ||\n asText(base?.hash),\n cs: asText(obj.clip_skip ?? obj.clipSkip),\n // Hires/upscaler: use_upscaler (Fooocus, HF Space) → refiner* (SwarmUI)\n hs: asText(up?.upscale_by) || asText(obj.refinerupscale),\n hu: asText(up?.upscale_method) || asText(obj.refinerupscalemethod),\n hd: asText(up?.upscaler_strength) || asText(obj.refinercontrolpercentage),\n ht: asText(up?.upscale_steps),\n };\n}\n\n// ============================================================================\n// Tool-Specific Builders\n// ============================================================================\n\n/**\n * Build A1111 text from NovelAI JSON metadata.\n *\n * NovelAI v4+ uses a nested prompt structure:\n * { v4_prompt: { caption: { base_caption: \"...\" } } }\n * Falls back to flat \"prompt\" / \"uc\" fields for older versions.\n */\nfunction buildNovelAI(obj: JsonObject): string {\n const v4Caption = (obj.v4_prompt as JsonObject)?.caption as\n | JsonObject\n | undefined;\n const v4NegCaption = (obj.v4_negative_prompt as JsonObject)?.caption as\n | JsonObject\n | undefined;\n // Source is \"<model name> <8-digit hex hash>\"\n const src = /^(.+) ([0-9A-F]{8})$/.exec(asText(obj.Source));\n return buildA1111({\n ...extractCommon(obj),\n // Prefer v4 captions, fall back to legacy flat fields. The V5 web\n // client appends quoted texts as \", teXt: ...\"; drop that block.\n p: (asText(v4Caption?.base_caption) || asText(obj.prompt)).replace(\n /(^|, )teXt:(?!:).*/s,\n '',\n ),\n n: asText(v4NegCaption?.base_caption) || asText(obj.uc),\n // img2img strength (Img2ImgRequest only)\n dn: asText(obj.strength),\n md: src?.[1] ?? asText(obj.Source),\n mh: src?.[2],\n });\n}\n\n// ============================================================================\n// ComfyUI Flat Scanner\n// ============================================================================\n\n/**\n * Scan a ComfyUI node graph (flat JSON) and extract generation parameters.\n *\n * ComfyUI stores metadata as a dictionary of nodes, each with a \"class_type\"\n * and \"inputs\" object. This function iterates all nodes and extracts\n * relevant parameters based on the node's class type.\n *\n * The \"first match wins\" strategy (??= / ||=) ensures we pick the primary\n * node when multiple nodes of the same type exist (e.g. two KSamplers).\n */\nfunction flatScan(json: string): GenerationParams {\n const result: GenerationParams = {};\n // User-prompt fallback: official enhancer templates (e.g. Krea-2 Turbo)\n // hold the user's input in a PrimitiveStringMultiline titled\n // \"... (User Prompt)\" while CLIPTextEncode only carries node references.\n // Collected during the scan, applied only when no text node yielded a\n // prompt literal.\n let up = '';\n // Pre-clean: strip trailing null bytes (PNG chunks; the lookbehind keeps\n // the trim linear, see channelKnownKeys) and replace NaN literals that\n // some ComfyUI versions emit (invalid JSON).\n const nodes = parseJson(\n json.replace(/(?<!\\0)\\0+$/, '').replace(/\\bNaN\\b/g, 'null'),\n );\n if (!nodes) return result;\n\n for (const key in nodes) {\n const node = nodes[key] as JsonObject;\n if (!node || typeof node !== 'object') continue;\n const classType = asText(node[CT]);\n const inputs = node.inputs as JsonObject | undefined;\n if (!inputs) continue;\n\n if (/User Prompt/.test(asText((node._meta as JsonObject)?.title)))\n up ||= asText(inputs.value);\n\n // --- Prompt text nodes -------------------------------------------\n // Matches CLIPTextEncode (and variants like SDXL, Flux) via \"TextEncode\",\n // text box nodes (DF_Text_Box, TextBox) via \".?Box\", ShowText|pysssss\n // (pythongosssss/ComfyUI-Custom-Scripts) which caches composed prompts in\n // inputs.text_0, and PromptStashSaver which holds user-authored prompts in\n // inputs.prompt_text.\n // Unified classification: if class name contains \"neg\" → negative prompt,\n // otherwise first-come-first-served (1st → positive, 2nd → negative).\n if (/Text(Encode|.?Box)|ShowText|PromptStash/.test(classType)) {\n const txt =\n asText(inputs.text) ||\n asText(inputs.prompt) ||\n asText(inputs.Text) ||\n asText(inputs.prompt_text) ||\n asText(inputs.text_0);\n if (txt) {\n if (/neg/i.test(classType)) {\n result.n ??= txt;\n } else {\n if (!result.p) result.p = txt;\n else if (!result.n) result.n = txt;\n }\n }\n }\n\n // --- Sampler nodes (KSampler, KSamplerAdvanced, etc.) ------------\n // Class-type guard is required here: \"steps\" and \"seed\" also appear\n // on non-sampler nodes (BasicScheduler, RandomNoise, etc.).\n if (classType.includes('Sampler')) {\n result.se ||= asText(inputs.seed) || asText(inputs.noise_seed);\n result.st ||= asText(inputs.steps);\n result.cf ||= asText(inputs.cfg);\n result.sa ||= asText(inputs.sampler_name);\n result.sc ||= asText(inputs.scheduler);\n }\n\n // --- Model loader nodes ------------------------------------------\n // ckpt_name / unet_name are unique to checkpoint and UNET loaders —\n // no class_type guard needed; unconditional ||= is safe here.\n result.md ||= asText(inputs.ckpt_name) || asText(inputs.unet_name);\n\n // --- Latent image nodes (for dimensions) -------------------------\n result.w ||= asText(inputs.width);\n result.h ||= asText(inputs.height);\n }\n result.p ||= up;\n return result;\n}\n\n// ============================================================================\n// A1111 Text Builder\n// ============================================================================\n\n/**\n * Build human-readable text in A1111 (Stable Diffusion WebUI) format.\n *\n * Output structure:\n * Line 1: positive prompt\n * Line 2: \"Negative prompt: <negative prompt>\"\n * Line 3: comma-separated key-value pairs (Steps, Sampler, CFG, etc.)\n */\nfunction buildA1111(params: GenerationParams): string {\n const lines: string[] = [];\n if (params.p) lines.push(params.p);\n if (params.n) lines.push(`Negative prompt: ${params.n}`);\n\n const fields: string[] = [];\n // addField only appends when value is non-empty (skips undefined and \"\").\n const addField = (key: string, value: string | undefined) => {\n if (value) fields.push(`${key}: ${value}`);\n };\n\n addField('Steps', params.st);\n addField('Sampler', params.sa);\n addField('Schedule type', params.sc);\n addField('CFG scale', params.cf);\n addField('Seed', params.se);\n if (params.w && params.h) addField('Size', `${params.w}x${params.h}`);\n addField('Model hash', params.mh);\n addField('Model', params.md);\n addField('Clip skip', params.cs);\n // Denoising strength: dn (standard) or hd (Fooocus refiner percentage).\n addField('Denoising strength', params.dn ?? params.hd);\n addField('Hires upscale', params.hs);\n addField('Hires steps', params.ht);\n addField('Hires upscaler', params.hu);\n\n if (fields.length) lines.push(fields.join(', '));\n return lines.join('\\n');\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Safely parse JSON, returning null on failure. */\nfunction parseJson(text: string | undefined): JsonObject | null {\n if (!text) return null;\n try {\n return JSON.parse(text) as JsonObject;\n } catch {\n return null;\n }\n}\n\n/**\n * Coerce a scalar to text. Strings pass through unchanged (a 64-bit seed\n * written as a string keeps every digit), numbers are stringified (one\n * written as a JSON number was already rounded past 2^53 by JSON.parse),\n * and anything else — missing, null, objects, ComfyUI node references like\n * [\"95\", 0] — becomes \"\".\n *\n * Every value ends up interpolated into A1111 text, so there is no reason to\n * hold numbers as numbers. Returning \"\" (falsy) enables `||` fallback chains:\n * `asText(a) || asText(b)`.\n */\nfunction asText(v: unknown): string {\n return typeof v === 'string' ? v : typeof v === 'number' ? String(v) : '';\n}\n\n/**\n * Convert a value to its string representation for channeling.\n * Strings pass through unchanged; objects are JSON-serialized.\n * Used by channelKnownKeys to convert nested JSON objects to strings\n * that extract() can later re-parse.\n */\nfunction stringifyValue(v: unknown): string {\n if (typeof v === 'string') return v;\n if (v && typeof v === 'object') return JSON.stringify(v);\n return '';\n}\n\n/**\n * Extract width/height from a dimension string using the given regex.\n * Different tools use different formats:\n * - Fooocus: \"1024x1024\" → /(\\d+)\\s*x\\s*(\\d+)/\n * - HF Space: \"(1024, 1024)\" → /\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/\n */\nfunction parseDimensions(\n text: string | undefined,\n pattern: RegExp,\n): [string?, string?] {\n if (!text) return [];\n const match = text.match(pattern);\n return match ? [match[1], match[2]] : [];\n}\n","/**\n * Lightweight binary readers for PNG, JPEG, and WebP metadata extraction.\n * Uses DataView API for endian-aware integer reading.\n */\n\n// Entry record: keyword → text value\nexport type Entries = Record<string, string>;\n\n// Maximum caBX (C2PA) bytes captured. The generator marker sits near the start\n// of the box, so clamping bounds memory against a maliciously oversized chunk.\nconst MAX_CABX = 8 * 1024 * 1024;\n\n// ============================================================================\n// PNG Reader\n// ============================================================================\n\n/**\n * Extract text chunks from PNG data as keyword→text entries.\n */\nexport function readPng(data: Uint8Array): Entries {\n const entries: Entries = {};\n const dv = dataview(data);\n let offset = 8; // Skip PNG signature\n\n while (offset + 8 <= data.length) {\n const length = dv.getUint32(offset);\n const type = str(data, offset + 4, 4);\n offset += 8;\n\n if (offset + length > data.length) break;\n\n // caBX: C2PA Content Credentials. Capture the manifest as a Latin-1 string\n // (1:1 byte view) so extract() can recover the generator name from it.\n if (type === 'caBX') {\n entries.cabx = str(data, offset, Math.min(length, MAX_CABX));\n }\n\n // eXIf: a TIFF structure like a JPEG APP1 payload (CivitAI PNGs)\n if (type === 'eXIf')\n Object.assign(entries, readExif(data.subarray(offset, offset + length)));\n\n if (type === 'tEXt' || type === 'iTXt') {\n const nullIdx = data.indexOf(0, offset);\n if (nullIdx > offset && nullIdx < offset + length) {\n const keyword = str(data, offset, nullIdx - offset);\n if (type === 'tEXt') {\n const textData = data.subarray(nullIdx + 1, offset + length);\n entries[keyword] =\n tryUtf8(textData) ??\n str(data, nullIdx + 1, offset + length - nullIdx - 1);\n } else {\n // Skip null + compression flag (1) + method (1), then two null-terminated strings\n const pos = nullIdx + 3;\n const langEnd = data.indexOf(0, pos);\n const transEnd = langEnd < 0 ? -1 : data.indexOf(0, langEnd + 1);\n if (langEnd < 0 || transEnd < 0) {\n offset += length + 4;\n continue;\n }\n entries[keyword] =\n tryUtf8(data.subarray(transEnd + 1, offset + length)) ?? '';\n }\n }\n }\n\n if (type === 'IEND') break;\n offset += length + 4; // Skip data + CRC\n }\n\n return entries;\n}\n\n// ============================================================================\n// JPEG Reader\n// ============================================================================\n\n/**\n * Extract metadata from JPEG: EXIF UserComment/ImageDescription/Make/Model,\n * COM segment, and APP11 (C2PA) as `cabx`.\n */\nexport function readJpeg(data: Uint8Array): Entries {\n const entries: Entries = {};\n let offset = 2; // Skip SOI\n\n while (offset + 4 <= data.length) {\n const marker = data[offset + 1]!;\n if (data[offset] !== 0xff || marker === 0xff) {\n offset++;\n continue;\n }\n\n // SOS (0xDA) or EOI (0xD9) — stop scanning\n if (marker > 0xd8 && marker < 0xdb) break;\n\n const segLen = (data[offset + 2]! << 8) | data[offset + 3]!;\n\n // APP1 (EXIF)\n if (\n marker === 0xe1 &&\n offset + 10 <= data.length &&\n str(data, offset + 4, 6) === 'Exif\\0\\0'\n ) {\n Object.assign(\n entries,\n readExif(data.subarray(offset + 10, offset + 2 + segLen)),\n );\n }\n\n // APP11 (JUMBF): C2PA Content Credentials, captured like the PNG caBX chunk.\n // The 8 bytes after the length are the \"JP\" identifier, box instance and\n // packet number; continuation packets are appended as they come.\n if (marker === 0xeb)\n entries.cabx = (entries.cabx ?? '') + str(data, offset + 12, segLen - 10);\n\n // COM segment\n if (marker === 0xfe) {\n const comData = data.subarray(offset + 4, offset + 2 + segLen);\n const text = tryUtf8(comData);\n if (text) entries.Comment = text;\n }\n\n offset += 2 + segLen;\n }\n\n return entries;\n}\n\n// ============================================================================\n// WebP Reader\n// ============================================================================\n\n/**\n * Extract metadata from WebP: EXIF chunk → same EXIF parsing as JPEG.\n */\nexport function readWebp(data: Uint8Array): Entries {\n const dv = dataview(data);\n let offset = 12; // Skip RIFF header\n\n while (offset + 8 <= data.length) {\n const type = str(data, offset, 4);\n const chunkSize = dv.getUint32(offset + 4, true); // little-endian\n offset += 8;\n\n if (type === 'EXIF' && offset + chunkSize <= data.length) {\n return readExif(data.subarray(offset, offset + chunkSize));\n }\n\n // RIFF chunks are padded to even byte boundaries\n offset += chunkSize + (chunkSize % 2);\n }\n\n return {};\n}\n\n// ============================================================================\n// EXIF / TIFF Parser\n// ============================================================================\n\n/**\n * Parse EXIF/TIFF data and extract metadata entries.\n */\nfunction readExif(data: Uint8Array): Entries {\n if (data.length < 8) return {};\n\n const firstByte = data[0];\n const le = firstByte === 0x49; // \"II\" = little-endian (both bytes are identical per TIFF spec)\n if (!le && firstByte !== 0x4d) return {}; // Not \"MM\" either\n\n const dv = dataview(data);\n if (dv.getUint16(2, le) !== 42) return {}; // TIFF magic\n\n const entries: Entries = {};\n const ifd0 = dv.getUint32(4, le);\n\n // Scan IFD0 for ImageDescription, Make, Model, UserComment, and Exif IFD pointer\n let exifIfdOffset = 0;\n const handleUserComment = (tagData: Uint8Array) => {\n const text = decodeUserComment(tagData);\n if (text) {\n if (text.startsWith('{')) {\n try {\n const obj = JSON.parse(text) as Record<string, unknown>;\n const software = obj.Software;\n const comment = obj.Comment;\n if (\n typeof software === 'string' &&\n software.startsWith('NovelAI') &&\n typeof comment === 'string'\n ) {\n entries.Software = software;\n entries.Comment = comment;\n // Model name and hash, as in the PNG Source chunk\n entries.Source = obj.Source as string;\n return;\n }\n } catch {\n // Not valid JSON — fall through to UserComment assignment.\n }\n }\n entries.UserComment = text;\n }\n };\n scanIfd(data, dv, ifd0, le, (tag, tagData) => {\n // ImageDescription (0x010E) through Model (0x0110). Tools label the value\n // with the PNG chunk keyword it stands in for, so the label decides the\n // entry key: save-image-extended writes ImageDescription \"Workflow: {...}\"\n // and Make \"Prompt: {...}\", while ComfyUI's built-in Save Animated WEBP\n // writes Make \"workflow:{...}\" and Model \"prompt:{...}\".\n if (tag > 0x010d && tag < 0x0111) {\n const text = decodeAscii(tagData);\n if (text) {\n // The space after the colon is optional, but a bare colon only counts\n // in front of JSON so values like \"http://...\" keep their text.\n const prefixMatch = text.match(/^([A-Za-z]+):(?:\\s|(?=\\{))/);\n if (prefixMatch) {\n const key = prefixMatch[1];\n if (key) entries[key] = text.slice(prefixMatch[0].length);\n } else {\n entries[\n tag === 0x010e\n ? 'ImageDescription'\n : tag === 0x010f\n ? 'Make'\n : 'Model'\n ] = text;\n }\n }\n } else if (tag === 0x9286) {\n // UserComment\n handleUserComment(tagData);\n } else if (tag === 0x8769) {\n // Exif IFD pointer\n exifIfdOffset = dv.getUint32(tagData.byteOffset - data.byteOffset, le);\n }\n });\n\n // Scan Exif IFD for UserComment (if not already found in IFD0)\n if (exifIfdOffset && !entries.UserComment && !entries.Software) {\n scanIfd(data, dv, exifIfdOffset, le, (tag, tagData) => {\n if (tag === 0x9286) handleUserComment(tagData); // UserComment\n });\n }\n\n return entries;\n}\n\n/**\n * Scan IFD entries and call handler for each tag.\n */\nfunction scanIfd(\n data: Uint8Array,\n dv: DataView,\n ifdOffset: number,\n le: boolean,\n handler: (tag: number, tagData: Uint8Array) => void,\n): void {\n const u16 = (o: number) => dv.getUint16(o, le);\n const u32 = (o: number) => dv.getUint32(o, le);\n if (ifdOffset + 2 > data.length) return;\n const count = u16(ifdOffset);\n let pos = ifdOffset + 2;\n\n for (let i = 0; i < count; i++) {\n if (pos + 12 > data.length) return;\n const tag = u16(pos);\n const type = u16(pos + 2);\n const valueCount = u32(pos + 4);\n const typeSize = [0, 1, 1, 2, 4, 8, 0, 1][type] ?? 1;\n const size = valueCount * typeSize;\n const valOffset = size <= 4 ? pos + 8 : u32(pos + 8);\n\n if (valOffset + size <= data.length) {\n handler(tag, data.subarray(valOffset, valOffset + size));\n }\n pos += 12;\n }\n}\n\n// ============================================================================\n// String Decoders\n// ============================================================================\n\n// Shared DataView constructor — the 48-character expression appears 3x\n// (readPng, readWebp, readExif). A helper saves ~61 bytes minified.\nfunction dataview(data: Uint8Array): DataView {\n return new DataView(data.buffer, data.byteOffset, data.byteLength);\n}\n\nconst utf8Dec = new TextDecoder('utf-8', { fatal: true });\n\n// Alias for String.fromCharCode — used in str and decodeUtf16.\n// Saves ~38 bytes in the minified IIFE.\nconst fromCharCode = String.fromCharCode;\n\nfunction str(data: Uint8Array, offset: number, len: number): string {\n let s = '';\n for (let i = 0; i < len; i++) s += fromCharCode(data[offset + i]!);\n return s;\n}\n\nfunction tryUtf8(data: Uint8Array): string | null {\n try {\n return utf8Dec.decode(data).replace(/\\0$/, '');\n } catch {\n return null;\n }\n}\n\nfunction decodeAscii(data: Uint8Array): string | null {\n const nullIdx = data.indexOf(0);\n return str(data, 0, nullIdx < 0 ? data.length : nullIdx).trim() || null;\n}\n\n/**\n * Decode UserComment with encoding prefix detection.\n */\nfunction decodeUserComment(data: Uint8Array): string | null {\n if (data.length < 8) return null;\n\n const prefix = str(data, 0, 8);\n const payload = data.subarray(8);\n\n if (prefix === 'UNICODE\\0') {\n if (payload.length < 2) return null;\n const isLE = payload[0] !== 0 && payload[1] === 0;\n return decodeUtf16(payload, isLE);\n }\n\n if (prefix === 'ASCII\\0\\0\\0') {\n return decodeAscii(payload);\n }\n\n // Try raw UTF-8\n return tryUtf8(data);\n}\n\nfunction decodeUtf16(data: Uint8Array, le: boolean): string {\n let s = '';\n for (let i = 0; i + 1 < data.length; i += 2) {\n const code = le\n ? data[i]! | (data[i + 1]! << 8)\n : (data[i]! << 8) | data[i + 1]!;\n if (!code) break;\n s += fromCharCode(code);\n }\n return s;\n}\n","/**\n * @enslo/sd-metadata-lite\n *\n * Lightweight AI image metadata reader for bookmarklets.\n * Reads PNG/JPEG/WebP files and returns A1111-format plain text.\n */\n\nimport { extract } from './extract';\nimport { readJpeg, readPng, readWebp } from './read';\n\n/**\n * Parse AI-generated image metadata and return A1111-format text.\n *\n * Supports PNG, JPEG, and WebP formats across 18+ generation tools. For PNG\n * images with no generation parameters, falls back to C2PA Content Credentials\n * and returns the generator name (e.g. ChatGPT / Gemini exports).\n * Returns empty string if no metadata is found.\n *\n * @param input - Image file data\n * @returns A1111-format metadata text, the C2PA generator name, or empty string\n */\nexport function parse(input: Uint8Array | ArrayBuffer): string {\n const data = input instanceof ArrayBuffer ? new Uint8Array(input) : input;\n\n // Format detection is intentionally loose (first 2 bytes only) to\n // minimize bundle size. False positives are harmless: the reader\n // will find no metadata and extract() returns \"\".\n\n // PNG: 89 50 (full signature: 89 50 4E 47 0D 0A 1A 0A)\n if (data[0] === 0x89 && data[1] === 0x50) {\n return extract(readPng(data));\n }\n\n // JPEG: FF D8\n if (data[0] === 0xff && data[1] === 0xd8) {\n return extract(readJpeg(data));\n }\n\n // WebP: 52 49 (full signature: RIFF....WEBP)\n if (data[0] === 0x52 && data[1] === 0x49) {\n return extract(readWebp(data));\n }\n\n return '';\n}\n"],"mappings":";AA0EA,MAAM,KAAK;AAKX,MAAM,SAAS;AAKf,MAAM,gBAAgB;;;;;;;;;;;;;;;;AAqBtB,SAAS,iBACP,KACA,SACS;CACT,KAAK,MAAM,OAAO;EAAC;EAAiB;EAAqB;CAAiB,GACxE,IAAI,IAAI,MAAM;EACZ,MAAM,SAAkB;GACtB,GAAG;IAIF,SACC,QAAQ,WACR,eAAe,IAAI,IAAI,CAAC,CAAC,QAAQ,eAAe,EAAE;EACtD;EAGA,IAAI,IAAI,QAAQ,OAAO,WAAW,eAAe,IAAI,MAAM;EAC3D,OAAO;CACT;CAEF,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAS,UAAU,SAA2B;CAG5C,IAAI,QAAQ,UAAU,WAAW,SAAS,GACxC,OAAO;EAAE,GAAG;GAAU,SAAS,QAAQ,WAAW,QAAQ;CAAS;CAGrE,MAAM,KAAK,QAAQ;CAKnB,IAAI,CAAC,IAAI,OAAO,iBAAiB,SAAS,OAAO;CAGjD,IAAI,CAAC,GAAG,WAAW,GAAG,GAAG;EAGvB,IAAI,GAAG,SAAS,QAAQ,GACtB,OAAO;GAAE,GAAG;IAAU,SAAS,QAAQ,WAAW;EAAG;EAEvD,OAAO;CACT;CAGA,MAAM,MAAM,UAAU,EAAE;CACxB,IAAI,CAAC,KAAK,OAAO;CAIjB,MAAM,YAAY,iBAAiB,KAAK,OAAO;CAC/C,IAAI,cAAc,SAAS,OAAO;CAIlC,IAAI,YAAY,OAAO,cAAc,KAC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