@enslo/sd-metadata-lite 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.ja.md +24 -8
- package/README.md +24 -8
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.js +60 -52
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,57 @@ 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.0] - 2026-11-04
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **C2PA generator names from JPEG** (#304): the Content Credentials claim
|
|
13
|
+
generator name is read from JPEG APP11 segments as it already was from
|
|
14
|
+
the PNG `caBX` chunk, so Gemini and Grok Imagine JPEGs return a name
|
|
15
|
+
(`Google C2PA Core Generator Library`, `Grok Imagine`) instead of nothing
|
|
16
|
+
or xAI's signature text. A C2PA name now takes precedence over the EXIF
|
|
17
|
+
text fields.
|
|
18
|
+
- **PNG `eXIf` chunk** (#288): EXIF stored in a PNG `eXIf` chunk (CivitAI
|
|
19
|
+
downloads) is read like JPEG EXIF, so those PNGs no longer return an empty
|
|
20
|
+
string.
|
|
21
|
+
- **NovelAI Diffusion V5** (#309): the auto text block the web client
|
|
22
|
+
appends (`, teXt: …`) is removed from the prompt, img2img strength is
|
|
23
|
+
written as `Denoising strength`, and `Source` fills `Model` and
|
|
24
|
+
`Model hash` for every NovelAI version.
|
|
25
|
+
- **Fooocus JSON scheme** (#284): prompts come from `full_prompt` /
|
|
26
|
+
`full_negative_prompt`, the lists Fooocus writes after expanding its
|
|
27
|
+
styles. Both Fooocus metadata schemes are now verified with real samples.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- **64-bit seeds were rounded** (#282, #283): seeds are passed through as
|
|
32
|
+
text, so values beyond `Number.MAX_SAFE_INTEGER` (Fooocus, some ComfyUI
|
|
33
|
+
graphs) keep every digit.
|
|
34
|
+
- **Easy Diffusion `clip_skip`** (#285): the boolean Easy Diffusion writes
|
|
35
|
+
(`False` / `True`) is no longer printed as a `Clip skip` value. Easy
|
|
36
|
+
Diffusion is now verified with real samples.
|
|
37
|
+
|
|
38
|
+
### Maintenance
|
|
39
|
+
|
|
40
|
+
- IIFE bundle size: 7,003 → 7,259 bytes (+256 bytes uncompressed; #282,
|
|
41
|
+
#283, #284, #285, #288, #304, #309)
|
|
42
|
+
- Update development dependencies (#280)
|
|
43
|
+
|
|
44
|
+
## [1.5.0] - 2026-08-17
|
|
45
|
+
|
|
46
|
+
### Improved
|
|
47
|
+
|
|
48
|
+
- **ComfyUI user-prompt extraction** (#261): The flat scanner now falls back
|
|
49
|
+
to `"... (User Prompt)"`-titled primitive nodes when no text node yields a
|
|
50
|
+
prompt literal, recovering the user's input from official enhancer
|
|
51
|
+
templates (e.g. Krea-2 Turbo) whose `CLIPTextEncode` nodes only carry node
|
|
52
|
+
references.
|
|
53
|
+
|
|
54
|
+
### Maintenance
|
|
55
|
+
|
|
56
|
+
- IIFE bundle size: 6,934 → 7,003 bytes (+69 bytes uncompressed; #261)
|
|
57
|
+
- Update development dependencies (#260)
|
|
58
|
+
|
|
8
59
|
## [1.4.0] - 2026-07-18
|
|
9
60
|
|
|
10
61
|
### Added
|
package/README.ja.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
AI生成画像のメタデータを読み取る軽量パーサーです。
|
|
11
11
|
バンドルサイズが重要なブックマークレットやユーザースクリプト向けに設計されています。
|
|
12
12
|
|
|
13
|
-
- **超軽量**: **
|
|
13
|
+
- **超軽量**: **7,259 bytes** のminified IIFEビルド
|
|
14
14
|
- **読み取り専用**: メタデータを抽出し、A1111形式のテキストで返却
|
|
15
15
|
- **ゼロ依存**: Node.jsとブラウザの両方で動作
|
|
16
16
|
- **18以上のツール対応**: 主要なAI画像生成ツールをサポート
|
|
@@ -18,6 +18,21 @@ AI生成画像のメタデータを読み取る軽量パーサーです。
|
|
|
18
18
|
> [!TIP]
|
|
19
19
|
> 書き込み、フォーマット変換、構造化メタデータが必要な場合は[フルライブラリ](../core/README.ja.md)をご利用ください。
|
|
20
20
|
|
|
21
|
+
## フルライブラリとの比較
|
|
22
|
+
|
|
23
|
+
| 機能 | `@enslo/sd-metadata` | `@enslo/sd-metadata-lite` |
|
|
24
|
+
| ---- | :------------------: | :-----------------------: |
|
|
25
|
+
| メタデータ読み取り | ✅ | ✅(A1111形式テキストのみ) |
|
|
26
|
+
| 画像へのメタデータ書き戻し | ✅ | - |
|
|
27
|
+
| カスタム(ユーザー作成)メタデータの埋め込み | ✅ | - |
|
|
28
|
+
| フォーマット変換(PNG/JPEG/WebP) | ✅ | - |
|
|
29
|
+
| ツール検知 | ✅ | - |
|
|
30
|
+
| 構造化メタデータオブジェクト | ✅ | - |
|
|
31
|
+
| IIFEビルド(ユーザースクリプト `@require`) | ✅ | ✅ |
|
|
32
|
+
| Node.js + ブラウザ | ✅ | ✅ |
|
|
33
|
+
|
|
34
|
+
バンドルサイズを最小に抑えたく、A1111形式のテキストだけで足りるなら lite を、それ以外は[フルライブラリ](../core/README.ja.md)をご利用ください。
|
|
35
|
+
|
|
21
36
|
## インストール
|
|
22
37
|
|
|
23
38
|
```bash
|
|
@@ -51,7 +66,7 @@ if (text) {
|
|
|
51
66
|
// ==UserScript==
|
|
52
67
|
// @name My Script
|
|
53
68
|
// @namespace https://example.com
|
|
54
|
-
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.
|
|
69
|
+
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.0/dist/index.global.js
|
|
55
70
|
// ==/UserScript==
|
|
56
71
|
|
|
57
72
|
const response = await fetch(imageUrl);
|
|
@@ -70,7 +85,7 @@ if (text) {
|
|
|
70
85
|
|
|
71
86
|
多くのサイトではCSPにより外部スクリプトの読み込みがブロックされます。代わりに、IIFEバンドルをインラインで貼り付けてください:
|
|
72
87
|
|
|
73
|
-
1. `dist/index.global.js` の内容をコピー(または[npm](https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.
|
|
88
|
+
1. `dist/index.global.js` の内容をコピー(または[npm](https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.0/dist/index.global.js)からダウンロード)
|
|
74
89
|
2. コードをインラインでブックマークレットに組み込みます:
|
|
75
90
|
|
|
76
91
|
```javascript
|
|
@@ -92,7 +107,7 @@ IIFEは `var sdml` に代入するため、インラインコードの直後か
|
|
|
92
107
|
**戻り値:**
|
|
93
108
|
|
|
94
109
|
- メタデータが見つかった場合はA1111形式のテキスト
|
|
95
|
-
- 生成パラメータを持たないPNGでは、C2PA Content Credentialsの生成元名(例: `OpenAI Media Service API`、`Google C2PA Core Generator Library`)があればそれを返却
|
|
110
|
+
- 生成パラメータを持たないPNG・JPEGでは、C2PA Content Credentialsの生成元名(例: `OpenAI Media Service API`、`Google C2PA Core Generator Library`、`Grok Imagine`)があればそれを返却
|
|
96
111
|
- メタデータが見つからない、またはフォーマットが認識できない場合は空文字列(`""`)
|
|
97
112
|
|
|
98
113
|
### 出力フォーマット
|
|
@@ -120,22 +135,23 @@ PNG、JPEG、WebPのメタデータを読み取り可能:
|
|
|
120
135
|
- [InvokeAI](https://github.com/invoke-ai/InvokeAI)
|
|
121
136
|
- [SwarmUI](https://github.com/mcmonkeyprojects/SwarmUI)
|
|
122
137
|
- [Stability Matrix](https://github.com/LykosAI/StabilityMatrix)
|
|
123
|
-
- [Civitai](https://civitai.com/)(
|
|
138
|
+
- [Civitai](https://civitai.com/)(WebPは実験的 *)
|
|
124
139
|
- [TensorArt](https://tensor.art/)
|
|
125
140
|
- [HuggingFace Space](https://huggingface.co/spaces)
|
|
126
141
|
- [Ruined Fooocus](https://github.com/runew0lf/RuinedFooocus)
|
|
127
|
-
- [Fooocus](https://github.com/lllyasviel/Fooocus)
|
|
128
|
-
- [Easy Diffusion](https://github.com/easydiffusion/easydiffusion)
|
|
142
|
+
- [Fooocus](https://github.com/lllyasviel/Fooocus)
|
|
143
|
+
- [Easy Diffusion](https://github.com/easydiffusion/easydiffusion)
|
|
129
144
|
|
|
130
145
|
> [!NOTE]
|
|
131
146
|
> \* リファレンスコードの解析に基づく実装であり、実際のサンプルファイルでは未検証です。
|
|
132
147
|
|
|
133
148
|
### Content Credentials (C2PA)
|
|
134
149
|
|
|
135
|
-
[C2PA](https://c2pa.org/) Content Credentialsで署名された商用ツールのPNGは、生成パラメータの代わりに生成元名で判別します:
|
|
150
|
+
[C2PA](https://c2pa.org/) Content Credentialsで署名された商用ツールのPNGとJPEGは、生成パラメータの代わりに生成元名で判別します:
|
|
136
151
|
|
|
137
152
|
- OpenAI ChatGPT
|
|
138
153
|
- Google Gemini
|
|
154
|
+
- xAI Grok Imagine
|
|
139
155
|
|
|
140
156
|
これらの画像では `parse()` が生成元名(例: `OpenAI Media Service API`)を返します。判別はベストエフォートです。Content Credentialsは再保存や再アップロードで簡単に失われ、また存在する場合も署名検証は行いません。
|
|
141
157
|
|
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**: **
|
|
13
|
+
- **Tiny**: **7,259 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
|
|
@@ -18,6 +18,21 @@ Designed for bookmarklets and userscripts where bundle size matters.
|
|
|
18
18
|
> [!TIP]
|
|
19
19
|
> Need write support, format conversion, or structured metadata? Use the [full library](../core/README.md) instead.
|
|
20
20
|
|
|
21
|
+
## Compared with the Full Library
|
|
22
|
+
|
|
23
|
+
| Feature | `@enslo/sd-metadata` | `@enslo/sd-metadata-lite` |
|
|
24
|
+
| ------- | :------------------: | :-----------------------: |
|
|
25
|
+
| Read metadata | ✅ | ✅ (A1111-format text only) |
|
|
26
|
+
| Write metadata back to an image | ✅ | - |
|
|
27
|
+
| Embed custom (user-authored) metadata | ✅ | - |
|
|
28
|
+
| Format conversion (PNG/JPEG/WebP) | ✅ | - |
|
|
29
|
+
| Tool detection | ✅ | - |
|
|
30
|
+
| Structured metadata object | ✅ | - |
|
|
31
|
+
| IIFE build (userscript `@require`) | ✅ | ✅ |
|
|
32
|
+
| Node.js + Browser | ✅ | ✅ |
|
|
33
|
+
|
|
34
|
+
Pick lite when the bundle has to stay tiny and A1111-format text is all you need; pick the [full library](../core/README.md) for everything else.
|
|
35
|
+
|
|
21
36
|
## Installation
|
|
22
37
|
|
|
23
38
|
```bash
|
|
@@ -51,7 +66,7 @@ Load the IIFE build via `@require`:
|
|
|
51
66
|
// ==UserScript==
|
|
52
67
|
// @name My Script
|
|
53
68
|
// @namespace https://example.com
|
|
54
|
-
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.
|
|
69
|
+
// @require https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.6.0/dist/index.global.js
|
|
55
70
|
// ==/UserScript==
|
|
56
71
|
|
|
57
72
|
const response = await fetch(imageUrl);
|
|
@@ -70,7 +85,7 @@ if (text) {
|
|
|
70
85
|
|
|
71
86
|
Most sites block external script loading via CSP. Instead, paste the IIFE bundle inline:
|
|
72
87
|
|
|
73
|
-
1. Copy the contents of `dist/index.global.js` (or download from [npm](https://cdn.jsdelivr.net/npm/@enslo/sd-metadata-lite@1.
|
|
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.0/dist/index.global.js))
|
|
74
89
|
2. Build your bookmarklet with the code inlined:
|
|
75
90
|
|
|
76
91
|
```javascript
|
|
@@ -92,7 +107,7 @@ Parses metadata from an image and returns A1111-format text.
|
|
|
92
107
|
**Returns:**
|
|
93
108
|
|
|
94
109
|
- A1111-format metadata string if metadata is found
|
|
95
|
-
- For
|
|
110
|
+
- For PNG and JPEG files with no generation parameters, the C2PA Content Credentials generator name (e.g. `OpenAI Media Service API`, `Google C2PA Core Generator Library`, `Grok Imagine`) when present
|
|
96
111
|
- Empty string (`""`) if no metadata is found or the format is unrecognized
|
|
97
112
|
|
|
98
113
|
### Output Format
|
|
@@ -120,22 +135,23 @@ Reads PNG, JPEG, and WebP metadata from:
|
|
|
120
135
|
- [InvokeAI](https://github.com/invoke-ai/InvokeAI)
|
|
121
136
|
- [SwarmUI](https://github.com/mcmonkeyprojects/SwarmUI)
|
|
122
137
|
- [Stability Matrix](https://github.com/LykosAI/StabilityMatrix)
|
|
123
|
-
- [Civitai](https://civitai.com/) (
|
|
138
|
+
- [Civitai](https://civitai.com/) (WebP is experimental *)
|
|
124
139
|
- [TensorArt](https://tensor.art/)
|
|
125
140
|
- [HuggingFace Space](https://huggingface.co/spaces)
|
|
126
141
|
- [Ruined Fooocus](https://github.com/runew0lf/RuinedFooocus)
|
|
127
|
-
- [Fooocus](https://github.com/lllyasviel/Fooocus)
|
|
128
|
-
- [Easy Diffusion](https://github.com/easydiffusion/easydiffusion)
|
|
142
|
+
- [Fooocus](https://github.com/lllyasviel/Fooocus)
|
|
143
|
+
- [Easy Diffusion](https://github.com/easydiffusion/easydiffusion)
|
|
129
144
|
|
|
130
145
|
> [!NOTE]
|
|
131
146
|
> \* Implemented based on reference code analysis, not verified with actual sample files.
|
|
132
147
|
|
|
133
148
|
### Content Credentials (C2PA)
|
|
134
149
|
|
|
135
|
-
|
|
150
|
+
PNG and JPEG files from commercial tools that sign their output with [C2PA](https://c2pa.org/) Content Credentials are detected by their generator name instead of generation parameters:
|
|
136
151
|
|
|
137
152
|
- OpenAI ChatGPT
|
|
138
153
|
- Google Gemini
|
|
154
|
+
- xAI Grok Imagine
|
|
139
155
|
|
|
140
156
|
For these images `parse()` returns the generator name (e.g. `OpenAI Media Service API`). Detection is best-effort: the credentials are easily stripped by re-saving or re-uploading, and a present manifest is not cryptographically verified.
|
|
141
157
|
|
package/dist/index.d.ts
CHANGED
|
@@ -16,7 +16,6 @@
|
|
|
16
16
|
* @param input - Image file data
|
|
17
17
|
* @returns A1111-format metadata text, the C2PA generator name, or empty string
|
|
18
18
|
*/
|
|
19
|
-
declare function parse(input: Uint8Array | ArrayBuffer): string;
|
|
19
|
+
export declare function parse(input: Uint8Array | ArrayBuffer): string;
|
|
20
20
|
//#endregion
|
|
21
|
-
export { parse };
|
|
22
21
|
//# 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",
|
|
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+$/,"")};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);return u(l(e.sui_image_params??e))}if(m&&!m.startsWith("{"))return m;if(m){let t=o(m),n="string"==typeof t?o(t):t;if(n){p.Source&&(n.Source=p.Source);let t=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+)\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}(n,m);if(t)return t;if(m.includes(e))return u(s(m));let i=l(n);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+$/,"").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
|
@@ -92,6 +92,7 @@ function extract(rawEntries) {
|
|
|
92
92
|
const raw = parseJson(params);
|
|
93
93
|
const obj = typeof raw === "string" ? parseJson(raw) : raw;
|
|
94
94
|
if (obj) {
|
|
95
|
+
if (entries.Source) obj.Source = entries.Source;
|
|
95
96
|
const result = tryJsonTool(obj, params);
|
|
96
97
|
if (result) return result;
|
|
97
98
|
if (params.includes(CT)) return buildA1111(flatScan(params));
|
|
@@ -106,9 +107,12 @@ function extract(rawEntries) {
|
|
|
106
107
|
return buildA1111(base);
|
|
107
108
|
}
|
|
108
109
|
}
|
|
109
|
-
if (entries[EASY_DIFF_KEY]) return buildA1111(
|
|
110
|
+
if (entries[EASY_DIFF_KEY]) return buildA1111({
|
|
111
|
+
...extractCommon(entries),
|
|
112
|
+
cs: ""
|
|
113
|
+
});
|
|
110
114
|
if (prompt?.includes(CT)) return buildA1111(flatScan(prompt));
|
|
111
|
-
return params ?? entries.UserComment ?? entries.Comment ?? entries.ImageDescription ??
|
|
115
|
+
return params ?? (readC2paName(entries.cabx) || (entries.UserComment ?? entries.Comment ?? entries.ImageDescription ?? ""));
|
|
112
116
|
}
|
|
113
117
|
/**
|
|
114
118
|
* Recover `claim_generator_info.name` from a caBX manifest captured as a Latin-1
|
|
@@ -143,10 +147,10 @@ function readC2paName(manifest) {
|
|
|
143
147
|
* Detection is ordered from most specific to least specific signatures.
|
|
144
148
|
*/
|
|
145
149
|
function tryJsonTool(obj, text) {
|
|
146
|
-
if (
|
|
150
|
+
if (asText(obj.software).includes("RuinedFooocus")) return buildA1111(extractCommon(obj));
|
|
147
151
|
if (EASY_DIFF_KEY in obj) return buildA1111(extractCommon(obj));
|
|
148
152
|
if (text.includes("\"Model\"") && text.includes("\"resolution\"")) {
|
|
149
|
-
const [w, h] = parseDimensions(
|
|
153
|
+
const [w, h] = parseDimensions(asText(obj.resolution), /(\d+)\s*x\s*(\d+)/);
|
|
150
154
|
return buildA1111({
|
|
151
155
|
...extractCommon(obj),
|
|
152
156
|
w,
|
|
@@ -154,7 +158,7 @@ function tryJsonTool(obj, text) {
|
|
|
154
158
|
});
|
|
155
159
|
}
|
|
156
160
|
if ("base_model" in obj) {
|
|
157
|
-
const [w, h] = parseDimensions(
|
|
161
|
+
const [w, h] = parseDimensions(asText(obj.resolution), /\(\s*(\d+)\s*,\s*(\d+)\s*\)/);
|
|
158
162
|
return buildA1111({
|
|
159
163
|
...extractCommon(obj),
|
|
160
164
|
w,
|
|
@@ -174,28 +178,28 @@ function tryJsonTool(obj, text) {
|
|
|
174
178
|
* Fooocus, RuinedFooocus, EasyDiffusion, HF Space.
|
|
175
179
|
*/
|
|
176
180
|
function extractCommon(obj) {
|
|
177
|
-
const sa =
|
|
178
|
-
const sc =
|
|
181
|
+
const sa = asText(obj.sampler ?? obj.sampler_name);
|
|
182
|
+
const sc = asText(obj.scheduler ?? obj.noise_schedule);
|
|
179
183
|
const mod = obj.model;
|
|
180
184
|
const base = obj.baseModel;
|
|
181
185
|
const up = obj.use_upscaler;
|
|
182
186
|
return {
|
|
183
|
-
p:
|
|
184
|
-
n:
|
|
185
|
-
se:
|
|
186
|
-
st:
|
|
187
|
-
cf:
|
|
187
|
+
p: obj.full_prompt?.join?.(", ") || asText(obj.prompt ?? obj.Prompt ?? obj.positive_prompt),
|
|
188
|
+
n: obj.full_negative_prompt?.join?.(", ") || asText(obj.negative_prompt ?? obj.Negative ?? obj.negativeprompt ?? obj.negativePrompt ?? obj.uc),
|
|
189
|
+
se: asText(obj.seed),
|
|
190
|
+
st: asText(obj.steps ?? obj.num_inference_steps),
|
|
191
|
+
cf: asText(obj.cfg ?? obj.cfg_scale ?? obj.cfgScale ?? obj.cfgscale ?? obj.guidance_scale ?? obj.scale),
|
|
188
192
|
sa: sa || sc,
|
|
189
193
|
sc: sa ? sc : void 0,
|
|
190
|
-
w:
|
|
191
|
-
h:
|
|
192
|
-
md:
|
|
193
|
-
mh:
|
|
194
|
-
cs:
|
|
195
|
-
hs:
|
|
196
|
-
hu:
|
|
197
|
-
hd:
|
|
198
|
-
ht:
|
|
194
|
+
w: asText(obj.width),
|
|
195
|
+
h: asText(obj.height),
|
|
196
|
+
md: asText(mod) || asText(obj.Model) || asText(obj.base_model) || asText(obj.base_model_name) || asText(base) || asText(mod?.name) || asText(base?.modelFileName) || asText(obj[EASY_DIFF_KEY]).split(/[\\/]/).pop(),
|
|
197
|
+
mh: asText(obj.base_model_hash) || asText(obj["Model hash"]) || asText(mod?.hash) || asText(base?.hash),
|
|
198
|
+
cs: asText(obj.clip_skip ?? obj.clipSkip),
|
|
199
|
+
hs: asText(up?.upscale_by) || asText(obj.refinerupscale),
|
|
200
|
+
hu: asText(up?.upscale_method) || asText(obj.refinerupscalemethod),
|
|
201
|
+
hd: asText(up?.upscaler_strength) || asText(obj.refinercontrolpercentage),
|
|
202
|
+
ht: asText(up?.upscale_steps)
|
|
199
203
|
};
|
|
200
204
|
}
|
|
201
205
|
/**
|
|
@@ -208,10 +212,14 @@ function extractCommon(obj) {
|
|
|
208
212
|
function buildNovelAI(obj) {
|
|
209
213
|
const v4Caption = obj.v4_prompt?.caption;
|
|
210
214
|
const v4NegCaption = obj.v4_negative_prompt?.caption;
|
|
215
|
+
const src = /^(.+) ([0-9A-F]{8})$/.exec(asText(obj.Source));
|
|
211
216
|
return buildA1111({
|
|
212
217
|
...extractCommon(obj),
|
|
213
|
-
p:
|
|
214
|
-
n:
|
|
218
|
+
p: (asText(v4Caption?.base_caption) || asText(obj.prompt)).replace(/(^|, )teXt:(?!:).*/s, ""),
|
|
219
|
+
n: asText(v4NegCaption?.base_caption) || asText(obj.uc),
|
|
220
|
+
dn: asText(obj.strength),
|
|
221
|
+
md: src?.[1] ?? asText(obj.Source),
|
|
222
|
+
mh: src?.[2]
|
|
215
223
|
});
|
|
216
224
|
}
|
|
217
225
|
/**
|
|
@@ -226,16 +234,18 @@ function buildNovelAI(obj) {
|
|
|
226
234
|
*/
|
|
227
235
|
function flatScan(json) {
|
|
228
236
|
const result = {};
|
|
237
|
+
let up = "";
|
|
229
238
|
const nodes = parseJson(json.replace(/\0+$/, "").replace(/\bNaN\b/g, "null"));
|
|
230
239
|
if (!nodes) return result;
|
|
231
240
|
for (const key in nodes) {
|
|
232
241
|
const node = nodes[key];
|
|
233
242
|
if (!node || typeof node !== "object") continue;
|
|
234
|
-
const classType =
|
|
243
|
+
const classType = asText(node[CT]);
|
|
235
244
|
const inputs = node.inputs;
|
|
236
245
|
if (!inputs) continue;
|
|
246
|
+
if (/User Prompt/.test(asText(node._meta?.title))) up ||= asText(inputs.value);
|
|
237
247
|
if (/Text(Encode|.?Box)|ShowText|PromptStash/.test(classType)) {
|
|
238
|
-
const txt =
|
|
248
|
+
const txt = asText(inputs.text) || asText(inputs.prompt) || asText(inputs.Text) || asText(inputs.prompt_text) || asText(inputs.text_0);
|
|
239
249
|
if (txt) {
|
|
240
250
|
if (/neg/i.test(classType)) result.n ??= txt;
|
|
241
251
|
else if (!result.p) result.p = txt;
|
|
@@ -243,16 +253,17 @@ function flatScan(json) {
|
|
|
243
253
|
}
|
|
244
254
|
}
|
|
245
255
|
if (classType.includes("Sampler")) {
|
|
246
|
-
result.se
|
|
247
|
-
result.st
|
|
248
|
-
result.cf
|
|
249
|
-
result.sa ||=
|
|
250
|
-
result.sc ||=
|
|
256
|
+
result.se ||= asText(inputs.seed) || asText(inputs.noise_seed);
|
|
257
|
+
result.st ||= asText(inputs.steps);
|
|
258
|
+
result.cf ||= asText(inputs.cfg);
|
|
259
|
+
result.sa ||= asText(inputs.sampler_name);
|
|
260
|
+
result.sc ||= asText(inputs.scheduler);
|
|
251
261
|
}
|
|
252
|
-
result.md ||=
|
|
253
|
-
result.w
|
|
254
|
-
result.h
|
|
262
|
+
result.md ||= asText(inputs.ckpt_name) || asText(inputs.unet_name);
|
|
263
|
+
result.w ||= asText(inputs.width);
|
|
264
|
+
result.h ||= asText(inputs.height);
|
|
255
265
|
}
|
|
266
|
+
result.p ||= up;
|
|
256
267
|
return result;
|
|
257
268
|
}
|
|
258
269
|
/**
|
|
@@ -297,11 +308,16 @@ function parseJson(text) {
|
|
|
297
308
|
}
|
|
298
309
|
}
|
|
299
310
|
/**
|
|
300
|
-
* Coerce
|
|
301
|
-
*
|
|
311
|
+
* Coerce a scalar to text. Strings pass through unchanged (so 64-bit seeds
|
|
312
|
+
* keep every digit), numbers are stringified, and anything else — missing,
|
|
313
|
+
* null, objects, ComfyUI node references like ["95", 0] — becomes "".
|
|
314
|
+
*
|
|
315
|
+
* Every value ends up interpolated into A1111 text, so there is no reason to
|
|
316
|
+
* hold numbers as numbers. Returning "" (falsy) enables `||` fallback chains:
|
|
317
|
+
* `asText(a) || asText(b)`.
|
|
302
318
|
*/
|
|
303
|
-
function
|
|
304
|
-
return typeof v === "string" ? v : "";
|
|
319
|
+
function asText(v) {
|
|
320
|
+
return typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
|
|
305
321
|
}
|
|
306
322
|
/**
|
|
307
323
|
* Convert a value to its string representation for channeling.
|
|
@@ -315,18 +331,6 @@ function stringifyValue(v) {
|
|
|
315
331
|
return "";
|
|
316
332
|
}
|
|
317
333
|
/**
|
|
318
|
-
* Coerce unknown value to number. Returns undefined for non-numeric values.
|
|
319
|
-
* Accepts both number and numeric string inputs (e.g. "42" → 42).
|
|
320
|
-
* NaN values are filtered out and returned as undefined.
|
|
321
|
-
*/
|
|
322
|
-
function asNumber(v) {
|
|
323
|
-
if (typeof v === "number") return v === v ? v : void 0;
|
|
324
|
-
if (typeof v === "string") {
|
|
325
|
-
const n = +v;
|
|
326
|
-
return n === n ? n : void 0;
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
334
|
* Extract width/height from a dimension string using the given regex.
|
|
331
335
|
* Different tools use different formats:
|
|
332
336
|
* - Fooocus: "1024x1024" → /(\d+)\s*x\s*(\d+)/
|
|
@@ -335,11 +339,11 @@ function asNumber(v) {
|
|
|
335
339
|
function parseDimensions(text, pattern) {
|
|
336
340
|
if (!text) return [];
|
|
337
341
|
const match = text.match(pattern);
|
|
338
|
-
return match ? [
|
|
342
|
+
return match ? [match[1], match[2]] : [];
|
|
339
343
|
}
|
|
340
344
|
//#endregion
|
|
341
345
|
//#region src/read.ts
|
|
342
|
-
const MAX_CABX =
|
|
346
|
+
const MAX_CABX = 8388608;
|
|
343
347
|
/**
|
|
344
348
|
* Extract text chunks from PNG data as keyword→text entries.
|
|
345
349
|
*/
|
|
@@ -353,6 +357,7 @@ function readPng(data) {
|
|
|
353
357
|
offset += 8;
|
|
354
358
|
if (offset + length > data.length) break;
|
|
355
359
|
if (type === "caBX") entries.cabx = str(data, offset, Math.min(length, MAX_CABX));
|
|
360
|
+
if (type === "eXIf") Object.assign(entries, readExif(data.subarray(offset, offset + length)));
|
|
356
361
|
if (type === "tEXt" || type === "iTXt") {
|
|
357
362
|
const nullIdx = data.indexOf(0, offset);
|
|
358
363
|
if (nullIdx > offset && nullIdx < offset + length) {
|
|
@@ -376,7 +381,8 @@ function readPng(data) {
|
|
|
376
381
|
return entries;
|
|
377
382
|
}
|
|
378
383
|
/**
|
|
379
|
-
* Extract metadata from JPEG: EXIF UserComment/ImageDescription/Make/Model
|
|
384
|
+
* Extract metadata from JPEG: EXIF UserComment/ImageDescription/Make/Model,
|
|
385
|
+
* COM segment, and APP11 (C2PA) as `cabx`.
|
|
380
386
|
*/
|
|
381
387
|
function readJpeg(data) {
|
|
382
388
|
const entries = {};
|
|
@@ -390,6 +396,7 @@ function readJpeg(data) {
|
|
|
390
396
|
if (marker > 216 && marker < 219) break;
|
|
391
397
|
const segLen = data[offset + 2] << 8 | data[offset + 3];
|
|
392
398
|
if (marker === 225 && offset + 10 <= data.length && str(data, offset + 4, 6) === "Exif\0\0") Object.assign(entries, readExif(data.subarray(offset + 10, offset + 2 + segLen)));
|
|
399
|
+
if (marker === 235) entries.cabx = (entries.cabx ?? "") + str(data, offset + 12, segLen - 10);
|
|
393
400
|
if (marker === 254) {
|
|
394
401
|
const text = tryUtf8(data.subarray(offset + 4, offset + 2 + segLen));
|
|
395
402
|
if (text) entries.Comment = text;
|
|
@@ -436,6 +443,7 @@ function readExif(data) {
|
|
|
436
443
|
if (typeof software === "string" && software.startsWith("NovelAI") && typeof comment === "string") {
|
|
437
444
|
entries.Software = software;
|
|
438
445
|
entries.Comment = comment;
|
|
446
|
+
entries.Source = obj.Source;
|
|
439
447
|
return;
|
|
440
448
|
}
|
|
441
449
|
} catch {}
|
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 * 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?: number;\n /** Sampling steps */\n st?: number;\n /** CFG scale (classifier-free guidance) */\n cf?: number;\n /** Sampler algorithm name */\n sa?: string;\n /** Noise scheduler */\n sc?: string;\n /** Image width in pixels */\n w?: number;\n /** Image height in pixels */\n h?: number;\n /** Model filename */\n md?: string;\n /** Model hash */\n mh?: string;\n /** CLIP skip */\n cs?: number;\n /** Denoising strength */\n dn?: number;\n /** Hires upscale factor */\n hs?: number;\n /** Hires upscaler name */\n hu?: string;\n /** Hires denoising strength */\n hd?: number;\n /** Hires sampling steps */\n ht?: number;\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 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\n // with a distinctive \"use_stable_diffusion_model\" key.\n if (entries[EASY_DIFF_KEY]) return buildA1111(extractCommon(entries));\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) carry no generation params, so\n // their generator name is the last resort.\n return (\n params ??\n entries.UserComment ??\n entries.Comment ??\n entries.ImageDescription ??\n readC2paName(entries.cabx)\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 (asString(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(\n asString(obj.resolution),\n /(\\d+)\\s*x\\s*(\\d+)/,\n );\n return buildA1111({ ...extractCommon(obj), w, h });\n }\n\n // HF Space / Civitai generator: identified by \"base_model\" key.\n // Resolution format: \"(1024, 1024)\" (Python tuple string).\n if ('base_model' in obj) {\n const [w, h] = parseDimensions(\n asString(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 = asString(obj.sampler ?? obj.sampler_name);\n const sc = asString(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: \"prompt\" (most tools) → \"Prompt\" (Fooocus) → \"positive_prompt\" (RuinedFooocus)\n p: asString(obj.prompt ?? obj.Prompt ?? obj.positive_prompt),\n // Negative: multiple naming conventions across tools\n // \"uc\" = NovelAI's \"undesired content\"\n n: asString(\n obj.negative_prompt ??\n obj.Negative ??\n obj.negativeprompt ??\n obj.negativePrompt ??\n obj.uc,\n ),\n se: asNumber(obj.seed),\n // \"num_inference_steps\" = HF Space / Civitai generator\n st: asNumber(obj.steps ?? obj.num_inference_steps),\n // CFG: many naming variants across tools\n // \"scale\" = NovelAI, \"guidance_scale\" = HF Space\n cf: asNumber(\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: asNumber(obj.width),\n h: asNumber(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 asString(mod) ||\n asString(obj.Model) ||\n asString(obj.base_model) ||\n asString(obj.base_model_name) ||\n asString(base) ||\n asString(mod?.name) ||\n asString(base?.modelFileName) ||\n asString(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 asString(obj.base_model_hash) ||\n asString(obj['Model hash']) ||\n asString(mod?.hash) ||\n asString(base?.hash),\n cs: asNumber(obj.clip_skip ?? obj.clipSkip),\n // Hires/upscaler: use_upscaler (Fooocus, HF Space) → refiner* (SwarmUI)\n hs: asNumber(up?.upscale_by) ?? asNumber(obj.refinerupscale),\n hu: asString(up?.upscale_method) || asString(obj.refinerupscalemethod),\n hd:\n asNumber(up?.upscaler_strength) ?? asNumber(obj.refinercontrolpercentage),\n ht: asNumber(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 return buildA1111({\n ...extractCommon(obj),\n // Prefer v4 captions, fall back to legacy flat fields.\n p: asString(v4Caption?.base_caption) || asString(obj.prompt),\n n: asString(v4NegCaption?.base_caption) || asString(obj.uc),\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 // 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 = asString(node[CT]);\n const inputs = node.inputs as JsonObject | undefined;\n if (!inputs) continue;\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 asString(inputs.text) ||\n asString(inputs.prompt) ||\n asString(inputs.Text) ||\n asString(inputs.prompt_text) ||\n asString(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 ??= asNumber(inputs.seed) ?? asNumber(inputs.noise_seed);\n result.st ??= asNumber(inputs.steps);\n result.cf ??= asNumber(inputs.cfg);\n result.sa ||= asString(inputs.sampler_name);\n result.sc ||= asString(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 ||= asString(inputs.ckpt_name) || asString(inputs.unet_name);\n\n // --- Latent image nodes (for dimensions) -------------------------\n result.w ??= asNumber(inputs.width);\n result.h ??= asNumber(inputs.height);\n }\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 truthy (skips 0, undefined, \"\").\n const addField = (key: string, value: string | number | 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 unknown value to string. Returns \"\" for non-strings.\n * Returning \"\" (falsy) enables `||` fallback chains: `asString(a) || asString(b)`.\n */\nfunction asString(v: unknown): string {\n return typeof v === '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 * Coerce unknown value to number. Returns undefined for non-numeric values.\n * Accepts both number and numeric string inputs (e.g. \"42\" → 42).\n * NaN values are filtered out and returned as undefined.\n */\nfunction asNumber(v: unknown): number | undefined {\n // biome-ignore lint/suspicious/noSelfCompare: intentional NaN check (IEEE 754: NaN !== NaN)\n if (typeof v === 'number') return v === v ? v : undefined;\n if (typeof v === 'string') {\n const n = +v;\n // biome-ignore lint/suspicious/noSelfCompare: intentional NaN check (IEEE 754: NaN !== NaN)\n return n === n ? n : undefined;\n }\n return undefined;\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): [number?, number?] {\n if (!text) return [];\n const match = text.match(pattern);\n return match ? [Number(match[1]), Number(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 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 + COM segment.\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 // 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 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":";AAoEA,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;IAEF,SACC,QAAQ,WAAW,eAAe,IAAI,IAAI,CAAC,CAAC,QAAQ,QAAQ,EAAE;EAClE;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,iBAA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;;;;;;;;;;;;;;;;;ACxTA,SAAgB,MAAM,OAAyC;CAC7D,MAAM,OAAO,iBAAiB,cAAc,IAAI,WAAW,KAAK,IAAI;CAOpE,IAAI,KAAK,OAAO,OAAQ,KAAK,OAAO,IAClC,OAAO,QAAQ,QAAQ,IAAI,CAAC;CAI9B,IAAI,KAAK,OAAO,OAAQ,KAAK,OAAO,KAClC,OAAO,QAAQ,SAAS,IAAI,CAAC;CAI/B,IAAI,KAAK,OAAO,MAAQ,KAAK,OAAO,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, 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;CAAiB,GACxE,IAAI,IAAI,MAAM;EACZ,MAAM,SAAkB;GACtB,GAAG;IAEF,SACC,QAAQ,WAAW,eAAe,IAAI,IAAI,CAAC,CAAC,QAAQ,QAAQ,EAAE;EAClE;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,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YAAY,MAAkB,IAAqB;CAC1D,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,QAAQ,KAAK,GAAG;EAC3C,MAAM,OAAO,KACT,KAAK,KAAO,KAAK,IAAI,MAAO,IAC3B,KAAK,MAAO,IAAK,KAAK,IAAI;EAC/B,IAAI,CAAC,MAAM;EACX,KAAK,aAAa,IAAI;CACxB;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;ACrUA,SAAgB,MAAM,OAAyC;CAC7D,MAAM,OAAO,iBAAiB,cAAc,IAAI,WAAW,KAAK,IAAI;CAOpE,IAAI,KAAK,OAAO,OAAQ,KAAK,OAAO,IAClC,OAAO,QAAQ,QAAQ,IAAI,CAAC;CAI9B,IAAI,KAAK,OAAO,OAAQ,KAAK,OAAO,KAClC,OAAO,QAAQ,SAAS,IAAI,CAAC;CAI/B,IAAI,KAAK,OAAO,MAAQ,KAAK,OAAO,IAClC,OAAO,QAAQ,SAAS,IAAI,CAAC;CAG/B,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enslo/sd-metadata-lite",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Lightweight AI image metadata reader for bookmarklets",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@biomejs/biome": "catalog:",
|
|
48
48
|
"@types/node": "catalog:",
|
|
49
|
-
"esbuild": "^0.28.
|
|
50
|
-
"terser": "^5.
|
|
49
|
+
"esbuild": "^0.28.2",
|
|
50
|
+
"terser": "^5.51.2",
|
|
51
51
|
"tsdown": "catalog:",
|
|
52
|
-
"tsx": "^4.23.
|
|
52
|
+
"tsx": "^4.23.15",
|
|
53
53
|
"typescript": "catalog:",
|
|
54
54
|
"vitest": "catalog:"
|
|
55
55
|
}
|