@buoy-gg/images 7.0.40 → 7.0.42

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.
Files changed (179) hide show
  1. package/README.md +12 -65
  2. package/lib/commonjs/autoCapture.js +1 -0
  3. package/lib/commonjs/autoCapture.web.js +1 -0
  4. package/lib/commonjs/capture/actions.js +1 -242
  5. package/lib/commonjs/capture/install.js +1 -45
  6. package/lib/commonjs/capture/install.web.js +1 -0
  7. package/lib/commonjs/capture/installExpoImage.js +1 -99
  8. package/lib/commonjs/capture/installRnImage.js +1 -128
  9. package/lib/commonjs/capture/nativeImageModules.js +1 -0
  10. package/lib/commonjs/capture/nativeImageModules.web.js +1 -0
  11. package/lib/commonjs/capture/overrides.js +1 -346
  12. package/lib/commonjs/capture/rnDecoratorEarly.js +1 -0
  13. package/lib/commonjs/capture/savings.js +1 -209
  14. package/lib/commonjs/capture/savings.web.js +1 -0
  15. package/lib/commonjs/capture/shared.js +1 -378
  16. package/lib/commonjs/components/ImageDetail.js +1 -454
  17. package/lib/commonjs/components/ImageDetailFooter.js +1 -158
  18. package/lib/commonjs/components/ImageRow.js +1 -156
  19. package/lib/commonjs/components/ImagesHeader.js +1 -63
  20. package/lib/commonjs/components/ImagesIcon.js +1 -19
  21. package/lib/commonjs/components/ImagesListFooter.js +1 -126
  22. package/lib/commonjs/components/ImagesModal.js +1 -240
  23. package/lib/commonjs/components/ImagesRoot.js +1 -24
  24. package/lib/commonjs/components/ImagesRoot.web.js +1 -0
  25. package/lib/commonjs/components/InsightsBar.js +1 -59
  26. package/lib/commonjs/export.js +1 -81
  27. package/lib/commonjs/format.js +1 -117
  28. package/lib/commonjs/hooks/useImageRecords.js +1 -20
  29. package/lib/commonjs/index.js +1 -261
  30. package/lib/commonjs/preset.js +1 -39
  31. package/lib/commonjs/register.js +1 -19
  32. package/lib/commonjs/registerEarly.js +1 -0
  33. package/lib/commonjs/remote.js +1 -42
  34. package/lib/commonjs/state.js +1 -58
  35. package/lib/commonjs/store/imageEventStore.js +1 -238
  36. package/lib/commonjs/store/insights.js +1 -76
  37. package/lib/commonjs/sync/imagesSyncAdapter.js +1 -360
  38. package/lib/commonjs/types.js +0 -1
  39. package/lib/module/autoCapture.js +1 -0
  40. package/lib/module/autoCapture.web.js +1 -0
  41. package/lib/module/capture/actions.js +1 -229
  42. package/lib/module/capture/install.js +1 -40
  43. package/lib/module/capture/install.web.js +1 -0
  44. package/lib/module/capture/installExpoImage.js +1 -94
  45. package/lib/module/capture/installRnImage.js +1 -122
  46. package/lib/module/capture/nativeImageModules.js +1 -0
  47. package/lib/module/capture/nativeImageModules.web.js +1 -0
  48. package/lib/module/capture/overrides.js +1 -329
  49. package/lib/module/capture/rnDecoratorEarly.js +1 -0
  50. package/lib/module/capture/savings.js +1 -205
  51. package/lib/module/capture/savings.web.js +1 -0
  52. package/lib/module/capture/shared.js +1 -369
  53. package/lib/module/components/ImageDetail.js +1 -450
  54. package/lib/module/components/ImageDetailFooter.js +1 -154
  55. package/lib/module/components/ImageRow.js +1 -152
  56. package/lib/module/components/ImagesHeader.js +1 -59
  57. package/lib/module/components/ImagesIcon.js +1 -12
  58. package/lib/module/components/ImagesListFooter.js +1 -122
  59. package/lib/module/components/ImagesModal.js +1 -235
  60. package/lib/module/components/ImagesRoot.js +1 -20
  61. package/lib/module/components/ImagesRoot.web.js +1 -0
  62. package/lib/module/components/InsightsBar.js +1 -55
  63. package/lib/module/export.js +1 -76
  64. package/lib/module/format.js +1 -108
  65. package/lib/module/hooks/useImageRecords.js +1 -16
  66. package/lib/module/index.js +1 -79
  67. package/lib/module/preset.js +1 -35
  68. package/lib/module/register.js +1 -19
  69. package/lib/module/registerEarly.js +1 -0
  70. package/lib/module/remote.js +1 -36
  71. package/lib/module/state.js +1 -54
  72. package/lib/module/store/imageEventStore.js +1 -221
  73. package/lib/module/store/insights.js +1 -71
  74. package/lib/module/sync/imagesSyncAdapter.js +1 -355
  75. package/lib/module/types.js +0 -1
  76. package/lib/typescript/autoCapture.d.ts +2 -0
  77. package/lib/typescript/autoCapture.web.d.ts +2 -0
  78. package/lib/typescript/capture/actions.d.ts +0 -17
  79. package/lib/typescript/capture/install.web.d.ts +6 -0
  80. package/lib/typescript/capture/installRnImage.d.ts +5 -0
  81. package/lib/typescript/capture/nativeImageModules.d.ts +4 -0
  82. package/lib/typescript/capture/nativeImageModules.web.d.ts +4 -0
  83. package/lib/typescript/capture/rnDecoratorEarly.d.ts +18 -0
  84. package/lib/typescript/capture/savings.web.d.ts +5 -0
  85. package/lib/typescript/components/ImageDetail.d.ts +0 -6
  86. package/lib/typescript/components/ImagesRoot.web.d.ts +2 -0
  87. package/lib/typescript/index.d.ts +1 -1
  88. package/lib/typescript/registerEarly.d.ts +10 -0
  89. package/lib/typescript/sync/imagesSyncAdapter.d.ts +0 -9
  90. package/lib/typescript/types.d.ts +2 -1
  91. package/lib/web/chunks/chunk-TTS5EH4R.mjs +1 -0
  92. package/lib/web/index.mjs +3 -0
  93. package/lib/web/register.mjs +1 -0
  94. package/package.json +52 -6
  95. package/register.js +1 -15
  96. package/lib/commonjs/capture/actions.js.map +0 -1
  97. package/lib/commonjs/capture/install.js.map +0 -1
  98. package/lib/commonjs/capture/installExpoImage.js.map +0 -1
  99. package/lib/commonjs/capture/installRnImage.js.map +0 -1
  100. package/lib/commonjs/capture/overrides.js.map +0 -1
  101. package/lib/commonjs/capture/savings.js.map +0 -1
  102. package/lib/commonjs/capture/shared.js.map +0 -1
  103. package/lib/commonjs/components/ImageDetail.js.map +0 -1
  104. package/lib/commonjs/components/ImageDetailFooter.js.map +0 -1
  105. package/lib/commonjs/components/ImageRow.js.map +0 -1
  106. package/lib/commonjs/components/ImagesHeader.js.map +0 -1
  107. package/lib/commonjs/components/ImagesIcon.js.map +0 -1
  108. package/lib/commonjs/components/ImagesListFooter.js.map +0 -1
  109. package/lib/commonjs/components/ImagesModal.js.map +0 -1
  110. package/lib/commonjs/components/ImagesRoot.js.map +0 -1
  111. package/lib/commonjs/components/InsightsBar.js.map +0 -1
  112. package/lib/commonjs/export.js.map +0 -1
  113. package/lib/commonjs/format.js.map +0 -1
  114. package/lib/commonjs/hooks/useImageRecords.js.map +0 -1
  115. package/lib/commonjs/index.js.map +0 -1
  116. package/lib/commonjs/preset.js.map +0 -1
  117. package/lib/commonjs/register.js.map +0 -1
  118. package/lib/commonjs/remote.js.map +0 -1
  119. package/lib/commonjs/state.js.map +0 -1
  120. package/lib/commonjs/store/imageEventStore.js.map +0 -1
  121. package/lib/commonjs/store/insights.js.map +0 -1
  122. package/lib/commonjs/sync/imagesSyncAdapter.js.map +0 -1
  123. package/lib/commonjs/types.js.map +0 -1
  124. package/lib/module/capture/actions.js.map +0 -1
  125. package/lib/module/capture/install.js.map +0 -1
  126. package/lib/module/capture/installExpoImage.js.map +0 -1
  127. package/lib/module/capture/installRnImage.js.map +0 -1
  128. package/lib/module/capture/overrides.js.map +0 -1
  129. package/lib/module/capture/savings.js.map +0 -1
  130. package/lib/module/capture/shared.js.map +0 -1
  131. package/lib/module/components/ImageDetail.js.map +0 -1
  132. package/lib/module/components/ImageDetailFooter.js.map +0 -1
  133. package/lib/module/components/ImageRow.js.map +0 -1
  134. package/lib/module/components/ImagesHeader.js.map +0 -1
  135. package/lib/module/components/ImagesIcon.js.map +0 -1
  136. package/lib/module/components/ImagesListFooter.js.map +0 -1
  137. package/lib/module/components/ImagesModal.js.map +0 -1
  138. package/lib/module/components/ImagesRoot.js.map +0 -1
  139. package/lib/module/components/InsightsBar.js.map +0 -1
  140. package/lib/module/export.js.map +0 -1
  141. package/lib/module/format.js.map +0 -1
  142. package/lib/module/hooks/useImageRecords.js.map +0 -1
  143. package/lib/module/index.js.map +0 -1
  144. package/lib/module/preset.js.map +0 -1
  145. package/lib/module/register.js.map +0 -1
  146. package/lib/module/remote.js.map +0 -1
  147. package/lib/module/state.js.map +0 -1
  148. package/lib/module/store/imageEventStore.js.map +0 -1
  149. package/lib/module/store/insights.js.map +0 -1
  150. package/lib/module/sync/imagesSyncAdapter.js.map +0 -1
  151. package/lib/module/types.js.map +0 -1
  152. package/lib/typescript/capture/actions.d.ts.map +0 -1
  153. package/lib/typescript/capture/install.d.ts.map +0 -1
  154. package/lib/typescript/capture/installExpoImage.d.ts.map +0 -1
  155. package/lib/typescript/capture/installRnImage.d.ts.map +0 -1
  156. package/lib/typescript/capture/overrides.d.ts.map +0 -1
  157. package/lib/typescript/capture/savings.d.ts.map +0 -1
  158. package/lib/typescript/capture/shared.d.ts.map +0 -1
  159. package/lib/typescript/components/ImageDetail.d.ts.map +0 -1
  160. package/lib/typescript/components/ImageDetailFooter.d.ts.map +0 -1
  161. package/lib/typescript/components/ImageRow.d.ts.map +0 -1
  162. package/lib/typescript/components/ImagesHeader.d.ts.map +0 -1
  163. package/lib/typescript/components/ImagesIcon.d.ts.map +0 -1
  164. package/lib/typescript/components/ImagesListFooter.d.ts.map +0 -1
  165. package/lib/typescript/components/ImagesModal.d.ts.map +0 -1
  166. package/lib/typescript/components/ImagesRoot.d.ts.map +0 -1
  167. package/lib/typescript/components/InsightsBar.d.ts.map +0 -1
  168. package/lib/typescript/export.d.ts.map +0 -1
  169. package/lib/typescript/format.d.ts.map +0 -1
  170. package/lib/typescript/hooks/useImageRecords.d.ts.map +0 -1
  171. package/lib/typescript/index.d.ts.map +0 -1
  172. package/lib/typescript/preset.d.ts.map +0 -1
  173. package/lib/typescript/register.d.ts.map +0 -1
  174. package/lib/typescript/remote.d.ts.map +0 -1
  175. package/lib/typescript/state.d.ts.map +0 -1
  176. package/lib/typescript/store/imageEventStore.d.ts.map +0 -1
  177. package/lib/typescript/store/insights.d.ts.map +0 -1
  178. package/lib/typescript/sync/imagesSyncAdapter.d.ts.map +0 -1
  179. package/lib/typescript/types.d.ts.map +0 -1
