@milofly/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tema.mjs ADDED
@@ -0,0 +1,423 @@
1
+ // `milofly theme …` — kompozisyon temasının yerel döngüsü. Tema geliştiricinin GELİŞTİRME MAĞAZASINDA yaşar (Web Yönetimi ile düzenlenir);
2
+ // CLI onu manifest olarak klasöre çeker, denetletir, sürüm olarak geri gönderip aynı mağazaya kurar. Gerçek mağazaya dokunamaz: her uç
3
+ // geliştiricinin kendi geliştirme mağazasını ister. Kurallar sunucudadır (sürüm yazıcısı ve kurulumla aynı doğrulayıcı).
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, mkdirSync, readFileSync, watch, writeFileSync } from "node:fs";
6
+ import { join, resolve } from "node:path";
7
+ import { assetFilePath, canonicalJson, checkManifestShape, PROJECT_LAYOUT, readThemeProject, writeThemeProject } from "@milofly/theme-sdk";
8
+ import { istemci } from "./oturum.mjs";
9
+ import { kalin, kirmizi, sari, sec, sor, soluk, uyar, yaz, yesil } from "./arayuz.mjs";
10
+
11
+ const AYAR = "milofly.theme.json";
12
+ const DURUM = join(".milofly", "state.json");
13
+ const ILK_SURUM = "0.1.0";
14
+
15
+ function proje(secenekler) {
16
+ const kok = resolve(secenekler.path ?? ".");
17
+ const dosya = join(kok, AYAR);
18
+ if (!existsSync(dosya)) throw new Error(`${AYAR} not found in ${kok}. Run "milofly theme init" first (or pass --path).`);
19
+ return { kok, ayar: JSON.parse(readFileSync(dosya, "utf8")) };
20
+ }
21
+
22
+ /** milofly.theme.json'a yazar; öteki alanlar korunur. */
23
+ function ayarYaz(kok, ayar) {
24
+ writeFileSync(join(kok, AYAR), JSON.stringify(ayar, null, 2) + "\n");
25
+ }
26
+
27
+ function durumOku(kok) {
28
+ const d = join(kok, DURUM);
29
+ return existsSync(d) ? JSON.parse(readFileSync(d, "utf8")) : {};
30
+ }
31
+
32
+ function durumYaz(kok, durum) {
33
+ mkdirSync(join(kok, ".milofly"), { recursive: true });
34
+ writeFileSync(join(kok, DURUM), JSON.stringify(durum, null, 2) + "\n");
35
+ }
36
+
37
+ /**
38
+ * Yayıncı anahtarı (`PUT /api/dev/publisher`; kural sahibi API'deki DevYayinciKimligi): bir kez seçilir, sonra değişmez; tema paketi
39
+ * anahtarının `{yayıncı}/` kesimi ve uygulama anahtarının `app.{yayıncı}.` kesimidir. Seçilmişse onu döndürür; seçilmemişse
40
+ * `istenen` ya da (etkileşimli terminalde) sorulup onaylanan değer yazılır.
41
+ */
42
+ async function yayinciAnahtari(c, istenen) {
43
+ const d = await c.cagir("/api/dev/publisher");
44
+ if (d.publisherKey) return d.publisherKey;
45
+ if (istenen === undefined && !process.stdin.isTTY)
46
+ throw new Error('You have no publisher key yet. Choose it once: "milofly theme publisher <key>" (it cannot be changed later).');
47
+ if (d.appSegments?.length) yaz(soluk(`Your apps already use: ${d.appSegments.join(", ")} — the publisher key must be one of them.`));
48
+ const anahtar = (istenen ?? (await sor(`Publisher key ${soluk("(3–40: a-z, 0-9, -; cannot be changed later)")}`, { varsayilan: d.suggested ?? undefined })))
49
+ .trim().toLowerCase();
50
+ if (!anahtar) throw new Error('Publisher key is required. Run "milofly theme publisher <key>".');
51
+ if (istenen === undefined && (await sor(`Use ${kalin(anahtar)} for good? (yes/no)`, { varsayilan: "no" })).toLowerCase() !== "yes")
52
+ throw new Error("Publisher key was not saved.");
53
+ const r = await c.cagir("/api/dev/publisher", { method: "PUT", govde: { publisherKey: anahtar } });
54
+ yaz(`${yesil("✔")} Publisher key: ${kalin(r.publisherKey)}`);
55
+ return r.publisherKey;
56
+ }
57
+
58
+ /** `theme publisher [key]` — yayıncı anahtarını gösterir; seçilmemişse seçer (portaldakiyle aynı uç). */
59
+ export async function publisher(secenekler, [istenen]) {
60
+ const c = await istemci(secenekler);
61
+ const d = await c.cagir("/api/dev/publisher");
62
+ if (d.publisherKey) {
63
+ if (istenen && istenen.trim().toLowerCase() !== d.publisherKey)
64
+ throw new Error(`Your publisher key is already ${d.publisherKey}; it cannot be changed.`);
65
+ return yaz(`Publisher key: ${kalin(d.publisherKey)}`);
66
+ }
67
+ await yayinciAnahtari(c, istenen);
68
+ }
69
+
70
+ /** `theme init [dir]` */
71
+ export async function init(secenekler, [hedef]) {
72
+ const c = await istemci(secenekler);
73
+ const yayinci = await yayinciAnahtari(c, undefined);
74
+
75
+ const { stores } = await c.cagir("/api/dev/stores");
76
+ if (stores.length === 0) throw new Error("You have no development store. Create one in the developer portal › Test stores.");
77
+ const magaza = secenekler.store
78
+ ? stores.find((s) => String(s.storeId) === String(secenekler.store)) ?? hataAt(`Development store ${secenekler.store} not found.`)
79
+ : await sec("Development store", stores, (s) => `${s.storeName} ${soluk(`(${s.storeCode}, #${s.storeId})`)}`);
80
+
81
+ const { themes } = await c.cagir(`/api/dev/theme-packages/source-themes?storeId=${magaza.storeId}`);
82
+ const tema = secenekler.theme
83
+ ? themes.find((t) => String(t.id) === String(secenekler.theme)) ?? hataAt(`Theme ${secenekler.theme} not found in ${magaza.storeCode}.`)
84
+ : await sec("Theme to start from", themes, (t) => `${t.name} ${soluk(`(#${t.id}, ${t.languageCode}${t.status === "A" ? ", live" : ""})`)}`);
85
+
86
+ const oneri = String(tema.name).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "theme";
87
+ const ad = secenekler.name ?? (await sor(`Package name ${soluk(`(key: ${yayinci}/<name>)`)}`, { varsayilan: oneri }));
88
+ const kok = resolve(hedef ?? ad);
89
+ if (existsSync(join(kok, AYAR))) throw new Error(`${join(kok, AYAR)} already exists.`);
90
+ mkdirSync(kok, { recursive: true });
91
+ writeFileSync(join(kok, AYAR), JSON.stringify({ storeId: magaza.storeId, storeCode: magaza.storeCode, sourceThemeId: tema.id, name: ad }, null, 2) + "\n");
92
+ writeFileSync(join(kok, ".gitignore"), ".milofly/\ndist/\n");
93
+ writeFileSync(join(kok, "README.md"),
94
+ `# ${yayinci}/${ad}\n\nMilofly composition theme. Commands (run in this folder):\n\n` +
95
+ "```\nmilofly theme pull # bring the theme from your development store\nmilofly theme check # validate with the Milofly rules\n" +
96
+ "milofly theme dev # push every change to your development store and open it\nmilofly theme push # write the version in theme/package.json\n" +
97
+ "milofly theme submit # send that version to review\n```\n\nDocs: https://developer.milofly.com/docs/cli\n");
98
+ await pull({ ...secenekler, path: kok }, [], c);
99
+ yaz(`\n${yesil("✔")} ${kalin(`${yayinci}/${ad}`)} is ready in ${kok}`);
100
+ yaz(` Next: fill the catalog name and description in ${PROJECT_LAYOUT.package}, then ${kalin("milofly theme check")}.`);
101
+ }
102
+
103
+ function hataAt(m) {
104
+ throw new Error(m);
105
+ }
106
+
107
+ /**
108
+ * Parça eşleme: sayfada `sayfa anahtarı + bileşen anahtarı + aynı anahtarın kaçıncı geçişi`, yerleşimde `yerleşim türü + bileşen anahtarı
109
+ * + kaçıncı geçiş` (API'nin DevTemaPaketleri.DilBloklariniTasi'siyle aynı kural). Araya başka bileşen eklemek eşlemeyi bozmaz.
110
+ */
111
+ function parcalar(tema) {
112
+ const harita = new Map();
113
+ const ekle = (kapsam, liste) => {
114
+ const sayac = new Map();
115
+ for (const p of liste ?? []) {
116
+ const n = (sayac.get(p.componentKey) ?? 0) + 1;
117
+ sayac.set(p.componentKey, n);
118
+ harita.set(`${kapsam}.${p.componentKey}#${n}`, p);
119
+ }
120
+ };
121
+ for (const sayfa of tema?.pages ?? []) ekle(`page:${sayfa.systemPageKey}`, sayfa.components);
122
+ for (const tur of new Set((tema?.layouts ?? []).map((l) => l.layoutType)))
123
+ ekle(`layout:${tur}`, tema.layouts.filter((l) => l.layoutType === tur));
124
+ return harita;
125
+ }
126
+
127
+ /**
128
+ * Yerel dil metinleri çekilen temayı EZMEZ (27.11.2026, Faz 1). Mağaza dilinin metni mağazadan gelir (Web Yönetimi'nde düzenlenen odur);
129
+ * öteki dillerde yereldeki blok kazanır (gönderilmemiş çeviri yereldedir), yerelde yoksa sunucunun paket sürümünden taşıdığı kalır.
130
+ * Mağazada metni olmayan ya da artık bulunmayan parçanın yerel çevirisi uyarıyla düşer (dil simetrisi; değer uydurulmaz).
131
+ */
132
+ function yerelDilleriKoru(sunucu, yerel, magazaDili) {
133
+ const sunucuParcalar = parcalar(sunucu.theme);
134
+ const dusen = [];
135
+ for (const [anahtar, y] of parcalar(yerel.theme)) {
136
+ const yerelBlok = y.defaultsByLang;
137
+ if (!yerelBlok || typeof yerelBlok !== "object") continue;
138
+ const digerDiller = Object.keys(yerelBlok).filter((d) => d.toLowerCase() !== String(magazaDili).toLowerCase());
139
+ if (digerDiller.length === 0) continue;
140
+ const s = sunucuParcalar.get(anahtar);
141
+ if (!s || !s.defaultsByLang || typeof s.defaultsByLang !== "object") {
142
+ dusen.push(`${anahtar} (${digerDiller.join(", ")})`);
143
+ continue;
144
+ }
145
+ for (const d of digerDiller) s.defaultsByLang[d] = yerelBlok[d];
146
+ }
147
+ return dusen;
148
+ }
149
+
150
+ /**
151
+ * `theme pull [--theme <id>]` — geliştirme mağazasındaki temayı klasöre yazar. İzlenen tema milofly.theme.json'daki `sourceThemeId`'dir;
152
+ * `theme push` onu kurduğu temaya çevirir, `--theme` başka bir temaya çevirir. Yerel paket bilgisi (sürüm, kart metni, diller, varsayılan
153
+ * dil) ve mağaza dili dışındaki yerel çeviriler korunur (`yerelDilleriKoru`).
154
+ */
155
+ export async function pull(secenekler, _, c0) {
156
+ const { kok, ayar } = proje(secenekler);
157
+ const c = c0 ?? (await istemci(secenekler));
158
+ if (secenekler.theme && String(secenekler.theme) !== String(ayar.sourceThemeId)) {
159
+ if (!/^\d+$/.test(String(secenekler.theme))) throw new Error(`--theme must be a theme number (got "${secenekler.theme}").`);
160
+ ayar.sourceThemeId = Number(secenekler.theme);
161
+ ayarYaz(kok, ayar);
162
+ yaz(soluk(`Now following theme #${ayar.sourceThemeId} (${AYAR}).`));
163
+ }
164
+ const r = await c.cagir(`/api/dev/theme-packages/source-themes/${ayar.sourceThemeId}/manifest?storeId=${ayar.storeId}` +
165
+ `&name=${encodeURIComponent(ayar.name)}`);
166
+ const manifest = r.manifest;
167
+ const paketDosyasi = join(kok, PROJECT_LAYOUT.package);
168
+ let dusen = [];
169
+ if (existsSync(paketDosyasi)) {
170
+ // Yerel proje bozuksa üzerine yazılmaz: önce düzeltilir (yerel çeviriler kaybolmasın).
171
+ const yerel = await readThemeProject(kok);
172
+ manifest.version = yerel.version || ILK_SURUM;
173
+ if (yerel.catalogTranslations && Object.keys(yerel.catalogTranslations).length > 0) manifest.catalogTranslations = yerel.catalogTranslations;
174
+ const diller = [...(yerel.supportedLanguageCodes ?? [])];
175
+ for (const d of manifest.supportedLanguageCodes ?? []) if (!diller.some((x) => x.toLowerCase() === d.toLowerCase())) diller.push(d);
176
+ if (diller.length > 0) manifest.supportedLanguageCodes = diller;
177
+ if (yerel.defaultLanguageCode) manifest.defaultLanguageCode = yerel.defaultLanguageCode;
178
+ dusen = yerelDilleriKoru(manifest, yerel, r.storeLanguageCode);
179
+ } else {
180
+ manifest.version = ILK_SURUM;
181
+ }
182
+ const yazilan = await writeThemeProject(kok, manifest);
183
+ yaz(`${yesil("✔")} Pulled ${ayar.storeCode ?? `store #${ayar.storeId}`} › theme #${ayar.sourceThemeId}: ${manifest.theme.pages.length} pages, ` +
184
+ `${manifest.theme.layouts.length} layouts, ${manifest.theme.settings.length} settings (${yazilan.length} files).`);
185
+ yaz(soluk(` Text in ${r.storeLanguageCode} comes from the store` +
186
+ (r.sourceRelease ? `; ${r.releaseLanguageCodes?.length ? r.releaseLanguageCodes.join(", ") : "no other language"} from release ${r.sourceRelease}` : "") +
187
+ `; languages: ${manifest.supportedLanguageCodes.join(", ")}.`));
188
+ if (r.unmatchedComponents?.length)
189
+ uyar(`Added in the store, no other language yet (only ${r.storeLanguageCode}): ${r.unmatchedComponents.join(", ")}`);
190
+ if (dusen.length) uyar(`Local translations dropped (the part was removed in the store or has no text there): ${dusen.join("; ")}`);
191
+ if (r.skippedPages?.length) uyar(`Not part of a theme package (content pages stay in the store): ${r.skippedPages.join(", ")}`);
192
+ }
193
+
194
+ function sorunlariYaz(baslik, liste, ton) {
195
+ if (!liste?.length) return;
196
+ yaz(`\n${ton(kalin(baslik))} ${soluk(`(${liste.length})`)}`);
197
+ for (const s of liste) yaz(` ${ton("•")} ${s.path || "(package)"} ${soluk(s.code)}\n ${s.detail}`);
198
+ }
199
+
200
+ /**
201
+ * Paketin kendi ikonlarını ve yazı tiplerini (theme/assets.json + theme/assets/) Milofly'a yükler: önce hangilerinin eksik olduğu sorulur,
202
+ * yalnız eksikler gönderilir (dosya içerik özetiyle tanınır; aynı dosya ikinci kez yüklenmez). Sunucu SVG'yi temizler, PNG/WOFF2 imzasını
203
+ * ve boyutu denetler, dosyayı pakete ait platform klasörüne yazar. check, push ve dev bu adımdan sonra manifesti gönderir.
204
+ */
205
+ async function varliklariYukle(c, kok, manifest) {
206
+ const dosyalar = manifest.assets?.files ?? [];
207
+ if (dosyalar.length === 0) return;
208
+ const { missing } = await c.cagir("/api/dev/theme-packages/assets/missing", {
209
+ method: "POST",
210
+ govde: { packageKey: manifest.packageKey, sha256s: dosyalar.map((d) => d.sha256) },
211
+ });
212
+ const eksik = new Set(missing);
213
+ for (const d of dosyalar.filter((x, i, l) => eksik.has(x.sha256) && l.findIndex((y) => y.sha256 === x.sha256) === i)) {
214
+ const form = new FormData();
215
+ form.append("packageKey", manifest.packageKey);
216
+ form.append("kind", d.kind);
217
+ if (d.kind === "font") {
218
+ form.append("weight", String(d.weight ?? ""));
219
+ form.append("style", String(d.style ?? ""));
220
+ }
221
+ form.append("file", new Blob([readFileSync(assetFilePath(kok, d.path))]), d.path.split("/").pop());
222
+ await c.cagir("/api/dev/theme-packages/assets", { method: "POST", govde: form });
223
+ yaz(`${yesil("✔")} ${soluk("uploaded")} ${d.path}`);
224
+ }
225
+ }
226
+
227
+ /** Henüz yüklenmemiş varlık dosyalarının özetleri (salt okuma: `assets/missing` yalnız sorar). */
228
+ async function eksikVarliklar(c, manifest) {
229
+ const dosyalar = manifest.assets?.files ?? [];
230
+ if (dosyalar.length === 0) return new Set();
231
+ const { missing } = await c.cagir("/api/dev/theme-packages/assets/missing", {
232
+ method: "POST",
233
+ govde: { packageKey: manifest.packageKey, sha256s: dosyalar.map((d) => d.sha256) },
234
+ });
235
+ return new Set(missing);
236
+ }
237
+
238
+ const YUKLENMEMIS_VARLIK = "theme_package.asset_not_uploaded";
239
+
240
+ /**
241
+ * `theme check` — yerel biçim + sunucu denetimi (sürüm, kurulum, yayım kapıları). SALT OKUMA (27.11.2026, Faz 1): hiçbir dosya yüklemez,
242
+ * sürüm yazmaz. Yerelde duran ama henüz yüklenmemiş varlık dosyası engel sayılmaz, "push/dev yükler" diye ayrı listelenir (dosyanın
243
+ * temizleme, imza ve boyut denetimi yüklemede yapılır). Çıkış kodu 1: sürüm yazılamaz ya da kurulamaz.
244
+ */
245
+ export async function check(secenekler) {
246
+ const { kok } = proje(secenekler);
247
+ const manifest = await readThemeProject(kok);
248
+ const c = await istemci(secenekler);
249
+ const eksik = await eksikVarliklar(c, manifest);
250
+ const r = await c.cagir("/api/dev/theme-packages/validate", { method: "POST", govde: manifest });
251
+ const dosyalar = manifest.assets?.files ?? [];
252
+ const bekleyen = [];
253
+ const surum = (r.release ?? []).filter((s) => {
254
+ if (s.code !== YUKLENMEMIS_VARLIK) return true;
255
+ const i = Number(/^assets\.files\[(\d+)\]/.exec(s.path ?? "")?.[1]);
256
+ const d = Number.isInteger(i) ? dosyalar[i] : undefined;
257
+ if (!d || !eksik.has(d.sha256)) return true;
258
+ bekleyen.push({ path: d.path, code: s.code, detail: "Uploaded by milofly theme push / theme dev." });
259
+ return false;
260
+ });
261
+ const gecerli = surum.length === 0 && (r.install ?? []).length === 0;
262
+ if (secenekler.json) {
263
+ yaz(JSON.stringify({ valid: gecerli, release: surum, install: r.install, publish: r.publish, pendingUploads: bekleyen.map((b) => b.path) }, null, 2));
264
+ } else {
265
+ sorunlariYaz("Blocks the release", surum, kirmizi);
266
+ sorunlariYaz("Release can be written but cannot be installed", r.install, kirmizi);
267
+ sorunlariYaz("Blocks publishing to all stores (review)", r.publish, sari);
268
+ sorunlariYaz("Not uploaded yet (push uploads them)", bekleyen, soluk);
269
+ yaz(gecerli
270
+ ? `\n${yesil("✔")} ${manifest.packageKey}@${manifest.version}: valid${r.publish.length ? " for your development store (fix the publishing items before review)" : ""}.`
271
+ : `\n${kirmizi("✖")} ${manifest.packageKey}@${manifest.version}: not valid.`);
272
+ }
273
+ if (!gecerli) process.exitCode = 1;
274
+ return { ...r, valid: gecerli, release: surum, pendingUploads: bekleyen };
275
+ }
276
+
277
+ async function gonder(c, ayar, kok, manifest, { activate, replaceThemeId }) {
278
+ await varliklariYukle(c, kok, manifest);
279
+ return c.cagir("/api/dev/theme-packages/push", {
280
+ method: "POST",
281
+ govde: { storeId: ayar.storeId, sourceThemeId: ayar.sourceThemeId, manifest, activate, replaceThemeId: replaceThemeId ?? null },
282
+ });
283
+ }
284
+
285
+ function dogrulamaHatasi(hata) {
286
+ const liste = hata.govde?.data?.errors;
287
+ if (!Array.isArray(liste)) return false;
288
+ sorunlariYaz("Rejected by Milofly", liste, kirmizi);
289
+ return true;
290
+ }
291
+
292
+ /**
293
+ * `theme push [--activate]` — theme/package.json'daki sürümü yazar (taslak) ve geliştirme mağazasına kurar. Sonra `theme pull` bu temayı
294
+ * izler: milofly.theme.json'daki `sourceThemeId` kurulan temaya çevrilir (27.11.2026, Faz 1).
295
+ */
296
+ export async function push(secenekler) {
297
+ const { kok, ayar } = proje(secenekler);
298
+ const manifest = await readThemeProject(kok);
299
+ if (/-dev\./.test(manifest.version)) throw new Error("Development versions are written by milofly theme dev. Use a release version in theme/package.json.");
300
+ const c = await istemci(secenekler);
301
+ try {
302
+ const r = await gonder(c, ayar, kok, manifest, { activate: Boolean(secenekler.activate) });
303
+ yaz(`${yesil("✔")} ${r.packageKey}@${r.release.version} ${soluk(`(release #${r.release.id}, ${r.release.status})`)} installed in your development store as theme #${r.themeId}${r.activated ? " and published there" : ""}.`);
304
+ if (String(r.themeId) !== String(ayar.sourceThemeId)) {
305
+ const onceki = ayar.sourceThemeId;
306
+ ayarYaz(kok, { ...ayar, sourceThemeId: r.themeId });
307
+ yaz(soluk(` milofly theme pull now follows theme #${r.themeId} (was #${onceki}; change it with --theme <id>).`));
308
+ }
309
+ if (r.activated && r.storefrontUrl) yaz(` Storefront: ${r.storefrontUrl}`);
310
+ yaz(` Store panel: ${r.panelUrl}`);
311
+ yaz(` Send it to review: ${kalin("milofly theme submit")}`);
312
+ } catch (hata) {
313
+ if (dogrulamaHatasi(hata)) process.exitCode = 1;
314
+ else throw hata;
315
+ }
316
+ }
317
+
318
+ function gelistirmeSurumu(taban) {
319
+ const z = new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14);
320
+ return `${String(taban).split(/[-+]/)[0]}-dev.${z}`;
321
+ }
322
+
323
+ /** `theme dev` — her değişiklikte geliştirme sürümü yazar, geliştirme mağazasına kurup yayına alır, önceki geliştirme kurulumunu siler. */
324
+ export async function dev(secenekler) {
325
+ const { kok, ayar } = proje(secenekler);
326
+ const c = await istemci(secenekler);
327
+ let durum = durumOku(kok);
328
+ let calisiyor = false;
329
+ let bekleyen = false;
330
+
331
+ async function tur() {
332
+ if (calisiyor) { bekleyen = true; return; }
333
+ calisiyor = true;
334
+ try {
335
+ const manifest = await readThemeProject(kok);
336
+ const sorunlar = checkManifestShape(manifest);
337
+ if (sorunlar.length) { sorunlariYaz("Local shape", sorunlar, kirmizi); return; }
338
+ manifest.version = gelistirmeSurumu(manifest.version);
339
+ const r = await gonder(c, ayar, kok, manifest, { activate: true, replaceThemeId: durum.devThemeId });
340
+ durum = { ...durum, devThemeId: r.themeId, lastDevVersion: r.release.version };
341
+ durumYaz(kok, durum);
342
+ yaz(`${soluk(new Date().toLocaleTimeString())} ${yesil("✔")} ${r.release.version} → theme #${r.themeId} is live in your development store` +
343
+ `${r.storefrontUrl ? `: ${r.storefrontUrl}` : ""}`);
344
+ // Sunucu aynı gönderimde eski geliştirme kurulumlarını ve sürümlerini süpürür (periyodik iş yok).
345
+ const sw = r.sweep;
346
+ if (sw && (sw.deletedThemeIds?.length || sw.deletedVersions?.length))
347
+ yaz(soluk(` cleaned up: ${sw.deletedThemeIds.length} old development themes, ${sw.deletedVersions.length} old development versions`));
348
+ if (sw?.artifactDeleteFailures?.length)
349
+ uyar(`Milofly could not delete ${sw.artifactDeleteFailures.length} stored development file(s); this is logged on Milofly's side.`);
350
+ // Sürüm süpürmesi yapılamadıysa kurulum yine tamamdır; eski geliştirme sürümleri bir sonraki gönderimde yeniden denenir.
351
+ if (sw?.error)
352
+ uyar(`Old development versions were not cleaned up this time (${sw.error}). Your change is installed; Milofly retries on the next change.`);
353
+ } catch (hata) {
354
+ if (!dogrulamaHatasi(hata)) yaz(`${kirmizi("✖")} ${hata.message}`);
355
+ } finally {
356
+ calisiyor = false;
357
+ if (bekleyen) { bekleyen = false; tetikle(); }
358
+ }
359
+ }
360
+
361
+ let zamanlayici = null;
362
+ const tetikle = () => {
363
+ clearTimeout(zamanlayici);
364
+ zamanlayici = setTimeout(tur, 700);
365
+ };
366
+
367
+ yaz(`${kalin("milofly theme dev")} — ${ayar.storeCode ?? `store #${ayar.storeId}`}. Watching ${join(kok, PROJECT_LAYOUT.root)} (Ctrl+C to stop).`);
368
+ yaz(soluk("Each change becomes a draft development release, is installed in your development store and published there. Your real stores are never touched."));
369
+ await tur();
370
+ watch(join(kok, PROJECT_LAYOUT.root), { recursive: true }, (_, dosya) => {
371
+ // JSON ve paketin kendi varlıkları (ikon, yazı tipi) değişince yeni geliştirme sürümü.
372
+ if (dosya && !/\.(json|svg|png|woff2)$/i.test(String(dosya))) return;
373
+ tetikle();
374
+ });
375
+ await new Promise(() => {});
376
+ }
377
+
378
+ /** `theme pack` — paketin tek dosyalık manifesti (inceleme, arşiv, el ile yükleme için); sunucuya bir şey göndermez. */
379
+ export async function pack(secenekler) {
380
+ const { kok } = proje(secenekler);
381
+ const manifest = await readThemeProject(kok);
382
+ mkdirSync(join(kok, "dist"), { recursive: true });
383
+ const dosya = join(kok, "dist", `${manifest.packageKey.replace("/", "__")}-${manifest.version}.json`);
384
+ writeFileSync(dosya, JSON.stringify(manifest, null, 2) + "\n");
385
+ const ozet = createHash("sha256").update(canonicalJson(manifest)).digest("hex");
386
+ yaz(`${yesil("✔")} ${dosya}\n ${soluk(`sha256(canonical JSON) ${ozet} — local reference; Milofly computes its own content digest on push`)}`);
387
+ }
388
+
389
+ async function surumBul(c, packageKey, version) {
390
+ const { packages } = await c.cagir("/api/dev/theme-packages");
391
+ const paket = packages.find((p) => p.packageKey === packageKey);
392
+ const surum = paket?.releases.find((r) => r.version === version);
393
+ if (!surum) throw new Error(`${packageKey}@${version} has not been pushed yet. Run "milofly theme push" first.`);
394
+ return surum;
395
+ }
396
+
397
+ /** `theme submit [--version x]` — sürümü platform incelemesine gönderir (taslak → incelemede). */
398
+ export async function submit(secenekler) {
399
+ const { kok } = proje(secenekler);
400
+ const manifest = await readThemeProject(kok);
401
+ const surumNo = secenekler.version ?? manifest.version;
402
+ if (/-dev\./.test(surumNo)) throw new Error("Development versions are not sent to review. Push a release version first.");
403
+ const c = await istemci(secenekler);
404
+ const surum = await surumBul(c, manifest.packageKey, surumNo);
405
+ const r = await c.cagir(`/api/dev/theme-packages/releases/${surum.id}/submit`, { method: "POST" });
406
+ yaz(`${yesil("✔")} ${manifest.packageKey}@${r.release.version} sent to review (${r.release.status}).`);
407
+ }
408
+
409
+ /** `theme list` */
410
+ export async function list(secenekler) {
411
+ const c = await istemci(secenekler);
412
+ const { packages } = await c.cagir("/api/dev/theme-packages");
413
+ if (packages.length === 0) return yaz("No theme packages yet.");
414
+ for (const p of packages) {
415
+ yaz(kalin(p.packageKey));
416
+ for (const r of p.releases.filter((r) => secenekler.all || !/-dev\./.test(r.version)))
417
+ yaz(` ${r.version.padEnd(28)} ${r.status.padEnd(10)} ${soluk(`#${r.id}`)}${r.reviewNote ? `\n ${sari("review:")} ${r.reviewNote}` : ""}`);
418
+ const gizli = p.releases.filter((r) => /-dev\./.test(r.version)).length;
419
+ if (!secenekler.all && gizli) yaz(soluk(` … ${gizli} development versions (--all to show)`));
420
+ }
421
+ }
422
+
423
+ export const komutlar = { init, publisher, pull, check, push, dev, pack, submit, list };
@@ -0,0 +1,27 @@
1
+ // `milofly app init <dir>` — ilk uygulamanın (kurulum, webhook, gömülü sayfa, API çağrısı) bir kopyasını açar.
2
+ import { cpSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { ILK_UYGULAMA } from "./sablon-yolu.mjs";
6
+ import { kalin, soluk, yaz, yesil } from "./arayuz.mjs";
7
+
8
+ const ATLANAN = new Set(["node_modules", "dist", ".env"]);
9
+
10
+ export async function init(secenekler, [hedef]) {
11
+ if (!hedef) throw new Error("Usage: milofly app init <directory>");
12
+ const kok = resolve(hedef);
13
+ if (existsSync(kok) && readdirSync(kok).length > 0) throw new Error(`${kok} is not empty.`);
14
+ const kaynak = fileURLToPath(ILK_UYGULAMA);
15
+ if (!existsSync(join(kaynak, "package.json"))) throw new Error(`App template not found at ${kaynak}.`);
16
+
17
+ cpSync(kaynak, kok, { recursive: true, filter: (yol) => !ATLANAN.has(yol.split(/[\\/]/).pop()) });
18
+ const paket = JSON.parse(readFileSync(join(kok, "package.json"), "utf8"));
19
+ paket.name = secenekler.name ?? hedef.split(/[\\/]/).pop();
20
+ writeFileSync(join(kok, "package.json"), JSON.stringify(paket, null, 2) + "\n");
21
+
22
+ yaz(`${yesil("✔")} App created in ${kok}`);
23
+ yaz(` ${kalin("Next")}: create the app in the developer portal › Apps, then follow ${join(hedef, "README.md")} (configuration, install, webhooks).`);
24
+ yaz(soluk(" It uses @milofly/app-bridge and @milofly/app-server from the same SDK release."));
25
+ }
26
+
27
+ export const komutlar = { init };
@@ -0,0 +1,42 @@
1
+ # First Milofly app (Node.js)
2
+
3
+ A complete app in one small server, no framework: install (OAuth), webhooks, an embedded page in the
4
+ Milofly store panel (App Bridge) and a call to the Milofly API.
5
+
6
+ | Route | What it shows |
7
+ |---|---|
8
+ | `GET /install` | Start an install from your side (`buildInstallUrl`, CSRF state in a cookie). |
9
+ | `GET /oauth/callback` | Redeem the install code (`exchangeCode`), store the installation, return to the panel. |
10
+ | `POST /webhooks/milofly` | Verify the signature on the raw body (`verifyWebhook`), process each `eventId` once. |
11
+ | `GET /` | The page the panel embeds (`createApp` from `@milofly/app-bridge`, loaded through an import map). |
12
+ | `POST /api/session` | Verify the session token (`verifySessionToken`) and call `GET /api/apps/v1/context`. |
13
+
14
+ ## Run
15
+
16
+ 1. In the developer portal: create an app, set
17
+ - **App URL** → `APP_ORIGIN` (the panel frames this page),
18
+ - **Redirect URL** → `APP_ORIGIN/oauth/callback`,
19
+ - **Webhook URL** → `APP_ORIGIN/webhooks/milofly` (public https; use a tunnel while developing),
20
+ - add your test store.
21
+ 2. Configure (all required; the app refuses to start without them):
22
+
23
+ ```
24
+ MILOFLY_ENVIRONMENT=production # or "custom" + MILOFLY_API_BASE_URL + MILOFLY_PANEL_ORIGIN
25
+ MILOFLY_APP_KEY=app.yourcompany.first
26
+ MILOFLY_CLIENT_ID=...
27
+ MILOFLY_CLIENT_SECRET=...
28
+ MILOFLY_SIGNING_SECRET=... # webhook signing secret; also signs session tokens
29
+ APP_ORIGIN=https://first-app.example.com
30
+ PORT=3000
31
+ ```
32
+ 3. `npm install && npm run build && npm start`
33
+ 4. Open `APP_ORIGIN/install` (or install from the Milofly app store in your test store).
34
+
35
+ ## Notes
36
+
37
+ - Installations and processed event ids live in memory here. Keep them in your database, with the access
38
+ token encrypted.
39
+ - The server sends `Content-Security-Policy: frame-ancestors <panel origin>`: only the Milofly panel may
40
+ frame the page. Do not add `X-Frame-Options`.
41
+ - Every request from the embedded page carries a fresh session token; verify it on every request. The
42
+ store, region and panel user come from the token, never from the page.
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "milofly-ilk-uygulama",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "First Milofly app: install, webhooks, embedded page (App Bridge), API call.",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20.6"
9
+ },
10
+ "scripts": {
11
+ "build": "tsc -p tsconfig.json",
12
+ "start": "node dist/server.js"
13
+ },
14
+ "dependencies": {
15
+ "@milofly/app-bridge": "0.1.1",
16
+ "@milofly/app-server": "0.1.1"
17
+ },
18
+ "devDependencies": {
19
+ "@types/node": "^20",
20
+ "typescript": "^5"
21
+ }
22
+ }
@@ -0,0 +1,51 @@
1
+ // The page Milofly embeds in the store panel.
2
+ import { createApp, MiloflyBridgeError } from "@milofly/app-bridge";
3
+
4
+ const $ = (id) => document.getElementById(id);
5
+ const status = (text, state) => {
6
+ $("status").textContent = text;
7
+ $("status").dataset.state = state;
8
+ };
9
+ const show = (value) => ($("out").textContent = JSON.stringify(value, null, 2));
10
+
11
+ // @belge:kopru-baslat
12
+ let app;
13
+ try {
14
+ // In production list the panel origin(s) you accept, e.g. ["https://app.milofly.com"].
15
+ app = await createApp();
16
+ } catch (err) {
17
+ // Opened outside the panel, or the panel did not answer.
18
+ status(err instanceof MiloflyBridgeError ? `Not connected (${err.code}).` : String(err), "error");
19
+ throw err;
20
+ }
21
+ status(`Connected: store ${app.storeContext.storeId}, region ${app.storeContext.regionId}, ${app.uiLocale} (${app.surface}).`, "ready");
22
+ if (app.initialPath) show({ initialPath: app.initialPath });
23
+
24
+ /** Calls YOUR server with the session token; your server verifies it (verifySessionToken). */
25
+ async function callBackend(path) {
26
+ const token = await app.getSessionToken(); // renewed through the panel before it expires
27
+ const res = await fetch(path, {
28
+ method: "POST",
29
+ headers: { Authorization: `Bearer ${token}`, "X-Milofly-Host": app.hostOrigin },
30
+ });
31
+ return { status: res.status, body: await res.json() };
32
+ }
33
+ // @belge-son
34
+
35
+ $("load").addEventListener("click", async () => show(await callBackend("/api/session")));
36
+
37
+ // @belge:kopru-eylemleri
38
+ $("toast").addEventListener("click", () => app.toast("Saved from the app", { tone: "success" }));
39
+ $("confirm").addEventListener("click", async () => {
40
+ const confirmed = await app.confirm({ title: "Sync products?", message: "Prices and stock will be updated.", confirmLabel: "Sync" });
41
+ show({ confirmed });
42
+ });
43
+ $("order").addEventListener("click", () => app.redirect("order", 1));
44
+ $("page").addEventListener("click", async () => {
45
+ if (!app.supports("navigate")) return show({ navigate: "not offered on this surface" });
46
+ // Call this whenever your router changes screens: the panel address follows, so a reload or a
47
+ // shared link opens the same screen (it comes back as app.initialPath).
48
+ await app.navigate("/settings");
49
+ show({ path: "/settings" });
50
+ });
51
+ // @belge-son
@@ -0,0 +1,41 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>First Milofly app</title>
7
+ <!-- App Bridge is served from the installed package; no bundler needed. -->
8
+ <script type="importmap">
9
+ {
10
+ "imports": {
11
+ "@milofly/app-bridge": "/vendor/app-bridge/index.js",
12
+ "@milofly/app-bridge/contract": "/vendor/app-bridge/contract.js"
13
+ }
14
+ }
15
+ </script>
16
+ <style>
17
+ body { font: 14px/1.5 system-ui, sans-serif; margin: 0; padding: 16px; color: #1c1a33; }
18
+ main { max-width: 720px; }
19
+ .row { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
20
+ button { height: 36px; padding: 0 14px; border-radius: 10px; border: 1px solid #c9c4e8; background: #fff; font: inherit; cursor: pointer; }
21
+ button.primary { background: #5b3df5; border-color: #5b3df5; color: #fff; }
22
+ pre { background: #f5f4fb; padding: 12px; border-radius: 10px; overflow: auto; font-size: 12px; }
23
+ [data-state="error"] { color: #b42318; }
24
+ </style>
25
+ </head>
26
+ <body>
27
+ <main>
28
+ <h1>First Milofly app</h1>
29
+ <p id="status" data-state="loading">Connecting to the Milofly panel…</p>
30
+ <div class="row">
31
+ <button class="primary" id="load">Load store context</button>
32
+ <button id="toast">Show a toast</button>
33
+ <button id="confirm">Ask for confirmation</button>
34
+ <button id="order">Open order #1</button>
35
+ <button id="page">Go to /settings</button>
36
+ </div>
37
+ <pre id="out"></pre>
38
+ </main>
39
+ <script type="module" src="/app.js"></script>
40
+ </body>
41
+ </html>
@@ -0,0 +1,31 @@
1
+ import { MILOFLY_ENVIRONMENTS, type MiloflyEnvironment } from "@milofly/app-server";
2
+
3
+ /** Required setting; the app does not start without it (no silent defaults). */
4
+ function required(name: string): string {
5
+ const value = process.env[name];
6
+ if (!value) throw new Error(`Environment variable ${name} is required (see README.md).`);
7
+ return value;
8
+ }
9
+
10
+ /**
11
+ * `MILOFLY_ENVIRONMENT=production` uses the published Milofly endpoints. `custom` reads
12
+ * `MILOFLY_API_BASE_URL` and `MILOFLY_PANEL_ORIGIN` (a local Milofly during development).
13
+ */
14
+ function environment(): MiloflyEnvironment {
15
+ const name = required("MILOFLY_ENVIRONMENT");
16
+ if (name === "production") return MILOFLY_ENVIRONMENTS.production;
17
+ if (name === "custom") return { apiBaseUrl: required("MILOFLY_API_BASE_URL"), panelOrigin: required("MILOFLY_PANEL_ORIGIN") };
18
+ throw new Error(`MILOFLY_ENVIRONMENT must be "production" or "custom" (got "${name}").`);
19
+ }
20
+
21
+ export const config = {
22
+ environment: environment(),
23
+ appKey: required("MILOFLY_APP_KEY"),
24
+ clientId: required("MILOFLY_CLIENT_ID"),
25
+ clientSecret: required("MILOFLY_CLIENT_SECRET"),
26
+ /** Webhook signing secret. It also signs the session tokens of your embedded pages. */
27
+ signingSecret: required("MILOFLY_SIGNING_SECRET"),
28
+ /** Public origin of this app (https in production). */
29
+ appOrigin: required("APP_ORIGIN"),
30
+ port: Number(required("PORT")),
31
+ };