@aippy/vite-plugins 0.2.8 โ†’ 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ import { findProjectRoot as e } from "./utils/index.js";
2
+ import t from "path";
3
+ import { parse as n } from "@babel/parser";
4
+ import * as r from "esbuild";
5
+ import i from "fs/promises";
6
+ import a from "magic-string";
7
+ //#region src/aippy-tagger/util.ts
8
+ var o = /* @__PURE__ */ "object3D.audioListener.positionalAudio.mesh.batchedMesh.instancedMesh.scene.sprite.lOD.skinnedMesh.skeleton.bone.lineSegments.lineLoop.points.group.camera.perspectiveCamera.orthographicCamera.cubeCamera.arrayCamera.instancedBufferGeometry.bufferGeometry.boxBufferGeometry.circleBufferGeometry.coneBufferGeometry.cylinderBufferGeometry.dodecahedronBufferGeometry.extrudeBufferGeometry.icosahedronBufferGeometry.latheBufferGeometry.octahedronBufferGeometry.planeBufferGeometry.polyhedronBufferGeometry.ringBufferGeometry.shapeBufferGeometry.sphereBufferGeometry.tetrahedronBufferGeometry.torusBufferGeometry.torusKnotBufferGeometry.tubeBufferGeometry.wireframeGeometry.tetrahedronGeometry.octahedronGeometry.icosahedronGeometry.dodecahedronGeometry.polyhedronGeometry.tubeGeometry.torusKnotGeometry.torusGeometry.sphereGeometry.ringGeometry.planeGeometry.latheGeometry.shapeGeometry.extrudeGeometry.edgesGeometry.coneGeometry.cylinderGeometry.circleGeometry.boxGeometry.capsuleGeometry.material.shadowMaterial.spriteMaterial.rawShaderMaterial.shaderMaterial.pointsMaterial.meshPhysicalMaterial.meshStandardMaterial.meshPhongMaterial.meshToonMaterial.meshNormalMaterial.meshLambertMaterial.meshDepthMaterial.meshDistanceMaterial.meshBasicMaterial.meshMatcapMaterial.lineDashedMaterial.lineBasicMaterial.primitive.light.spotLightShadow.spotLight.pointLight.rectAreaLight.hemisphereLight.directionalLightShadow.directionalLight.ambientLight.lightShadow.ambientLightProbe.hemisphereLightProbe.lightProbe.spotLightHelper.skeletonHelper.pointLightHelper.hemisphereLightHelper.gridHelper.polarGridHelper.directionalLightHelper.cameraHelper.boxHelper.box3Helper.planeHelper.arrowHelper.axesHelper.texture.videoTexture.dataTexture.dataTexture3D.compressedTexture.cubeTexture.canvasTexture.depthTexture.raycaster.vector2.vector3.vector4.euler.matrix3.matrix4.quaternion.bufferAttribute.float16BufferAttribute.float32BufferAttribute.float64BufferAttribute.int8BufferAttribute.int16BufferAttribute.int32BufferAttribute.uint8BufferAttribute.uint16BufferAttribute.uint32BufferAttribute.instancedBufferAttribute.color.fog.fogExp2.shape.colorShiftMaterial".split("."), s = /* @__PURE__ */ "AsciiRenderer.Billboard.Clone.ComputedAttribute.Decal.Edges.Effects.GradientTexture.Image.MarchingCubes.Outlines.PositionalAudio.Sampler.ScreenSizer.ScreenSpace.Splat.Svg.Text.Text3D.Trail.CubeCamera.OrthographicCamera.PerspectiveCamera.CameraControls.FaceControls.KeyboardControls.MotionPathControls.PresentationControls.ScrollControls.DragControls.GizmoHelper.Grid.Helper.PivotControls.TransformControls.CubeTexture.Fbx.Gltf.Ktx2.Loader.Progress.ScreenVideoTexture.Texture.TrailTexture.VideoTexture.WebcamVideoTexture.CycleRaycast.DetectGPU.Example.FaceLandmarker.Fbo.Html.Select.SpriteAnimator.StatsGl.Stats.Trail.Wireframe.CurveModifier.AdaptiveDpr.AdaptiveEvents.BakeShadows.Bvh.Detailed.Instances.Merged.meshBounds.PerformanceMonitor.Points.Preload.Segments.Fisheye.Hud.Mask.MeshPortalMaterial.RenderCubeTexture.RenderTexture.View.MeshDiscardMaterial.MeshDistortMaterial.MeshReflectorMaterial.MeshRefractionMaterial.MeshTransmissionMaterial.MeshWobbleMaterial.PointMaterial.shaderMaterial.SoftShadows.CatmullRomLine.CubicBezierLine.Facemesh.Line.Mesh.QuadraticBezierLine.RoundedBox.ScreenQuad.AccumulativeShadows.Backdrop.BBAnchor.Bounds.CameraShake.Caustics.Center.Cloud.ContactShadows.Environment.Float.Lightformer.MatcapTexture.NormalTexture.RandomizedLight.Resize.ShadowAlpha.Shadow.Sky.Sparkles.SpotLightShadow.SpotLight.Stage.Stars.OrbitControls".split(".");
9
+ function c(e) {
10
+ return !o.includes(e) && !s.includes(e);
11
+ }
12
+ //#endregion
13
+ //#region src/aippy-tagger/index.ts
14
+ var l = /* @__PURE__ */ new Set([".jsx", ".tsx"]), u = e(), d = t.resolve(u, "./tailwind.config.ts"), f = t.resolve(u, "./src/tailwind.config.aippy.json"), p = t.resolve(u, "./.aippy.tailwind.config.js");
15
+ function m() {
16
+ let e = process.cwd(), r = {
17
+ totalFiles: 0,
18
+ processedFiles: 0,
19
+ totalElements: 0
20
+ };
21
+ return {
22
+ name: "vite-plugin-aippy-tagger",
23
+ enforce: "pre",
24
+ async transform(i, o) {
25
+ if (!l.has(t.extname(o)) || o.includes("node_modules")) return null;
26
+ r.totalFiles++;
27
+ let s = t.relative(e, o);
28
+ try {
29
+ let e = n(i, {
30
+ sourceType: "module",
31
+ plugins: ["jsx", "typescript"]
32
+ }), l = new a(i), u = 0, d = null, { walk: f } = await import("estree-walker");
33
+ return f(e, { enter(e) {
34
+ if (e.type === "JSXElement" && (d = e), e.type === "JSXOpeningElement") {
35
+ let n = e, r;
36
+ if (n.name.type === "JSXIdentifier") r = n.name.name;
37
+ else if (n.name.type === "JSXMemberExpression") {
38
+ let e = n.name;
39
+ r = `${e.object.name}.${e.property.name}`;
40
+ } else return;
41
+ if (r === "Fragment" || r === "React.Fragment") return;
42
+ let i = n.attributes.reduce((e, t) => (t.type === "JSXAttribute" && (t.value?.type === "StringLiteral" ? e[t.name.name] = t.value.value : t.value?.type === "JSXExpressionContainer" && t.value.expression.type === "StringLiteral" && (e[t.name.name] = t.value.expression.value)), e), {}), a = "";
43
+ d && d.children && (a = d.children.map((e) => e.type === "JSXText" ? e.value.trim() : e.type === "JSXExpressionContainer" && e.expression.type === "StringLiteral" ? e.expression.value : "").filter(Boolean).join(" ").trim());
44
+ let f = {};
45
+ a && (f.text = a), i.placeholder && (f.placeholder = i.placeholder), i.className && (f.className = i.className);
46
+ let p = n.loc?.start?.line ?? 0, m = n.loc?.start?.column ?? 0, h = `${s}:${p}:${m}`, g = t.basename(o);
47
+ if (c(r)) {
48
+ let e = ` data-component-path="${s}" data-component-line="${p}" data-component-file="${g}" data-component-name="${r}" data-component-content="${encodeURIComponent(JSON.stringify(f))}"`;
49
+ l.appendLeft(n.name.end ?? 0, ` data-aippy-id="${h}" data-aippy-name="${r}" ${e}`), u++;
50
+ }
51
+ }
52
+ } }), r.processedFiles++, r.totalElements += u, {
53
+ code: l.toString(),
54
+ map: l.generateMap({ hires: !0 })
55
+ };
56
+ } catch (e) {
57
+ return console.error(`Error processing file ${s}:`, e), r.processedFiles++, null;
58
+ }
59
+ },
60
+ async buildStart() {
61
+ try {
62
+ await h();
63
+ } catch (e) {
64
+ console.error("Error generating tailwind.config.aippy.json:", e);
65
+ }
66
+ },
67
+ configureServer(e) {
68
+ try {
69
+ e.watcher.add(d), e.watcher.on("change", async (e) => {
70
+ t.normalize(e) === t.normalize(d) && await h();
71
+ });
72
+ } catch (e) {
73
+ console.error("Error adding watcher:", e);
74
+ }
75
+ }
76
+ };
77
+ }
78
+ async function h() {
79
+ try {
80
+ await r.build({
81
+ entryPoints: [d],
82
+ outfile: p,
83
+ bundle: !0,
84
+ format: "esm",
85
+ banner: { js: "import { createRequire } from \"module\"; const require = createRequire(import.meta.url);" }
86
+ });
87
+ try {
88
+ let e = await import(p + "?update=" + Date.now());
89
+ if (!e || !e.default) throw console.error("Invalid Tailwind config structure:", e), Error("Invalid Tailwind config structure");
90
+ await i.writeFile(f, JSON.stringify(e.default, null, 2)), await i.unlink(p).catch(() => {});
91
+ } catch (e) {
92
+ throw console.error("Error processing config:", e), e;
93
+ }
94
+ } catch (e) {
95
+ throw console.error("Error in generateConfig:", e), e;
96
+ }
97
+ }
98
+ //#endregion
99
+ export { m as t };
@@ -1,301 +1,2 @@
1
- var E = Object.defineProperty;
2
- var I = (i, s, t) => s in i ? E(i, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[s] = t;
3
- var w = (i, s, t) => I(i, typeof s != "symbol" ? s + "" : s, t);
4
- import { promises as g } from "fs";
5
- import h from "path";
6
- import { parse as $ } from "@babel/parser";
7
- import F from "@babel/traverse";
8
- import * as p from "@babel/types";
9
- import A from "@babel/generator";
10
- import { generateConstantName as W, extractAssetsFromContent as S, processAssetURL as T } from "../utils/index.js";
11
- import { F as b, g as x, a as N, b as y } from "../file-scanner-DSr-Ek-8.js";
12
- function R(i, s) {
13
- const t = {};
14
- for (const [a, o] of s.entries())
15
- t[o] = a;
16
- return Array.from(i.values()).forEach((a) => {
17
- t[a.constantName] = a.originalUri;
18
- }), JSON.stringify(t, null, 2) + `
19
- `;
20
- }
21
- function O(i) {
22
- const s = /* @__PURE__ */ new Map();
23
- try {
24
- if (!i.trim())
25
- return s;
26
- const t = JSON.parse(i);
27
- for (const [e, a] of Object.entries(t))
28
- typeof a == "string" && s.set(a, e);
29
- s.size > 0 && console.log(`๐Ÿ“‹ Found ${s.size} existing constants in assets.json`);
30
- } catch (t) {
31
- console.warn("Warning: Failed to parse existing assets.json:", t);
32
- }
33
- return s;
34
- }
35
- function J(i, s, t, e) {
36
- const a = Array.from(t.values()).filter(
37
- (n) => s.has(n.originalUri)
38
- ).length, o = i - a;
39
- o > 0 ? console.log(`โœ… Generated ${i} asset constants (${o} new, ${a} reused) in ${e}`) : i > 0 ? console.log(`โœ… Generated ${i} asset constants (all reused from existing) in ${e}`) : console.log("โœ… No asset constants found");
40
- }
41
- const C = typeof F == "function" ? F : F.default, U = typeof A == "function" ? A : A.default;
42
- class P {
43
- constructor(s = {}) {
44
- w(this, "options");
45
- w(this, "assets", /* @__PURE__ */ new Map());
46
- w(this, "existingAssets", /* @__PURE__ */ new Map());
47
- w(this, "fileCache", new b());
48
- this.options = {
49
- extensions: [".png", ".jpg", ".jpeg", ".gif", ".svg", ".mp4", ".mp3", ".wav", ".ogg", ".webm"],
50
- srcDir: "src",
51
- outputFile: "src/config/assets.json",
52
- devMode: !1,
53
- ...s
54
- };
55
- }
56
- clearCache() {
57
- this.fileCache.clear();
58
- }
59
- generateConstantName(s) {
60
- const t = /* @__PURE__ */ new Set([
61
- ...Array.from(this.assets.values()).map((e) => e.constantName),
62
- ...Array.from(this.existingAssets.values())
63
- ]);
64
- return W(s, t);
65
- }
66
- async scanTsFile(s) {
67
- try {
68
- const t = await this.fileCache.read(s), e = [], a = S(t, "js", this.options.extensions), o = t.split(`
69
- `);
70
- return a.forEach((n) => {
71
- const r = this.generateConstantName(n), c = o.findIndex((u) => u.includes(n)) + 1;
72
- e.push({
73
- originalUri: n,
74
- constantName: r,
75
- filePath: s,
76
- line: c,
77
- column: 1
78
- });
79
- }), e;
80
- } catch (t) {
81
- return console.warn(`Warning: Failed to scan ${s}:`, t), [];
82
- }
83
- }
84
- async scanAllTsFiles() {
85
- const s = this.options.srcDir;
86
- try {
87
- const t = await x(s, [".ts", ".tsx"]);
88
- for (const e of t) {
89
- if (e.endsWith("assets.json") || e.endsWith("assets.ts"))
90
- continue;
91
- (await this.scanTsFile(e)).forEach((o) => {
92
- this.existingAssets.has(o.originalUri) && (o.constantName = this.existingAssets.get(o.originalUri));
93
- const n = o.originalUri;
94
- this.assets.has(n) || this.assets.set(n, o);
95
- });
96
- }
97
- } catch (t) {
98
- console.error("Error scanning TypeScript files:", t);
99
- }
100
- }
101
- async readExistingAssetsFile() {
102
- try {
103
- return await g.readFile(this.options.outputFile, "utf-8");
104
- } catch {
105
- return "";
106
- }
107
- }
108
- async parseExistingAssets() {
109
- const s = await this.readExistingAssetsFile();
110
- this.existingAssets = O(s);
111
- }
112
- async generateAssetsFile() {
113
- await this.parseExistingAssets(), await this.scanAllTsFiles();
114
- const s = R(this.assets, this.existingAssets), t = h.dirname(this.options.outputFile);
115
- await g.mkdir(t, { recursive: !0 }), await g.writeFile(this.options.outputFile, s, "utf-8"), await this.generateAssetsWrapper(), J(this.assets.size, this.existingAssets, this.assets, this.options.outputFile);
116
- }
117
- /**
118
- * ็”Ÿๆˆ assets.ts ๅŒ…่ฃ…ๆ–‡ไปถ
119
- * ่‡ชๅŠจ่ฐƒ็”จ window.getReplacedAssets ๅค„็† iOS ๅ›พ็‰‡ๆ›ฟๆข
120
- */
121
- async generateAssetsWrapper() {
122
- const s = this.options.outputFile.replace(/\.json$/, ".ts"), e = `// ๐ŸŽ Auto-generated wrapper for assets.json
123
- // This file handles iOS image replacement via asset-interceptor.js
124
- import assetsData from "./${h.basename(this.options.outputFile)}";
125
-
126
- // Batch process all asset URLs for potential replacements
127
- // sessionStorage may contain __aippy_asset_overrides__ with multiple image mappings
128
- (window as any).getReplacedAssets?.(assetsData);
129
-
130
- export default assetsData;
131
- `;
132
- await g.writeFile(s, e, "utf-8"), console.log(` โœ“ Generated assets wrapper: ${h.relative(process.cwd(), s)}`);
133
- }
134
- getAssets() {
135
- return Array.from(this.assets.values());
136
- }
137
- async replaceUrisInFile(s, t) {
138
- try {
139
- const e = await this.fileCache.read(s), a = $(e, {
140
- sourceType: "module",
141
- plugins: ["typescript", "jsx", "decorators-legacy"]
142
- });
143
- let o = !1;
144
- if (C(a, {
145
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
146
- StringLiteral: (l) => {
147
- const m = l.node.value, v = T(m);
148
- if (t.has(v)) {
149
- const D = t.get(v), j = p.memberExpression(
150
- p.identifier("assetsData"),
151
- p.identifier(D)
152
- );
153
- l.parent && p.isJSXAttribute(l.parent) ? l.replaceWith(p.jsxExpressionContainer(j)) : l.replaceWith(j), o = !0;
154
- }
155
- }
156
- }), !o)
157
- return;
158
- const n = this.options.outputFile.replace(/\.json$/, ".ts"), r = N(n, this.options.srcDir), c = y(s, n), d = y(s, this.options.outputFile) + ".json";
159
- let u = !1;
160
- if (C(a, {
161
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
162
- ImportDeclaration: (l) => {
163
- const m = l.node.source.value;
164
- (m === r || m === c || m === d) && (u = !0, l.stop());
165
- }
166
- }), !u) {
167
- const l = p.importDeclaration(
168
- [p.importDefaultSpecifier(p.identifier("assetsData"))],
169
- p.stringLiteral(r)
170
- );
171
- a.program.body.unshift(l);
172
- }
173
- const f = U(a, {
174
- retainLines: !1,
175
- comments: !0,
176
- compact: !1
177
- }, e);
178
- await g.writeFile(s, f.code, "utf-8"), this.fileCache.invalidate(s), console.log(` โœ“ Replaced URIs in ${h.relative(process.cwd(), s)}`);
179
- } catch (e) {
180
- console.warn(`Warning: Failed to replace URIs in ${s}:`, e);
181
- }
182
- }
183
- async replaceAllUris() {
184
- const s = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Set();
185
- for (const e of this.assets.values())
186
- s.set(e.originalUri, e.constantName), t.add(e.filePath);
187
- for (const e of t)
188
- await this.replaceUrisInFile(e, s);
189
- }
190
- async cleanupUnusedConstants() {
191
- try {
192
- const s = await this.readExistingAssetsFile();
193
- if (!s.trim())
194
- return;
195
- const t = /* @__PURE__ */ new Map();
196
- try {
197
- const n = JSON.parse(s);
198
- for (const [r, c] of Object.entries(n))
199
- typeof c == "string" && t.set(r, c);
200
- } catch (n) {
201
- console.warn("Warning: Failed to parse assets.json:", n);
202
- return;
203
- }
204
- if (t.size === 0)
205
- return;
206
- const e = /* @__PURE__ */ new Set(), a = await x(this.options.srcDir, [".ts", ".tsx"]);
207
- for (const n of a)
208
- if (!(n.endsWith("assets.json") || n.endsWith("assets.ts")))
209
- try {
210
- const r = await this.fileCache.read(n);
211
- for (const c of t.keys())
212
- r.includes(c) && e.add(c);
213
- } catch (r) {
214
- console.warn(`Warning: Failed to read ${n}:`, r);
215
- }
216
- const o = [];
217
- for (const n of t.keys())
218
- e.has(n) || o.push(n);
219
- if (o.length > 0) {
220
- console.log(`๐Ÿงน Removing ${o.length} unused constant(s):`), o.forEach((r) => {
221
- console.log(` - ${r}`);
222
- });
223
- const n = [];
224
- for (const r of o) {
225
- const c = t.get(r);
226
- c && n.push(c);
227
- }
228
- for (const r of n)
229
- this.assets.delete(r);
230
- } else
231
- console.log("โœ… All constants are in use");
232
- } catch (s) {
233
- console.warn("Warning: Failed to cleanup unused constants:", s);
234
- }
235
- }
236
- /**
237
- * ๐ŸŽ ๅ‡็บง็Žฐๆœ‰็š„็›ธๅฏน่ทฏๅพ„ๆˆ– .json ๅฏผๅ…ฅไธบ @/ ๅˆซๅ็š„ .ts ๅŒ…่ฃ…ๆ–‡ไปถๅฏผๅ…ฅ
238
- */
239
- async upgradeJsonImportsToTs() {
240
- const s = this.options.outputFile.replace(/\.json$/, ".ts"), t = N(s, this.options.srcDir), e = await x(this.options.srcDir, [".ts", ".tsx"]);
241
- let a = 0;
242
- for (const o of e)
243
- if (!(o.endsWith("assets.ts") || o.endsWith("assets.json")))
244
- try {
245
- const n = await this.fileCache.read(o), r = y(o, this.options.outputFile) + ".json", c = y(o, s);
246
- if (!n.includes(r) && !n.includes(c))
247
- continue;
248
- const d = $(n, {
249
- sourceType: "module",
250
- plugins: ["typescript", "jsx", "decorators-legacy"]
251
- });
252
- let u = !1;
253
- if (C(d, {
254
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
255
- ImportDeclaration: (f) => {
256
- const l = f.node.source.value;
257
- (l === r || l === c) && (f.node.source.value = t, u = !0);
258
- }
259
- }), u) {
260
- const f = U(d, {
261
- retainLines: !1,
262
- comments: !0,
263
- compact: !1
264
- }, n);
265
- await g.writeFile(o, f.code, "utf-8"), this.fileCache.invalidate(o), console.log(` โœ“ Upgraded import in ${h.relative(process.cwd(), o)} โ†’ ${t}`), a++;
266
- }
267
- } catch (n) {
268
- console.warn(`Warning: Failed to upgrade imports in ${o}:`, n);
269
- }
270
- a > 0 && console.log(`โœ… Upgraded ${a} file(s) to use ${t}`);
271
- }
272
- }
273
- function X(i = {}) {
274
- return {
275
- name: "vite-plugin-asset-constants",
276
- apply: "build",
277
- // Ensure this plugin runs before other plugins to modify source files before build
278
- enforce: "pre",
279
- async buildStart() {
280
- if (i.devMode)
281
- try {
282
- const s = new P(i);
283
- await s.generateAssetsFile();
284
- const t = s.getAssets();
285
- t.length > 0 && (console.log(`๐Ÿ“ฆ Found ${t.length} asset references:`), t.forEach((e) => {
286
- console.log(` ${e.constantName} = '${e.originalUri}' (${h.relative(process.cwd(), e.filePath)}:${e.line})`);
287
- }), console.log(`
288
- ๐Ÿ”„ Replacing URIs with constants...`), await s.replaceAllUris(), console.log("โœ… URI replacement completed!")), console.log(`
289
- ๐Ÿงน Checking for unused constants...`), await s.cleanupUnusedConstants(), await s.generateAssetsFile(), console.log(`
290
- ๐Ÿ”„ Upgrading assets.json imports to assets.ts...`), await s.upgradeJsonImportsToTs(), console.log(`โœ… Asset constants finalized!
291
- `), s.clearCache();
292
- } catch (s) {
293
- console.error("โŒ Error in asset constants plugin:", s);
294
- }
295
- }
296
- };
297
- }
298
- export {
299
- X as assetConstantsPlugin,
300
- X as default
301
- };
1
+ import { t as e } from "../asset-constants-BvKclVVI.js";
2
+ export { e as assetConstantsPlugin, e as default };
@@ -0,0 +1,252 @@
1
+ import { extractAssetsFromContent as e, generateConstantName as t, processAssetURL as n } from "./utils/index.js";
2
+ import { a as r, i, n as a, r as o, t as s } from "./file-scanner-DT-LbrCa.js";
3
+ import { promises as c } from "fs";
4
+ import l from "path";
5
+ import { parse as u } from "@babel/parser";
6
+ import d from "@babel/traverse";
7
+ import * as f from "@babel/types";
8
+ import p from "@babel/generator";
9
+ //#region src/asset-constants/generator-utils.ts
10
+ function m(e, t) {
11
+ let n = {};
12
+ for (let [e, r] of t.entries()) n[r] = e;
13
+ return Array.from(e.values()).forEach((e) => {
14
+ n[e.constantName] = e.originalUri;
15
+ }), JSON.stringify(n, null, 2) + "\n";
16
+ }
17
+ function h(e) {
18
+ let t = /* @__PURE__ */ new Map();
19
+ try {
20
+ if (!e.trim()) return t;
21
+ let n = JSON.parse(e);
22
+ for (let [e, r] of Object.entries(n)) typeof r == "string" && t.set(r, e);
23
+ t.size > 0 && console.log(`๐Ÿ“‹ Found ${t.size} existing constants in assets.json`);
24
+ } catch (e) {
25
+ console.warn("Warning: Failed to parse existing assets.json:", e);
26
+ }
27
+ return t;
28
+ }
29
+ function g(e, t, n, r) {
30
+ let i = Array.from(n.values()).filter((e) => t.has(e.originalUri)).length, a = e - i;
31
+ console.log(a > 0 ? `โœ… Generated ${e} asset constants (${a} new, ${i} reused) in ${r}` : e > 0 ? `โœ… Generated ${e} asset constants (all reused from existing) in ${r}` : "โœ… No asset constants found");
32
+ }
33
+ //#endregion
34
+ //#region src/asset-constants/index.ts
35
+ var _ = typeof d == "function" ? d : d.default, v = typeof p == "function" ? p : p.default, y = class {
36
+ constructor(e = {}) {
37
+ r(this, "options", void 0), r(this, "assets", /* @__PURE__ */ new Map()), r(this, "existingAssets", /* @__PURE__ */ new Map()), r(this, "fileCache", new s()), this.options = {
38
+ extensions: [
39
+ ".png",
40
+ ".jpg",
41
+ ".jpeg",
42
+ ".gif",
43
+ ".svg",
44
+ ".mp4",
45
+ ".mp3",
46
+ ".wav",
47
+ ".ogg",
48
+ ".webm"
49
+ ],
50
+ srcDir: "src",
51
+ outputFile: "src/config/assets.json",
52
+ devMode: !1,
53
+ ...e
54
+ };
55
+ }
56
+ clearCache() {
57
+ this.fileCache.clear();
58
+ }
59
+ generateConstantName(e) {
60
+ let n = /* @__PURE__ */ new Set([...Array.from(this.assets.values()).map((e) => e.constantName), ...Array.from(this.existingAssets.values())]);
61
+ return t(e, n);
62
+ }
63
+ async scanTsFile(t) {
64
+ try {
65
+ let n = await this.fileCache.read(t), r = [], i = e(n, "js", this.options.extensions), a = n.split("\n");
66
+ return i.forEach((e) => {
67
+ let n = this.generateConstantName(e), i = a.findIndex((t) => t.includes(e)) + 1;
68
+ r.push({
69
+ originalUri: e,
70
+ constantName: n,
71
+ filePath: t,
72
+ line: i,
73
+ column: 1
74
+ });
75
+ }), r;
76
+ } catch (e) {
77
+ return console.warn(`Warning: Failed to scan ${t}:`, e), [];
78
+ }
79
+ }
80
+ async scanAllTsFiles() {
81
+ let e = this.options.srcDir;
82
+ try {
83
+ let t = await o(e, [".ts", ".tsx"]);
84
+ for (let e of t) e.endsWith("assets.json") || e.endsWith("assets.ts") || (await this.scanTsFile(e)).forEach((e) => {
85
+ this.existingAssets.has(e.originalUri) && (e.constantName = this.existingAssets.get(e.originalUri));
86
+ let t = e.originalUri;
87
+ this.assets.has(t) || this.assets.set(t, e);
88
+ });
89
+ } catch (e) {
90
+ console.error("Error scanning TypeScript files:", e);
91
+ }
92
+ }
93
+ async readExistingAssetsFile() {
94
+ try {
95
+ return await c.readFile(this.options.outputFile, "utf-8");
96
+ } catch {
97
+ return "";
98
+ }
99
+ }
100
+ async parseExistingAssets() {
101
+ let e = await this.readExistingAssetsFile();
102
+ this.existingAssets = h(e);
103
+ }
104
+ async generateAssetsFile() {
105
+ await this.parseExistingAssets(), await this.scanAllTsFiles();
106
+ let e = m(this.assets, this.existingAssets), t = l.dirname(this.options.outputFile);
107
+ await c.mkdir(t, { recursive: !0 }), await c.writeFile(this.options.outputFile, e, "utf-8"), await this.generateAssetsWrapper(), g(this.assets.size, this.existingAssets, this.assets, this.options.outputFile);
108
+ }
109
+ async generateAssetsWrapper() {
110
+ let e = this.options.outputFile.replace(/\.json$/, ".ts"), t = `// ๐ŸŽ Auto-generated wrapper for assets.json
111
+ // This file handles iOS image replacement via asset-interceptor.js
112
+ import assetsData from "./${l.basename(this.options.outputFile)}";
113
+
114
+ // Batch process all asset URLs for potential replacements
115
+ // sessionStorage may contain __aippy_asset_overrides__ with multiple image mappings
116
+ (window as any).getReplacedAssets?.(assetsData);
117
+
118
+ export default assetsData;
119
+ `;
120
+ await c.writeFile(e, t, "utf-8"), console.log(` โœ“ Generated assets wrapper: ${l.relative(process.cwd(), e)}`);
121
+ }
122
+ getAssets() {
123
+ return Array.from(this.assets.values());
124
+ }
125
+ async replaceUrisInFile(e, t) {
126
+ try {
127
+ let r = await this.fileCache.read(e), o = u(r, {
128
+ sourceType: "module",
129
+ plugins: [
130
+ "typescript",
131
+ "jsx",
132
+ "decorators-legacy"
133
+ ]
134
+ }), s = !1;
135
+ if (_(o, { StringLiteral: (e) => {
136
+ let r = e.node.value, i = n(r);
137
+ if (t.has(i)) {
138
+ let n = t.get(i), r = f.memberExpression(f.identifier("assetsData"), f.identifier(n));
139
+ e.parent && f.isJSXAttribute(e.parent) ? e.replaceWith(f.jsxExpressionContainer(r)) : e.replaceWith(r), s = !0;
140
+ }
141
+ } }), !s) return;
142
+ let d = this.options.outputFile.replace(/\.json$/, ".ts"), p = a(d, this.options.srcDir), m = i(e, d), h = i(e, this.options.outputFile) + ".json", g = !1;
143
+ if (_(o, { ImportDeclaration: (e) => {
144
+ let t = e.node.source.value;
145
+ (t === p || t === m || t === h) && (g = !0, e.stop());
146
+ } }), !g) {
147
+ let e = f.importDeclaration([f.importDefaultSpecifier(f.identifier("assetsData"))], f.stringLiteral(p));
148
+ o.program.body.unshift(e);
149
+ }
150
+ let y = v(o, {
151
+ retainLines: !1,
152
+ comments: !0,
153
+ compact: !1
154
+ }, r);
155
+ await c.writeFile(e, y.code, "utf-8"), this.fileCache.invalidate(e), console.log(` โœ“ Replaced URIs in ${l.relative(process.cwd(), e)}`);
156
+ } catch (t) {
157
+ console.warn(`Warning: Failed to replace URIs in ${e}:`, t);
158
+ }
159
+ }
160
+ async replaceAllUris() {
161
+ let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Set();
162
+ for (let n of this.assets.values()) e.set(n.originalUri, n.constantName), t.add(n.filePath);
163
+ for (let n of t) await this.replaceUrisInFile(n, e);
164
+ }
165
+ async cleanupUnusedConstants() {
166
+ try {
167
+ let e = await this.readExistingAssetsFile();
168
+ if (!e.trim()) return;
169
+ let t = /* @__PURE__ */ new Map();
170
+ try {
171
+ let n = JSON.parse(e);
172
+ for (let [e, r] of Object.entries(n)) typeof r == "string" && t.set(e, r);
173
+ } catch (e) {
174
+ console.warn("Warning: Failed to parse assets.json:", e);
175
+ return;
176
+ }
177
+ if (t.size === 0) return;
178
+ let n = /* @__PURE__ */ new Set(), r = await o(this.options.srcDir, [".ts", ".tsx"]);
179
+ for (let e of r) if (!(e.endsWith("assets.json") || e.endsWith("assets.ts"))) try {
180
+ let r = await this.fileCache.read(e);
181
+ for (let e of t.keys()) r.includes(e) && n.add(e);
182
+ } catch (t) {
183
+ console.warn(`Warning: Failed to read ${e}:`, t);
184
+ }
185
+ let i = [];
186
+ for (let e of t.keys()) n.has(e) || i.push(e);
187
+ if (i.length > 0) {
188
+ console.log(`๐Ÿงน Removing ${i.length} unused constant(s):`), i.forEach((e) => {
189
+ console.log(` - ${e}`);
190
+ });
191
+ let e = [];
192
+ for (let n of i) {
193
+ let r = t.get(n);
194
+ r && e.push(r);
195
+ }
196
+ for (let t of e) this.assets.delete(t);
197
+ } else console.log("โœ… All constants are in use");
198
+ } catch (e) {
199
+ console.warn("Warning: Failed to cleanup unused constants:", e);
200
+ }
201
+ }
202
+ async upgradeJsonImportsToTs() {
203
+ let e = this.options.outputFile.replace(/\.json$/, ".ts"), t = a(e, this.options.srcDir), n = await o(this.options.srcDir, [".ts", ".tsx"]), r = 0;
204
+ for (let a of n) if (!(a.endsWith("assets.ts") || a.endsWith("assets.json"))) try {
205
+ let n = await this.fileCache.read(a), o = i(a, this.options.outputFile) + ".json", s = i(a, e);
206
+ if (!n.includes(o) && !n.includes(s)) continue;
207
+ let d = u(n, {
208
+ sourceType: "module",
209
+ plugins: [
210
+ "typescript",
211
+ "jsx",
212
+ "decorators-legacy"
213
+ ]
214
+ }), f = !1;
215
+ if (_(d, { ImportDeclaration: (e) => {
216
+ let n = e.node.source.value;
217
+ (n === o || n === s) && (e.node.source.value = t, f = !0);
218
+ } }), f) {
219
+ let e = v(d, {
220
+ retainLines: !1,
221
+ comments: !0,
222
+ compact: !1
223
+ }, n);
224
+ await c.writeFile(a, e.code, "utf-8"), this.fileCache.invalidate(a), console.log(` โœ“ Upgraded import in ${l.relative(process.cwd(), a)} โ†’ ${t}`), r++;
225
+ }
226
+ } catch (e) {
227
+ console.warn(`Warning: Failed to upgrade imports in ${a}:`, e);
228
+ }
229
+ r > 0 && console.log(`โœ… Upgraded ${r} file(s) to use ${t}`);
230
+ }
231
+ };
232
+ function b(e = {}) {
233
+ return {
234
+ name: "vite-plugin-asset-constants",
235
+ apply: "build",
236
+ enforce: "pre",
237
+ async buildStart() {
238
+ if (e.devMode) try {
239
+ let t = new y(e);
240
+ await t.generateAssetsFile();
241
+ let n = t.getAssets();
242
+ n.length > 0 && (console.log(`๐Ÿ“ฆ Found ${n.length} asset references:`), n.forEach((e) => {
243
+ console.log(` ${e.constantName} = '${e.originalUri}' (${l.relative(process.cwd(), e.filePath)}:${e.line})`);
244
+ }), console.log("\n๐Ÿ”„ Replacing URIs with constants..."), await t.replaceAllUris(), console.log("โœ… URI replacement completed!")), console.log("\n๐Ÿงน Checking for unused constants..."), await t.cleanupUnusedConstants(), await t.generateAssetsFile(), console.log("\n๐Ÿ”„ Upgrading assets.json imports to assets.ts..."), await t.upgradeJsonImportsToTs(), console.log("โœ… Asset constants finalized!\n"), t.clearCache();
245
+ } catch (e) {
246
+ console.error("โŒ Error in asset constants plugin:", e);
247
+ }
248
+ }
249
+ };
250
+ }
251
+ //#endregion
252
+ export { b as t };