@@ -1,205 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * Savings prover — Squoosh-style, on device.
5
- *
6
- * Instead of estimating what an oversized source wastes, PROVE it: re-encode
7
- * the image at the displayed size (× pixel ratio) as WebP via
8
- * expo-image-manipulator (verified: chainable resize → saveAsync WebP on BOTH
9
- * platforms, available in Expo Go), stat the output file, and report real
10
- * bytes vs the original. The optimized file:// URI can then be A/B'd in place
11
- * through the existing swap-url override.
12
- *
13
- * Original size is resolved in tiers: observed download bytes (onProgress
14
- * total) → expo disk-cache file size → HEAD Content-Length.
15
- */
16
-
17
- import { remoteImagesDispatch } from "../remote";
18
- import { neededPixels } from "../store/imageEventStore";
19
- function loadLegacyFs() {
20
- try {
21
- const mod = require("expo-file-system/legacy");
22
- const fs = mod?.default || mod;
23
- if (fs?.getInfoAsync) return fs;
24
- } catch {
25
- // try main import
26
- }
27
- try {
28
- const mod = require("expo-file-system");
29
- const fs = mod?.default || mod;
30
- if (fs?.getInfoAsync) return fs;
31
- } catch {
32
- // not installed
33
- }
34
- return null;
35
- }
36
- async function fileSize(uri) {
37
- const fs = loadLegacyFs();
38
- if (!fs?.getInfoAsync) return null;
39
- try {
40
- const normalized = uri.startsWith("file://") ? uri : `file://${uri}`;
41
- const info = await fs.getInfoAsync(normalized, {
42
- size: true
43
- });
44
- return info.exists && typeof info.size === "number" ? info.size : null;
45
- } catch {
46
- return null;
47
- }
48
- }
49
- async function resolveOriginalBytes(record) {
50
- if (record.bytesTotal && record.bytesTotal > 0) {
51
- return {
52
- bytes: record.bytesTotal,
53
- source: "download"
54
- };
55
- }
56
- // expo disk cache file
57
- if (record.lib === "expo") {
58
- try {
59
- const expo = require("expo-image");
60
- const path = await expo.Image.getCachePathAsync(record.uri);
61
- if (path) {
62
- const size = await fileSize(path);
63
- if (size != null) return {
64
- bytes: size,
65
- source: "cacheFile"
66
- };
67
- }
68
- } catch {
69
- // fall through
70
- }
71
- }
72
- // HEAD request (network sources only)
73
- if (record.sourceKind === "network") {
74
- try {
75
- const response = await fetch(record.uri, {
76
- method: "HEAD"
77
- });
78
- const length = Number(response.headers.get("content-length"));
79
- if (Number.isFinite(length) && length > 0) return {
80
- bytes: length,
81
- source: "head"
82
- };
83
- } catch {
84
- // unknown original size is fine
85
- }
86
- }
87
- return null;
88
- }
89
-
90
- /**
91
- * Re-encode `record`'s source at its displayed size as WebP and measure it.
92
- * Requires expo-image-manipulator (graceful message when absent).
93
- */
94
- export async function proveSavings(record) {
95
- // Mirror mode: the re-encode must happen ON DEVICE (that's the whole point —
96
- // real bytes from the real encoder); forward and relay the result.
97
- const remote = remoteImagesDispatch();
98
- if (remote) {
99
- try {
100
- return await remote("proveSavings", {
101
- id: record.id
102
- });
103
- } catch (error) {
104
- return {
105
- ok: false,
106
- message: String(error?.message ?? error)
107
- };
108
- }
109
- }
110
- if (!record.uri || record.sourceKind !== "network" && record.sourceKind !== "asset" && record.sourceKind !== "file") {
111
- return {
112
- ok: false,
113
- message: "No loadable source URI on this record"
114
- };
115
- }
116
- const needed = neededPixels(record);
117
- if (!needed) {
118
- return {
119
- ok: false,
120
- message: "No layout yet — the image must render once to know its displayed size"
121
- };
122
- }
123
- let manipulator;
124
- try {
125
- manipulator = require("expo-image-manipulator");
126
- } catch {
127
- return {
128
- ok: false,
129
- message: "expo-image-manipulator not installed — add it to enable real savings measurement"
130
- };
131
- }
132
- const webp = manipulator.SaveFormat?.WEBP ?? "webp";
133
- const targetWidth = Math.min(needed.width, record.intrinsic?.width ?? needed.width);
134
- let original = null;
135
- let optimized = null;
136
- try {
137
- [original, optimized] = await Promise.all([resolveOriginalBytes(record), (async () => {
138
- // Preferred: context API (current). Fallback: deprecated manipulateAsync.
139
- if (manipulator.ImageManipulator?.manipulate) {
140
- const context = manipulator.ImageManipulator.manipulate(record.uri);
141
- try {
142
- const ref = await context.resize({
143
- width: targetWidth
144
- }).renderAsync();
145
- try {
146
- return await ref.saveAsync({
147
- format: webp,
148
- compress: 0.8
149
- });
150
- } finally {
151
- ref.release?.();
152
- }
153
- } finally {
154
- context.release?.();
155
- }
156
- }
157
- if (manipulator.manipulateAsync) {
158
- return manipulator.manipulateAsync(record.uri, [{
159
- resize: {
160
- width: targetWidth
161
- }
162
- }], {
163
- compress: 0.8,
164
- format: webp
165
- });
166
- }
167
- return null;
168
- })()]);
169
- } catch (error) {
170
- return {
171
- ok: false,
172
- message: `Re-encode failed: ${String(error?.message ?? error)}`
173
- };
174
- }
175
- if (!optimized?.uri) {
176
- return {
177
- ok: false,
178
- message: "Re-encode produced no output (unsupported source?)"
179
- };
180
- }
181
- const optimizedBytes = await fileSize(optimized.uri);
182
- const result = {
183
- ok: true,
184
- message: "",
185
- optimizedUri: optimized.uri,
186
- optimizedBytes: optimizedBytes ?? undefined,
187
- optimizedDims: {
188
- width: optimized.width,
189
- height: optimized.height
190
- },
191
- originalBytes: original?.bytes,
192
- originalBytesSource: original?.source
193
- };
194
- if (original?.bytes != null && optimizedBytes != null) {
195
- result.savedBytes = Math.max(0, original.bytes - optimizedBytes);
196
- result.savedPct = original.bytes > 0 ? Math.round(result.savedBytes / original.bytes * 100) : 0;
197
- result.message = `Right-sized WebP is ${result.savedPct}% smaller (real bytes, encoded on device)`;
198
- } else if (optimizedBytes != null) {
199
- result.message = "Optimized variant encoded — original size unknown (no download bytes, cache entry, or Content-Length)";
200
- } else {
201
- result.message = "Optimized variant encoded — could not stat the output file";
202
- }
203
- return result;
204
- }
205
- //# sourceMappingURL=savings.js.map
1
+ "use strict";import{remoteImagesDispatch as d}from"../remote";import{neededPixels as y}from"../store/imageEventStore";function g(){try{const e=require("expo-file-system/legacy");const t=e?.default||e;if(t?.getInfoAsync)return t}catch{}try{const e=require("expo-file-system");const t=e?.default||e;if(t?.getInfoAsync)return t}catch{}return null}async function f(e){const t=g();if(!t?.getInfoAsync)return null;try{const n=e.startsWith("file://")?e:`file://${e}`;const s=await t.getInfoAsync(n,{size:true});return s.exists&&typeof s.size==="number"?s.size:null}catch{return null}}async function p(e){if(e.bytesTotal&&e.bytesTotal>0){return{bytes:e.bytesTotal,source:"download"}}if(e.lib==="expo"){try{const t=require("expo-image");const n=await t.Image.getCachePathAsync(e.uri);if(n){const s=await f(n);if(s!=null)return{bytes:s,source:"cacheFile"}}}catch{}}if(e.sourceKind==="network"){try{const t=await fetch(e.uri,{method:"HEAD"});const n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>0)return{bytes:n,source:"head"}}catch{}}return null}export async function proveSavings(e){const t=d();if(t){try{return await t("proveSavings",{id:e.id})}catch(a){return{ok:false,message:String(a?.message??a)}}}if(!e.uri||e.sourceKind!=="network"&&e.sourceKind!=="asset"&&e.sourceKind!=="file"){return{ok:false,message:"No loadable source URI on this record"}}const n=y(e);if(!n){return{ok:false,message:"No layout yet \u2014 the image must render once to know its displayed size"}}let s;try{s=require("expo-image-manipulator")}catch{return{ok:false,message:"expo-image-manipulator not installed \u2014 add it to enable real savings measurement"}}const u=s.SaveFormat?.WEBP??"webp";const c=Math.min(n.width,e.intrinsic?.width??n.width);let r=null;let o=null;try{[r,o]=await Promise.all([p(e),(async()=>{if(s.ImageManipulator?.manipulate){const a=s.ImageManipulator.manipulate(e.uri);try{const m=await a.resize({width:c}).renderAsync();try{return await m.saveAsync({format:u,compress:.8})}finally{m.release?.()}}finally{a.release?.()}}if(s.manipulateAsync){return s.manipulateAsync(e.uri,[{resize:{width:c}}],{compress:.8,format:u})}return null})()])}catch(a){return{ok:false,message:`Re-encode failed: ${String(a?.message??a)}`}}if(!o?.uri){return{ok:false,message:"Re-encode produced no output (unsupported source?)"}}const l=await f(o.uri);const i={ok:true,message:"",optimizedUri:o.uri,optimizedBytes:l??void 0,optimizedDims:{width:o.width,height:o.height},originalBytes:r?.bytes,originalBytesSource:r?.source};if(r?.bytes!=null&&l!=null){i.savedBytes=Math.max(0,r.bytes-l);i.savedPct=r.bytes>0?Math.round(i.savedBytes/r.bytes*100):0;i.message=`Right-sized WebP is ${i.savedPct}% smaller (real bytes, encoded on device)`}else if(l!=null){i.message="Optimized variant encoded \u2014 original size unknown (no download bytes, cache entry, or Content-Length)"}else{i.message="Optimized variant encoded \u2014 could not stat the output file"}return i}
@@ -0,0 +1 @@
1
+ "use strict";import{remoteImagesDispatch as u}from"../remote";import{neededPixels as f}from"../store/imageEventStore";const o=new Map;export async function proveSavings(i){const d=u();if(d)return await d("proveSavings",{id:i.id});const r=f(i);if(!r)return{ok:false,message:"Measure the displayed image before optimizing it."};try{const t=await fetch(i.uri);if(!t.ok)throw new Error(`Image download returned HTTP ${t.status}.`);const a=await t.blob();const s=await createImageBitmap(a);const e=document.createElement("canvas");e.width=Math.max(1,Math.min(s.width,Math.round(r.width)));e.height=Math.max(1,Math.min(s.height,Math.round(r.height)));const h=e.getContext("2d");if(!h){s.close();throw new Error("Canvas is unavailable.")}h.drawImage(s,0,0,e.width,e.height);s.close();const n=await new Promise((m,c)=>e.toBlob(p=>p?m(p):c(new Error("Image encoding failed.")),"image/webp",.8));if(n.type!=="image/webp")return{ok:false,message:"This browser cannot encode WebP images."};const g=o.get(i.id);if(g)URL.revokeObjectURL(g);const w=URL.createObjectURL(n);o.set(i.id,w);while(o.size>30){const[m,c]=o.entries().next().value;URL.revokeObjectURL(c);o.delete(m)}const l=a.size-n.size;return{ok:true,message:"WebP preview created.",originalBytes:a.size,originalBytesSource:"download",optimizedBytes:n.size,optimizedUri:w,optimizedDims:{width:e.width,height:e.height},savedBytes:l,savedPct:a.size?l/a.size*100:0}}catch(t){return{ok:false,message:`Image optimization failed: ${t instanceof Error?t.message:String(t)}`}}}
@@ -1,369 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * Capture core shared by the RN <Image> decorator and the expo-image patch.
5
- *
6
- * ImageInstanceTracker: one per live image component instance. It rolls a new
7
- * ImageRecord whenever the instance's source URI changes, and exposes wrapped
8
- * event handlers that feed the store while still calling through to whatever
9
- * handlers the app passed.
10
- */
11
-
12
- import { imagesState } from "../state";
13
- import { dropActionState, settleReloadRequest } from "./actions";
14
- import { createRecord, getRecord, updateRecord } from "../store/imageEventStore";
15
-
16
- /**
17
- * Images rendered by Buoy's own UI (e.g. thumbnails inside the Images modal)
18
- * carry this testID prefix and are excluded from capture, so the tool doesn't
19
- * pollute its own registry.
20
- */
21
- export const INTERNAL_TEST_ID_PREFIX = "buoy-internal";
22
- export function isInternalImage(testID) {
23
- return typeof testID === "string" && testID.startsWith(INTERNAL_TEST_ID_PREFIX);
24
- }
25
-
26
- /**
27
- * React Native's own devtools UI loads images too (LogBox icons resolve to
28
- * Metro asset URLs under Libraries/LogBox). They're noise in an app-focused
29
- * registry — skip them.
30
- */
31
- export function isNoiseUri(uri) {
32
- return uri.includes("Libraries%2FLogBox") || uri.includes("Libraries/LogBox") || uri.includes("LogBoxImages");
33
- }
34
- export function classifyUri(uri) {
35
- if (uri.startsWith("http://") || uri.startsWith("https://")) return "network";
36
- if (uri.startsWith("file://") || uri.startsWith("asset://")) return "file";
37
- if (uri.startsWith("data:")) return "data";
38
- return "other";
39
- }
40
-
41
- /**
42
- * Best-effort URI extraction from any source prop shape (RN or expo-image):
43
- * string, number (Metro asset), {uri}, arrays of those, ImageRef.
44
- */
45
- export function resolveSourceUri(source) {
46
- if (source == null) return {
47
- uri: "",
48
- kind: "other"
49
- };
50
- if (Array.isArray(source)) {
51
- return resolveSourceUri(source.length > 0 ? source[0] : null);
52
- }
53
- if (typeof source === "string") {
54
- return {
55
- uri: source,
56
- kind: classifyUri(source)
57
- };
58
- }
59
- if (typeof source === "number") {
60
- // Metro asset id. Image is guaranteed evaluated by the time an instance
61
- // renders, so requiring it lazily here can never latch the decorator late.
62
- try {
63
- const rn = require("react-native");
64
- const resolved = rn.Image?.resolveAssetSource?.(source);
65
- if (resolved?.uri) return {
66
- uri: resolved.uri,
67
- kind: "asset"
68
- };
69
- } catch {
70
- // fall through
71
- }
72
- return {
73
- uri: `asset:#${source}`,
74
- kind: "asset"
75
- };
76
- }
77
- if (typeof source === "object") {
78
- const uri = source.uri;
79
- if (typeof uri === "string") {
80
- const kind = classifyUri(uri);
81
- // require()'d assets resolve to Metro dev-server URLs in dev — still
82
- // report them as assets when they carry the packager marker.
83
- if (source.__packager_asset) {
84
- return {
85
- uri,
86
- kind: "asset"
87
- };
88
- }
89
- return {
90
- uri,
91
- kind
92
- };
93
- }
94
- // expo-image ImageRef (native shared object) has width/height but no uri.
95
- const width = source.width;
96
- if (typeof width === "number") return {
97
- uri: "(ImageRef)",
98
- kind: "other"
99
- };
100
- }
101
- return {
102
- uri: "",
103
- kind: "other"
104
- };
105
- }
106
-
107
- /** The event-handler subset we intercept, normalized across both libraries. */
108
-
109
- /**
110
- * RN events arrive as {nativeEvent}; expo-image passes the payload directly.
111
- *
112
- * The shape is told apart by the property DESCRIPTOR, never by reading the
113
- * property. expo-image (SDK 56+) installs a deprecation GETTER called
114
- * `nativeEvent` on the payload it hands us — so the obvious
115
- * `event.nativeEvent` sniff logged
116
- * '[expo-image]: Accessing event payload through "nativeEvent" is deprecated'
117
- * once per load event, for every image in the app, purely because Buoy
118
- * looked. A real RN synthetic event carries it as a plain data property;
119
- * `getOwnPropertyDescriptor` distinguishes the two and invokes nothing.
120
- */
121
- export function payloadOf(event) {
122
- if (!event || typeof event !== "object") return {};
123
- const descriptor = Object.getOwnPropertyDescriptor(event, "nativeEvent");
124
- const native = descriptor && !descriptor.get ? descriptor.value : undefined;
125
- if (native && typeof native === "object") {
126
- return native;
127
- }
128
- return event;
129
- }
130
-
131
- /**
132
- * After an RN-core load, classify the cache via Image.queryCache.
133
- *
134
- * Delayed + retried: NSURLCache commits fresh downloads asynchronously, so a
135
- * query at the instant of onLoad reports a miss for images that ARE being
136
- * cached (observed live). First probe after 600ms, one re-probe at 3s to
137
- * catch slow cache writes.
138
- */
139
- function queryRnCache(recordId, uri) {
140
- const probe = () => {
141
- try {
142
- const rn = require("react-native");
143
- const queryCache = rn.Image?.queryCache;
144
- if (typeof queryCache !== "function" || !uri) return;
145
- queryCache([uri]).then(result => {
146
- const verdict = result?.[uri];
147
- if (verdict) {
148
- updateRecord(recordId, {
149
- cacheVerdict: verdict,
150
- cacheVerdictSource: "queryCache"
151
- });
152
- }
153
- }).catch(() => {});
154
- } catch {
155
- // queryCache unavailable (web) — leave verdict unknown.
156
- }
157
- };
158
- setTimeout(probe, 600);
159
- setTimeout(() => {
160
- const record = getRecord(recordId);
161
- if (record && record.cacheVerdictSource !== "queryCache") probe();
162
- }, 3000);
163
- }
164
- export class ImageInstanceTracker {
165
- recordId = null;
166
- uri = null;
167
- handlerCache = null;
168
- constructor(lib) {
169
- this.lib = lib;
170
- }
171
- getRecordId() {
172
- return this.recordId;
173
- }
174
-
175
- /** Record accessibility presence (called per render; writes only on change). */
176
- noteA11y(hasAltText) {
177
- if (this.recordId == null) return;
178
- const record = getRecord(this.recordId);
179
- if (record && record.hasAltText !== hasAltText) {
180
- updateRecord(this.recordId, {
181
- hasAltText
182
- });
183
- }
184
- }
185
-
186
- /** Call on every render with the current source prop. Rolls records on change. */
187
- syncSource(source) {
188
- const {
189
- uri,
190
- kind
191
- } = resolveSourceUri(source);
192
- if (uri === this.uri) return;
193
- this.uri = uri;
194
- this.handlerCache = null; // handlers close over recordId via getter, but roll anyway
195
- if (this.recordId != null) dropActionState(this.recordId);
196
- if (!uri || isNoiseUri(uri)) {
197
- this.recordId = null;
198
- return;
199
- }
200
- const record = createRecord({
201
- lib: this.lib,
202
- uri,
203
- sourceKind: kind
204
- });
205
- this.recordId = record.id;
206
- }
207
- unmount() {
208
- if (this.recordId != null) {
209
- updateRecord(this.recordId, {
210
- mounted: false
211
- });
212
- dropActionState(this.recordId);
213
- }
214
- }
215
-
216
- /**
217
- * Wrapped handlers for the current originals. Cached by handler identity so
218
- * re-renders with unchanged props reuse the same functions.
219
- */
220
- handlers(orig) {
221
- const key = [orig.onLoadStart, orig.onProgress, orig.onLoad, orig.onError, orig.onLoadEnd, orig.onDisplay, orig.onLayout, this.recordId];
222
- const cached = this.handlerCache;
223
- if (cached && cached.key.length === key.length && cached.key.every((k, i) => k === key[i])) {
224
- return cached.out;
225
- }
226
- const recordId = this.recordId;
227
- const lib = this.lib;
228
- const uri = this.uri ?? "";
229
- const out = {
230
- onLoadStart: event => {
231
- if (recordId != null) {
232
- const record = getRecord(recordId);
233
- const now = Date.now();
234
- // Out-of-order defense (seen live on iOS remounts/cache hits AND
235
- // instant file:// failures): the native onLoadStart of a burst can
236
- // arrive AFTER its onLoad/onError. A "start" right after a settled
237
- // outcome belongs to that same burst — don't regress the record.
238
- const settledAt = Math.max(record?.loadedAt ?? 0, record?.erroredAt ?? 0);
239
- const settledJustNow = settledAt > 0 && now - settledAt < 300;
240
- updateRecord(recordId, {
241
- ...(settledJustNow ? {} : {
242
- status: "loading",
243
- error: undefined,
244
- errorCode: undefined,
245
- errorHeaders: undefined
246
- }),
247
- startedAt: now,
248
- loadCount: (record?.loadCount ?? 0) + 1
249
- });
250
- }
251
- orig.onLoadStart?.(event);
252
- },
253
- onProgress: event => {
254
- if (recordId != null) {
255
- const p = payloadOf(event);
256
- updateRecord(recordId, {
257
- progressSeen: true,
258
- bytesLoaded: typeof p.loaded === "number" ? p.loaded : undefined,
259
- bytesTotal: typeof p.total === "number" ? p.total : undefined
260
- });
261
- }
262
- orig.onProgress?.(event);
263
- },
264
- onLoad: event => {
265
- if (recordId != null) {
266
- const p = payloadOf(event);
267
- const source = p.source ?? {};
268
- const now = Date.now();
269
- const record = getRecord(recordId);
270
- // Duration only counts from a start belonging to THIS load cycle: a
271
- // start newer than the previous completion. Without one (instant
272
- // cache hit whose onLoadStart arrives late/never), report 0ms.
273
- const start = record?.startedAt != null && record.startedAt <= now && record.startedAt > (record.loadedAt ?? record.createdAt - 1) ? record.startedAt : record?.loadedAt == null ? record?.startedAt ?? record?.createdAt ?? now : now;
274
- const width = typeof source.width === "number" ? source.width : 0;
275
- const height = typeof source.height === "number" ? source.height : 0;
276
- updateRecord(recordId, {
277
- status: "loaded",
278
- loadedAt: now,
279
- durationMs: Math.max(0, now - start),
280
- error: undefined,
281
- errorCode: undefined,
282
- errorHeaders: undefined,
283
- intrinsic: width > 0 && height > 0 ? {
284
- width,
285
- height
286
- } : record?.intrinsic,
287
- cacheVerdict: typeof p.cacheType === "string" ? p.cacheType : record?.cacheVerdict,
288
- cacheVerdictSource: typeof p.cacheType === "string" ? "event" : record?.cacheVerdictSource,
289
- mediaType: typeof source.mediaType === "string" || source.mediaType === null ? source.mediaType : record?.mediaType,
290
- isAnimated: typeof source.isAnimated === "boolean" ? source.isAnimated : record?.isAnimated
291
- });
292
- settleReloadRequest(recordId);
293
- if (lib === "rn") queryRnCache(recordId, uri);
294
- }
295
- orig.onLoad?.(event);
296
- },
297
- onError: event => {
298
- if (recordId != null) {
299
- const p = payloadOf(event);
300
- let message = typeof p.error === "string" ? p.error : String(p.error?.message ?? "unknown error");
301
- // Simulation sources produce raw file-not-found noise — translate to
302
- // an honest label (state-based, so it works for both libs' error
303
- // texts), in our record AND in the event the app receives.
304
- const record0 = getRecord(recordId);
305
- const s = imagesState();
306
- const activeOverride = s.overrides.get(recordId);
307
- if (activeOverride?.source?.type === "error") {
308
- message = "Forced error (Buoy Images simulation)";
309
- if (typeof p.error === "string") p.error = message;
310
- } else if (s.globalModes.network === "offline" && record0?.sourceKind === "network") {
311
- message = "Offline simulation (Buoy Images): network image blocked";
312
- if (typeof p.error === "string") p.error = message;
313
- }
314
- updateRecord(recordId, {
315
- status: "error",
316
- erroredAt: Date.now(),
317
- error: message,
318
- errorCode: typeof p.responseCode === "number" ? p.responseCode : undefined,
319
- errorHeaders: p.httpResponseHeaders && typeof p.httpResponseHeaders === "object" ? p.httpResponseHeaders : undefined
320
- });
321
- settleReloadRequest(recordId);
322
- }
323
- orig.onError?.(event);
324
- },
325
- onLayout: event => {
326
- if (recordId != null) {
327
- const layout = payloadOf(event).layout ?? {};
328
- const width = typeof layout.width === "number" ? layout.width : 0;
329
- const height = typeof layout.height === "number" ? layout.height : 0;
330
- if (width > 0 && height > 0) {
331
- const record = getRecord(recordId);
332
- const prev = record?.layout;
333
- // Size change AFTER the image loaded = layout-shift suspect (the
334
- // image arriving resized its box — reserve explicit dimensions).
335
- const shifted = prev != null && record?.loadedAt != null && (Math.abs(prev.width - width) > 1 || Math.abs(prev.height - height) > 1);
336
- updateRecord(recordId, {
337
- layout: {
338
- width,
339
- height
340
- },
341
- ...(shifted ? {
342
- layoutShifts: (record?.layoutShifts ?? 0) + 1
343
- } : {})
344
- });
345
- }
346
- }
347
- orig.onLayout?.(event);
348
- }
349
- };
350
-
351
- // Only forward-wrap the optional ones so we don't attach handlers a
352
- // library doesn't support (onDisplay is expo-only; onLoadEnd is RN-only).
353
- out.onLoadEnd = orig.onLoadEnd ? event => orig.onLoadEnd?.(event) : undefined;
354
- if (this.lib === "expo") {
355
- out.onDisplay = event => {
356
- if (recordId != null) updateRecord(recordId, {
357
- displayedAt: Date.now()
358
- });
359
- orig.onDisplay?.(event);
360
- };
361
- }
362
- this.handlerCache = {
363
- key,
364
- out
365
- };
366
- return out;
367
- }
368
- }
369
- //# sourceMappingURL=shared.js.map
1
+ "use strict";import{imagesState as I}from"../state";import{dropActionState as b,settleReloadRequest as A}from"./actions";import{createRecord as w,getRecord as h,updateRecord as u}from"../store/imageEventStore";export const INTERNAL_TEST_ID_PREFIX="buoy-internal";export function isInternalImage(t){return typeof t==="string"&&t.startsWith(INTERNAL_TEST_ID_PREFIX)}export function isNoiseUri(t){return t.includes("Libraries%2FLogBox")||t.includes("Libraries/LogBox")||t.includes("LogBoxImages")}export function classifyUri(t){if(t.startsWith("http://")||t.startsWith("https://"))return"network";if(t.startsWith("file://")||t.startsWith("asset://"))return"file";if(t.startsWith("data:"))return"data";return"other"}export function resolveSourceUri(t){if(t==null)return{uri:"",kind:"other"};if(Array.isArray(t)){return resolveSourceUri(t.length>0?t[0]:null)}if(typeof t==="string"){return{uri:t,kind:classifyUri(t)}}if(typeof t==="number"){try{const e=require("react-native");const n=e.Image?.resolveAssetSource?.(t);if(n?.uri)return{uri:n.uri,kind:"asset"}}catch{}return{uri:`asset:#${t}`,kind:"asset"}}if(typeof t==="object"){const e=t.uri;if(typeof e==="string"){const c=classifyUri(e);if(t.__packager_asset){return{uri:e,kind:"asset"}}return{uri:e,kind:c}}const n=t.width;if(typeof n==="number")return{uri:"(ImageRef)",kind:"other"}}return{uri:"",kind:"other"}}export function payloadOf(t){if(!t||typeof t!=="object")return{};const e=Object.getOwnPropertyDescriptor(t,"nativeEvent");const n=e&&!e.get?e.value:void 0;if(n&&typeof n==="object"){return n}return t}function k(t,e){const n=()=>{try{const c=require("react-native");const o=c.Image?.queryCache;if(typeof o!=="function"||!e)return;o([e]).then(m=>{const f=m?.[e];if(f){u(t,{cacheVerdict:f,cacheVerdictSource:"queryCache"})}}).catch(()=>{})}catch{}};setTimeout(n,600);setTimeout(()=>{const c=h(t);if(c&&c.cacheVerdictSource!=="queryCache")n()},3e3)}export class ImageInstanceTracker{recordId=null;uri=null;handlerCache=null;constructor(e){this.lib=e}getRecordId(){return this.recordId}noteA11y(e){if(this.recordId==null)return;const n=h(this.recordId);if(n&&n.hasAltText!==e){u(this.recordId,{hasAltText:e})}}syncSource(e){const{uri:n,kind:c}=resolveSourceUri(e);if(n===this.uri)return;this.uri=n;this.handlerCache=null;if(this.recordId!=null)b(this.recordId);if(!n||isNoiseUri(n)){this.recordId=null;return}const o=w({lib:this.lib,uri:n,sourceKind:c});this.recordId=o.id}unmount(){if(this.recordId!=null){u(this.recordId,{mounted:false});b(this.recordId)}}handlers(e){const n=[e.onLoadStart,e.onProgress,e.onLoad,e.onError,e.onLoadEnd,e.onDisplay,e.onLayout,this.recordId];const c=this.handlerCache;if(c&&c.key.length===n.length&&c.key.every((d,r)=>d===n[r])){return c.out}const o=this.recordId;const m=this.lib;const f=this.uri??"";const p={onLoadStart:d=>{if(o!=null){const r=h(o);const s=Date.now();const a=Math.max(r?.loadedAt??0,r?.erroredAt??0);const i=a>0&&s-a<300;u(o,{...i?{}:{status:"loading",error:void 0,errorCode:void 0,errorHeaders:void 0},startedAt:s,loadCount:(r?.loadCount??0)+1})}e.onLoadStart?.(d)},onProgress:d=>{if(o!=null){const r=payloadOf(d);u(o,{progressSeen:true,bytesLoaded:typeof r.loaded==="number"?r.loaded:void 0,bytesTotal:typeof r.total==="number"?r.total:void 0})}e.onProgress?.(d)},onLoad:d=>{if(o!=null){const r=payloadOf(d);const s=r.source??{};const a=Date.now();const i=h(o);const l=i?.startedAt!=null&&i.startedAt<=a&&i.startedAt>(i.loadedAt??i.createdAt-1)?i.startedAt:i?.loadedAt==null?i?.startedAt??i?.createdAt??a:a;const y=typeof s.width==="number"?s.width:0;const g=typeof s.height==="number"?s.height:0;u(o,{status:"loaded",loadedAt:a,durationMs:Math.max(0,a-l),error:void 0,errorCode:void 0,errorHeaders:void 0,intrinsic:y>0&&g>0?{width:y,height:g}:i?.intrinsic,cacheVerdict:typeof r.cacheType==="string"?r.cacheType:i?.cacheVerdict,cacheVerdictSource:typeof r.cacheType==="string"?"event":i?.cacheVerdictSource,mediaType:typeof s.mediaType==="string"||s.mediaType===null?s.mediaType:i?.mediaType,isAnimated:typeof s.isAnimated==="boolean"?s.isAnimated:i?.isAnimated});A(o);if(m==="rn")k(o,f)}e.onLoad?.(d)},onError:d=>{if(o!=null){const r=payloadOf(d);let s=typeof r.error==="string"?r.error:String(r.error?.message??"unknown error");const a=h(o);const i=I();const l=i.overrides.get(o);if(l?.source?.type==="error"){s="Forced error (Buoy Images simulation)";if(typeof r.error==="string")r.error=s}else if(i.globalModes.network==="offline"&&a?.sourceKind==="network"){s="Offline simulation (Buoy Images): network image blocked";if(typeof r.error==="string")r.error=s}u(o,{status:"error",erroredAt:Date.now(),error:s,errorCode:typeof r.responseCode==="number"?r.responseCode:void 0,errorHeaders:r.httpResponseHeaders&&typeof r.httpResponseHeaders==="object"?r.httpResponseHeaders:void 0});A(o)}e.onError?.(d)},onLayout:d=>{if(o!=null){const r=payloadOf(d).layout??{};const s=typeof r.width==="number"?r.width:0;const a=typeof r.height==="number"?r.height:0;if(s>0&&a>0){const i=h(o);const l=i?.layout;const y=l!=null&&i?.loadedAt!=null&&(Math.abs(l.width-s)>1||Math.abs(l.height-a)>1);u(o,{layout:{width:s,height:a},...y?{layoutShifts:(i?.layoutShifts??0)+1}:{}})}}e.onLayout?.(d)}};p.onLoadEnd=e.onLoadEnd?d=>e.onLoadEnd?.(d):void 0;if(this.lib==="expo"){p.onDisplay=d=>{if(o!=null)u(o,{displayedAt:Date.now()});e.onDisplay?.(d)}}this.handlerCache={key:n,out:p};return p}}