@blocofy/cli 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/blocofy.mjs CHANGED
@@ -29,7 +29,14 @@ import {
29
29
  saveStore,
30
30
  withStoreLock,
31
31
  writeSecret,
32
+ credentialRefusal,
33
+ readOAuthTokens,
34
+ writeOAuthTokens,
32
35
  } from "../lib/credentials.mjs";
36
+ import { CLI_CLIENT_ID, LoginError, revokeToken, runBrowserLogin } from "../lib/oauth.mjs";
37
+ import { accessTokenFor } from "../lib/refresh.mjs";
38
+ import { oauthSecretStore, storeLabel, SecretStoreError } from "../lib/secret-store.mjs";
39
+ import { InitError, inspectInitDir, readInitState, runInit, initApi } from "../lib/init.mjs";
33
40
  import { printError, printTarget, printWarning, redact, registerSecret, targetData } from "../lib/output.mjs";
34
41
  import {
35
42
  CONTEXT_NAME_RE,
@@ -87,7 +94,8 @@ const args = process.argv.slice(2);
87
94
  // 0.8.0: `login --api-key` DEĞERSİZ bayraktır (parser'da boolean) — sır gizli prompt'tan ya da
88
95
  // BLOCOFY_API_KEY'den gelir, argv'ye asla girmez. `pages media-uses` / `media-decide` v1 API komutlarıdır.
89
96
  const KNOWN = {
90
- login: ["url", "token", "api-key", "api-url", "keychain"],
97
+ login: ["url", "token", "api-key", "api-url", "keychain", "site", "insecure-storage", "no-browser"],
98
+ init: ["site", "api-url", "insecure-storage", "no-browser"],
91
99
  pages: ["decisions", "expected-revision-id", "expected-version", "json", "dir"],
92
100
  themePull: ["draft", "instance"],
93
101
  themePush: ["diff", "draft", "instance", "name", "live", "yes", "confirm", "dry-run", "validate", "idempotency-key", "prune", "work"],
@@ -159,9 +167,23 @@ function printHelp() {
159
167
  Develop your theme locally against live data, preview it three ways, and publish.
160
168
 
161
169
  Usage
162
- blocofy login [--context <name>] [--url <url>] [--token <bcf_…>] [--keychain]
163
- Verify a dev token against its site (GET /api/dev/whoami) and save it as a named
164
- context (default name: the site's slug). Nothing is saved if verification fails.
170
+ blocofy login [--context <name>] [--site <handle|slug>] [--api-url <url>] [--no-browser]
171
+ [--insecure-storage]
172
+ Log in with your browser (PKCE, loopback 127.0.0.1/[::1] callback): pick the site and
173
+ approve. The login is draft-only ("Tema geliştirme"): it can never change the live site or
174
+ publish. "Connected" is printed only after GET /api/v1/ping confirms site + profile. The
175
+ tokens go to the OS secure store (macOS Keychain, Windows DPAPI file, Linux Secret Service);
176
+ no store → refused, never a silent plain file. --insecure-storage (or
177
+ BLOCOFY_SECRET_STORE=file) chooses ~/.blocofy/secrets.json (0600) explicitly.
178
+ Needs a terminal: CI / SSH never opens a browser (use env credentials or the options below).
179
+ --api-url <url> platform (default https://app.blocofy.com)
180
+ --no-browser do not open the browser; open the printed URL yourself
181
+ --site refuse (and revoke) the login unless this site was approved
182
+
183
+ blocofy login --url <url> --token [--context <name>] [--keychain] (advanced)
184
+ Verify a pasted dev token (bcf_… / bcf2_…) against its site (GET /api/dev/whoami) and save
185
+ it as a named context (default name: the site's slug). The token is read from a hidden
186
+ prompt; --token <value> works but warns (argv is visible in ps and shell history).
165
187
  Get a token from the admin panel → Settings → Theme CLI tokens.
166
188
  --keychain keep the secret in the macOS keychain (or BLOCOFY_SECRET_STORE=keychain);
167
189
  default: ~/.blocofy/secrets.json (0600)
@@ -176,7 +198,18 @@ Usage
176
198
  blocofy contexts [--json] list saved contexts (never prints secrets)
177
199
  blocofy use <name> default context for status / target / pages check outside a
178
200
  project (never used by any other command)
179
- blocofy logout --context <name> remove a context and its secrets
201
+ blocofy logout [--context <name>] remove a context and its secrets; a browser login is also
202
+ revoked on the platform (RFC 7009). Both results are printed;
203
+ exit 4 if the local copy could not be removed or the platform
204
+ login was NOT revoked (then cut it in the panel).
205
+
206
+ blocofy init [dir] [--site <handle|slug>] [--context <name>]
207
+ Set up a new project: (browser login if needed) → a theme work of its own (idempotent:
208
+ .blocofy/init.json keeps its key; re-run continues, never a second work) → the work's theme
209
+ files → .blocofy/project.json → a preview link → the live theme read back unchanged.
210
+ Refuses a non-empty directory that is not a project and one bound to another site
211
+ (exit 3, nothing written). Non-interactive runs need --site and a saved/env credential.
212
+ Exit 5: the live theme changed meanwhile (init never writes it; not reported as success).
180
213
  blocofy link [dir] --context <name> [--adopt]
181
214
  Bind a project directory to the context's (verified) site: writes .blocofy/project.json
182
215
  (commit it), .blocofy/local.json (your context; git-ignored) and .blocofy/.gitignore.
@@ -435,7 +468,8 @@ Usage
435
468
  blocofy --help
436
469
 
437
470
  Examples
438
- blocofy login --url https://store.myblocofy.com --token bcf_xxxxxxxx (context "store")
471
+ blocofy login && blocofy init my-site (browser login, new project)
472
+ blocofy login --url https://store.myblocofy.com --token (pasted dev token, hidden)
439
473
  blocofy theme pull store-theme --context store && cd store-theme && blocofy theme dev
440
474
  blocofy link ~/code/store-theme --context store (an existing checkout)
441
475
  blocofy theme push && blocofy theme publish (inside the bound project)
@@ -468,16 +502,19 @@ Targets (which site a command talks to)
468
502
  (one warning; run \`blocofy link --adopt\` to record it). A server that reports no origin cannot
469
503
  serve a binding that records one (TARGET_UNVERIFIED).
470
504
  Exit codes (every command): 0 ok · 1 usage/network/5xx/local check · 2 server refusal (HTTP 4xx)
471
- · 3 target/binding refusal · 4 'site apply' only: not finished within its bounded pass count —
472
- every step already applied is safe, re-run the same command to resume.
505
+ · 3 target/binding refusal · 4 'site apply': not finished within its bounded pass count —
506
+ every step already applied is safe, re-run the same command to resume; 'logout': the local
507
+ login was not removed or the platform login was NOT revoked · 5 'init': the live theme changed
508
+ meanwhile (init never writes it; not reported as a success).
473
509
  --json: every failure prints {"error":{"code","message","details"}} as the LAST stderr line; the
474
510
  target block ({"target":…}) and any warning lines are printed on stderr before it.
475
511
  Retries: network errors and HTTP 429/502/503/504 are retried up to 3 times (Retry-After honoured,
476
512
  max 30s per wait; else 0.3s/0.9s/2s), resending the identical request (pages push carries one
477
513
  x-idempotency-key per push). HTTP 500 is never retried. Each retry prints a notice on stderr.
478
514
 
479
- Auth: ~/.blocofy/credentials.json (contexts, no secrets) + ~/.blocofy/secrets.json (0600) or the
480
- macOS keychain. A pre-0.10 credentials file is migrated on first use (backup:
515
+ Auth: ~/.blocofy/credentials.json (contexts, no secrets). A browser login's tokens live in the OS
516
+ secure store (macOS Keychain, Windows DPAPI file, Linux Secret Service; the 0600 file only when
517
+ chosen); a pasted token/key in ~/.blocofy/secrets.json (0600) or the macOS keychain. A pre-0.10 credentials file is migrated on first use (backup:
481
518
  ~/.blocofy/credentials.v1.bak.json — copy it back to roll back).
482
519
  The CLI does not build assets — bring your own (npm/Vite/Tailwind); the platform serves
483
520
  plain Liquid + static assets.`);
@@ -509,6 +546,7 @@ const retry = { onRetry };
509
546
  */
510
547
  function exitCodeFor(error) {
511
548
  if (error instanceof TargetError || error instanceof CredentialsError) return error.exitCode ?? 1;
549
+ if (error instanceof LoginError || error instanceof InitError || error?.name === "LoopbackError") return error.exitCode ?? 1;
512
550
  if (error instanceof CliRefusal) return 2;
513
551
  const status = Number(error?.status);
514
552
  return status >= 400 && status < 500 ? 2 : 1;
@@ -530,8 +568,25 @@ function envelopeFor(error) {
530
568
  return { code, message: error?.message || String(error), details };
531
569
  }
532
570
 
571
+ /** The context the current command resolved (for the re-login hint of a credential refusal). */
572
+ let activeContext = null;
573
+
574
+ /**
575
+ * ADR-0014 (wave P4) — the plain Turkish lines of a credential refusal (the profile gate's codes and the CLI's own
576
+ * REAUTH_REQUIRED), printed before the usual `error [code]` line. Never under --json (the envelope carries the code).
577
+ */
578
+ function printRefusalLines(error) {
579
+ if (JSON_MODE) return;
580
+ if (Array.isArray(error?.lines)) for (const line of error.lines) console.error(redact(line));
581
+ const code = error instanceof CliRefusal ? error.error?.code : error?.details?.server_code ?? error?.code;
582
+ const details = error instanceof CliRefusal ? error.error?.details : error?.serverDetails ?? error?.body?.details ?? error?.details;
583
+ const refusal = credentialRefusal(code, details ?? {}, { context: error?.details?.context ?? activeContext });
584
+ if (refusal) for (const line of refusal.lines) console.error(redact(line));
585
+ }
586
+
533
587
  function failAndExit(error) {
534
588
  const code = exitCodeFor(error);
589
+ printRefusalLines(error);
535
590
  if ((error instanceof PagesCliError || error instanceof SiteStateFsError) && !JSON_MODE) {
536
591
  if (error.diagnostics?.length) reportPageDiagnostics(error.diagnostics);
537
592
  }
@@ -643,6 +698,9 @@ function saveVerifiedPair(name, kind, args) {
643
698
  function saveVerifiedPairLocked(name, kind, { url, secret, identity, storeName }) {
644
699
  const store = loadStore();
645
700
  const existing = store.contexts[name];
701
+ if (existing?.oauth) {
702
+ throw new TargetError("TARGET_CONTEXT_OCCUPIED", `Context "${name}" is a browser login (blocofy login); a pasted ${kind === "dev" ? "dev token" : "API key"} gets a context of its own. Nothing was saved. Use --context <another-name>.`, { context: name });
703
+ }
646
704
  writeSecret(name, kind, storeName, secret);
647
705
  if (existing?.[kind] && existing[kind].secret.store !== storeName) {
648
706
  try {
@@ -684,7 +742,7 @@ async function loginApiKey(flags, positionals) {
684
742
 
685
743
  let apiKey = null;
686
744
  if (process.stdin.isTTY) {
687
- apiKey = await promptSecret("API key (blcf_live_…, hidden): ");
745
+ apiKey = await promptSecret("API key (blcf_live_… / blcf_k2_…, hidden): ");
688
746
  if (apiKey === null) {
689
747
  console.error("Cancelled. Nothing was written.");
690
748
  process.exit(1);
@@ -697,7 +755,7 @@ async function loginApiKey(flags, positionals) {
697
755
  process.exit(1);
698
756
  }
699
757
  if (!isValidApiKey(apiKey)) {
700
- console.error("Invalid API key — a v1 key starts with blcf_live_ (a bcf_ dev token is not accepted for the v1 API). Nothing was written.");
758
+ console.error("Invalid API key — a v1 key starts with blcf_live_ or blcf_k2_ (a bcf_ dev token is not accepted for the v1 API). Nothing was written.");
701
759
  process.exit(1);
702
760
  }
703
761
  registerSecret(apiKey);
@@ -708,22 +766,198 @@ async function loginApiKey(flags, positionals) {
708
766
  await assertPairFitsContext(name, loadStore().contexts[name], identity, "dev");
709
767
  saveVerifiedPair(name, "api", { url: apiUrl, secret: apiKey, identity, storeName });
710
768
  console.log(`✓ API key saved to context "${name}" → ${credentialsPath()} (API: ${apiUrl})`);
769
+ console.log(` Secret store: ${storeLabel(storeName)}`);
711
770
  console.log(` Site: ${siteLabel(identity.site) || identity.site.id}`);
712
771
  console.log("Next: blocofy pages media-uses <page-handle>");
713
772
  }
714
773
 
774
+ // ── browser login (ADR-0014 §5, wave P4) ──────────────────────────────────────────────────────────────────
775
+
776
+ /** Where the owner manages connections (the "Connections and keys" hub). */
777
+ const CONNECTIONS_PATH = "/settings/connections";
778
+
779
+ /** A person at a terminal: stdin is a TTY and CI is not set. Unattended runs never open a browser. */
780
+ const isUnattended = () => !process.stdin.isTTY || Boolean(process.env.CI);
781
+ const isSshSession = () => Boolean(process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY);
782
+
783
+ const withLines = (error, lines) => Object.assign(error, { lines });
784
+
785
+ function assertBrowserLoginPossible() {
786
+ if (isUnattended()) {
787
+ throw withLines(
788
+ new LoginError("LOGIN_UNATTENDED", "Browser login needs an interactive terminal (no TTY, or CI is set): no browser was opened and nothing was sent. In CI use BLOCOFY_API_KEY + BLOCOFY_API_URL (or BLOCOFY_URL + BLOCOFY_TOKEN); advanced: blocofy login --token / blocofy login --api-key."),
789
+ [
790
+ "Tarayıcıyla giriş bir terminal ister; bu oturum etkileşimsiz (CI ya da yönlendirilmiş girdi). Tarayıcı açılmadı, hiçbir şey gönderilmedi.",
791
+ " CI/otomasyon: BLOCOFY_API_KEY + BLOCOFY_API_URL (ya da BLOCOFY_URL + BLOCOFY_TOKEN) ortam değişkenleri.",
792
+ " Gelişmiş: yapıştırılan token ile giriş: blocofy login --token ya da blocofy login --api-key",
793
+ ],
794
+ );
795
+ }
796
+ if (isSshSession()) {
797
+ throw withLines(
798
+ new LoginError("LOGIN_NO_BROWSER", "Browser login is not supported over SSH (the browser cannot reach this machine's 127.0.0.1 callback). Nothing was sent. Advanced: blocofy login --token / blocofy login --api-key."),
799
+ [
800
+ "Uzak (SSH) oturumda tarayıcıyla giriş desteklenmiyor: tarayıcı bu makinenin 127.0.0.1 adresine dönemez. Hiçbir şey gönderilmedi.",
801
+ " Gelişmiş: yapıştırılan token ile giriş: blocofy login --token ya da blocofy login --api-key",
802
+ ],
803
+ );
804
+ }
805
+ }
806
+
807
+ function loginOrigin(flags) {
808
+ const origin = normalizeUrl(typeof flags["api-url"] === "string" ? flags["api-url"] : DEFAULT_API_URL);
809
+ if (!isValidUrl(origin)) throw new LoginError("USAGE", "Invalid --api-url — must be a valid http(s):// URL. Nothing was written.");
810
+ return origin;
811
+ }
812
+
813
+ /** `--site <handle|slug>` names the approved site. */
814
+ const siteMatches = (site, arg) => String(site.id) === String(arg) || (site.slug != null && site.slug === arg);
815
+
816
+ /** A browser login owns its context: never one that holds pasted secrets, never one recorded for another site. */
817
+ function assertContextFreeForLogin(name, identity) {
818
+ const ctx = loadStore().contexts[name];
819
+ if (!ctx) return;
820
+ if (ctx.dev || ctx.api) {
821
+ throw new TargetError("TARGET_CONTEXT_OCCUPIED", `Context "${name}" holds a pasted dev token / API key; a browser login gets a context of its own. Nothing was saved. Use --context <another-name> (or \`blocofy logout --context ${name}\` first).`, { context: name });
822
+ }
823
+ if (identity && ctx.site) {
824
+ const o = compareOrigin(ctx.platform_origin, identity.platformOrigin);
825
+ if (String(ctx.site.id) !== String(identity.site.id) || o === "mismatch" || o === "unproven") {
826
+ throw new TargetError("TARGET_SITE_MISMATCH", `Context "${name}" is for site ${ctx.site.slug ?? ctx.site.id}, but you approved ${identity.site.slug ?? identity.site.id}. Nothing was saved. Use another --context name.`, { context: name, context_site_id: ctx.site.id, new_site_id: identity.site.id });
827
+ }
828
+ }
829
+ }
830
+
831
+ /** Save a verified browser login (token set first, then the context). Returns the previous token set, if any. */
832
+ function saveOAuthContext(name, storeName, { tokens, identity, metadata }, origin) {
833
+ return withStoreLock(() => {
834
+ const store = loadStore();
835
+ const existing = store.contexts[name];
836
+ let previous = null;
837
+ if (existing?.oauth) {
838
+ try {
839
+ const t = readOAuthTokens(name, existing);
840
+ if (t) previous = { token: t.refresh_token ?? t.access_token, endpoint: existing.oauth.revocation_endpoint ?? null };
841
+ } catch {
842
+ previous = null;
843
+ }
844
+ }
845
+ writeOAuthTokens(name, storeName, tokens);
846
+ if (existing?.oauth && existing.oauth.secret.store !== storeName) {
847
+ try {
848
+ removeSecrets(name, { oauth: existing.oauth });
849
+ } catch {
850
+ /* the old copy stays in the other store; the context now points at the new one */
851
+ }
852
+ }
853
+ store.contexts[name] = {
854
+ platform_origin: identity.platformOrigin ?? origin,
855
+ site: { id: identity.site.id, slug: identity.site.slug ?? null, name: identity.site.name ?? null, domain: identity.site.domain ?? null },
856
+ oauth: {
857
+ url: origin,
858
+ issuer: metadata.issuer,
859
+ client_id: CLI_CLIENT_ID,
860
+ token_endpoint: metadata.token_endpoint,
861
+ revocation_endpoint: metadata.revocation_endpoint ?? null,
862
+ dev_url: identity.devUrl ?? null,
863
+ profile: identity.profile,
864
+ secret: { store: storeName },
865
+ logged_in_at: new Date().toISOString(),
866
+ },
867
+ verified_at: new Date().toISOString(),
868
+ };
869
+ if (!store.current_context) store.current_context = name;
870
+ saveStore(store);
871
+ return previous;
872
+ });
873
+ }
874
+
875
+ /**
876
+ * The browser login and its save (ADR §5.2): used by `login` and by `init` when it has no credential. Success is the
877
+ * canonical identity probe, then the save. Returns `{ name, identity, storeName, explicitStore, origin }`.
878
+ */
879
+ async function browserLoginAndSave({ flags, contextName = null, siteArg = null }) {
880
+ assertBrowserLoginPossible();
881
+ const origin = loginOrigin(flags);
882
+ let store;
883
+ try {
884
+ store = oauthSecretStore({ insecure: Boolean(flags["insecure-storage"]) });
885
+ } catch (error) {
886
+ throw error instanceof SecretStoreError ? new CredentialsError(error.code, error.message) : error;
887
+ }
888
+ if (contextName) {
889
+ contextNameOrExit(contextName);
890
+ assertContextFreeForLogin(contextName, null);
891
+ }
892
+ if (!JSON_MODE) console.error(`Blocofy girişi tarayıcıda açılıyor (${origin})…`);
893
+ const result = await runBrowserLogin({
894
+ origin,
895
+ openBrowser: flags["no-browser"] ? async () => {} : async (url) => openUrl(url),
896
+ print: (url) => {
897
+ if (JSON_MODE) return;
898
+ console.error("Tarayıcı açılmazsa bu adresi aç (adres sır içermez):");
899
+ console.error(` ${url}`);
900
+ console.error("Tarayıcıda siteni seçip onayla; en çok 5 dakika bekliyorum…");
901
+ },
902
+ onRetry,
903
+ });
904
+ registerSecret(result.tokens.access_token);
905
+ registerSecret(result.tokens.refresh_token);
906
+ const { identity } = result;
907
+ if (siteArg && !siteMatches(identity.site, siteArg)) {
908
+ await result.abandon(new LoginError("LOGIN_SITE_MISMATCH", `You approved ${identity.site.slug ?? identity.site.id} in the browser, but --site asks for ${siteArg}. The new login was revoked; nothing was saved.`, { site: identity.site.id, requested: siteArg }, 3));
909
+ }
910
+ const name = contextName ?? identity.site.slug ?? "";
911
+ try {
912
+ contextNameOrExit(name);
913
+ assertContextFreeForLogin(name, identity);
914
+ } catch (error) {
915
+ await result.abandon(error);
916
+ }
917
+ const previous = saveOAuthContext(name, store.name, result, origin);
918
+ // A re-login replaces the context's previous login: close that one too (best effort; the hub lists any survivor).
919
+ if (previous?.token && previous.endpoint) await revokeToken({ endpoint: previous.endpoint, token: previous.token });
920
+ return { name, identity, storeName: store.name, explicitStore: store.explicit, origin };
921
+ }
922
+
923
+ async function browserLogin(flags, positionals) {
924
+ if (positionals.length > 0) throw new TargetError("USAGE", "Usage: blocofy login [--context <name>] [--site <handle|slug>] [--api-url <url>] [--no-browser] [--insecure-storage]", {}, 1);
925
+ const siteArg = typeof flags.site === "string" ? flags.site : null;
926
+ const { name, identity, storeName, explicitStore, origin } = await browserLoginAndSave({ flags, contextName: typeof flags.context === "string" ? flags.context : null, siteArg });
927
+ if (explicitStore) printWarning({ code: "SECRET_STORE_PLAINTEXT", message: `The login is kept in ~/.blocofy/secrets.json (0600) because you chose it (--insecure-storage / BLOCOFY_SECRET_STORE=file), not in the OS secure store.` }, { json: JSON_MODE });
928
+ const p = identity.profile;
929
+ if (JSON_MODE) {
930
+ console.log(JSON.stringify({ login: { context: name, site: identity.site, platform_origin: identity.platformOrigin, profile: p, audience: identity.audience, store: storeName, policy_version: identity.policyVersion } }, null, 2));
931
+ return;
932
+ }
933
+ console.log(`✓ Bağlandı: ${siteLabel(identity.site) || identity.site.id} — context "${name}"`);
934
+ console.log(` Profil: ${p.label ?? p.id} (${p.id}@${p.version ?? "?"})${p.id === "theme-dev" ? " — taslak üzerinde çalışır; canlı siteni değiştiremez, yayınlayamaz." : ""}`);
935
+ console.log(` Giriş bilgisi: ${storeLabel(storeName)}`);
936
+ if (!identity.devUrl) console.log(" Not: sitenin henüz bir alan adı yok; tema dosyası komutları (theme dev/pull/push) şimdilik çalışmaz.");
937
+ console.log(`Sonraki adım: yeni proje için blocofy init <dizin> · mevcut dizin için blocofy link <dizin> --context ${name}`);
938
+ console.log(` Bağlantıyı panelden kesmek: ${origin}${CONNECTIONS_PATH} · bu makineden çıkış: blocofy logout --context ${name}`);
939
+ console.log(`technical: platform ${identity.platformOrigin ?? origin}, audience ${identity.audience}, policy_version ${identity.policyVersion ?? "?"}`);
940
+ }
941
+
715
942
  async function login(rest) {
716
943
  const { flags, positionals } = parseArgsOrExit(rest, KNOWN.login);
717
- if (flags["api-key"] || flags["api-url"] !== undefined) {
718
- if (!flags["api-key"]) {
719
- console.error("--api-url is only used with --api-key. Nothing was written.");
720
- process.exit(1);
721
- }
944
+ if (flags["api-key"]) {
722
945
  await loginApiKey(flags, positionals);
723
946
  return;
724
947
  }
948
+ // ADR-0014 O2: the browser is the default; a pasted dev token (`--url` / `--token` / `--keychain`) is the advanced path.
949
+ if (flags.url === undefined && flags.token === undefined && !flags.keychain) {
950
+ await browserLogin(flags, positionals);
951
+ return;
952
+ }
953
+ if (flags["api-url"] !== undefined || flags.site !== undefined || flags["insecure-storage"] || flags["no-browser"]) {
954
+ console.error("--api-url / --site / --insecure-storage / --no-browser belong to the browser login (`blocofy login`) or `--api-key`; a pasted dev token takes --url and --token. Nothing was written.");
955
+ process.exit(1);
956
+ }
725
957
  let url = typeof flags.url === "string" ? normalizeUrl(flags.url) : "";
726
958
  let token = typeof flags.token === "string" ? flags.token.trim() : "";
959
+ // ADR-0014 B6: a token on the command line is visible to other local users (ps) and kept in shell history.
960
+ if (token) printWarning({ code: "TOKEN_IN_ARGV", message: "The dev token was given on the command line, where `ps` and your shell history can see it. Prefer `blocofy login --url <site> --token` (hidden prompt) or BLOCOFY_URL + BLOCOFY_TOKEN." }, { json: JSON_MODE });
727
961
 
728
962
  // Flag ile verildiyse anında doğrula (prompt'a düşmeden).
729
963
  if (url && !isValidUrl(url)) {
@@ -734,7 +968,7 @@ async function login(rest) {
734
968
  console.error(
735
969
  token.startsWith("blcf_")
736
970
  ? "Invalid --token — that is a v1 API key (blcf_…), not a theme dev token (bcf_…). The two are separate credentials: add the API key with `blocofy login --api-key`. Nothing was written."
737
- : "Invalid --token — must start with bcf_.",
971
+ : "Invalid --token — must start with bcf_ or bcf2_.",
738
972
  );
739
973
  process.exit(1);
740
974
  }
@@ -753,13 +987,30 @@ async function login(rest) {
753
987
  "Enter a valid URL, e.g. https://store.myblocofy.com",
754
988
  );
755
989
  }
990
+ if (!token && process.stdin.isTTY) {
991
+ // ADR-0014 B6: the dev token prompt does not echo.
992
+ rl.close();
993
+ for (let i = 0; i < 3 && !token; i += 1) {
994
+ const answer = await promptSecret("Dev token (bcf_… / bcf2_…, hidden): ");
995
+ if (answer === null) {
996
+ console.error("Cancelled. Nothing was written.");
997
+ process.exit(1);
998
+ }
999
+ if (isValidToken(answer.trim())) token = answer.trim();
1000
+ else console.error(" ✗ Token must start with bcf_ or bcf2_ — get one from the admin panel: Settings → Theme CLI tokens.");
1001
+ }
1002
+ if (!token) {
1003
+ console.error("Too many invalid attempts.");
1004
+ process.exit(1);
1005
+ }
1006
+ }
756
1007
  if (!token) {
757
1008
  token = await promptValid(
758
1009
  rl,
759
1010
  "Dev token (bcf_…): ",
760
1011
  (s) => s.trim(),
761
1012
  isValidToken,
762
- "Token must start with bcf_ — get one from the admin panel: Settings → Theme CLI tokens.",
1013
+ "Token must start with bcf_ or bcf2_ — get one from the admin panel: Settings → Theme CLI tokens.",
763
1014
  );
764
1015
  }
765
1016
  } finally {
@@ -777,6 +1028,7 @@ async function login(rest) {
777
1028
  saveVerifiedPair(name, "dev", { url, secret: token, identity, storeName });
778
1029
  console.log(`✓ Saved context "${name}" → ${credentialsPath()}`);
779
1030
  console.log(` Site: ${siteLabel(identity.site)} — commands using context "${name}" target this site.`);
1031
+ console.log(` Secret store: ${storeLabel(storeName)}`);
780
1032
  console.log(`Next: bind a project directory: blocofy link <dir> --context ${name} (or pull into an empty one: blocofy theme pull <dir> --context ${name})`);
781
1033
  }
782
1034
 
@@ -791,6 +1043,7 @@ async function contextsCommand(rest) {
791
1043
  platform_origin: c.platform_origin ?? null,
792
1044
  dev: c.dev ? { url: c.dev.url, store: c.dev.secret.store } : null,
793
1045
  api: c.api ? { url: c.api.url, store: c.api.secret.store } : null,
1046
+ login: c.oauth ? { url: c.oauth.url, store: c.oauth.secret.store, profile: c.oauth.profile ?? null, state: c.oauth.state ?? "active" } : null,
794
1047
  verified_at: c.verified_at ?? null,
795
1048
  }));
796
1049
  if (JSON_MODE) {
@@ -803,7 +1056,8 @@ async function contextsCommand(rest) {
803
1056
  }
804
1057
  for (const r of rows) {
805
1058
  const site = r.site ? `${siteLabel(r.site)} · ${r.site.id}` : "(not verified yet)";
806
- const pairs = [r.dev ? `dev ${r.dev.url} [${r.dev.store}]` : null, r.api ? `api ${r.api.url} [${r.api.store}]` : null].filter(Boolean).join(", ");
1059
+ const login = r.login ? `cli-login ${r.login.url} [${r.login.store}]${r.login.profile ? ` ${r.login.profile.id}@${r.login.profile.version}` : ""}${r.login.state === "reauth_required" ? " (needs a new login)" : ""}` : null;
1060
+ const pairs = [r.dev ? `dev ${r.dev.url} [${r.dev.store}]` : null, r.api ? `api ${r.api.url} [${r.api.store}]` : null, login].filter(Boolean).join(", ");
807
1061
  console.log(`${r.current ? "*" : " "} ${r.name} ${site} ${pairs}`);
808
1062
  }
809
1063
  }
@@ -822,20 +1076,82 @@ async function useCommand(rest) {
822
1076
  console.log(" (Inside a bound project the project's site decides; `use` never retargets it.)");
823
1077
  }
824
1078
 
1079
+ /**
1080
+ * ADR-0014 §5.5 — `blocofy logout [--context <name>]`. Two independent results, both printed:
1081
+ * server revoked (RFC 7009 /revoke answered 200) | unreachable (network / 5xx: NOT revoked) | refused (another
1082
+ * answer: NOT revoked) | unavailable (the saved login could not be read: NOT revoked) | not_applicable
1083
+ * (a pasted token or key: revoke it in the panel)
1084
+ * local cleared | failed — done whatever the server said.
1085
+ * Exit 0 only when the local login is cleared and nothing is left open on the server; otherwise 4.
1086
+ */
825
1087
  async function logoutCommand(rest) {
826
1088
  const { flags, positionals } = parseArgsOrExit(rest, []);
827
- const name = typeof flags.context === "string" ? flags.context : null;
828
- if (!name || positionals.length) throw new TargetError("USAGE", "Usage: blocofy logout --context <name>", {}, 1);
829
- withStoreLock(() => {
830
- const store = loadStore();
831
- const ctx = store.contexts[name];
832
- if (!ctx) throw new TargetError("TARGET_CONTEXT_UNKNOWN", `No context named "${name}".`, { context: name });
833
- removeSecrets(name, ctx);
834
- delete store.contexts[name];
835
- if (store.current_context === name) store.current_context = null;
836
- saveStore(store);
837
- });
838
- console.log(`✓ Removed context "${name}" and its secrets.`);
1089
+ if (positionals.length) throw new TargetError("USAGE", "Usage: blocofy logout [--context <name>]", {}, 1);
1090
+ const store0 = loadStore();
1091
+ const name = typeof flags.context === "string" ? flags.context : store0.current_context;
1092
+ if (!name) throw new TargetError("USAGE", "Usage: blocofy logout --context <name> (no default context is set; see `blocofy contexts`).", {}, 1);
1093
+ const ctx = store0.contexts[name];
1094
+ if (!ctx) throw new TargetError("TARGET_CONTEXT_UNKNOWN", `No context named "${name}".`, { context: name });
1095
+
1096
+ let server = { outcome: "not_applicable", status: null };
1097
+ if (ctx.oauth) {
1098
+ let tokens = null;
1099
+ try {
1100
+ tokens = readOAuthTokens(name, ctx);
1101
+ } catch {
1102
+ tokens = null;
1103
+ }
1104
+ const token = tokens?.refresh_token ?? tokens?.access_token ?? null;
1105
+ if (token) registerSecret(token);
1106
+ server = token && ctx.oauth.revocation_endpoint
1107
+ ? await revokeToken({ endpoint: ctx.oauth.revocation_endpoint, token, clientId: ctx.oauth.client_id ?? CLI_CLIENT_ID })
1108
+ : { outcome: "unavailable", status: null };
1109
+ }
1110
+
1111
+ let local = "cleared";
1112
+ let localError = null;
1113
+ try {
1114
+ withStoreLock(() => {
1115
+ const store = loadStore();
1116
+ const current = store.contexts[name];
1117
+ if (!current) return;
1118
+ removeSecrets(name, current);
1119
+ delete store.contexts[name];
1120
+ if (store.current_context === name) store.current_context = null;
1121
+ saveStore(store);
1122
+ });
1123
+ } catch (error) {
1124
+ local = "failed";
1125
+ localError = error;
1126
+ }
1127
+
1128
+ const hub = ctx.oauth ? `${String(ctx.oauth.url).replace(/\/+$/, "")}${CONNECTIONS_PATH}` : null;
1129
+ const ok = local === "cleared" && (server.outcome === "revoked" || server.outcome === "not_applicable");
1130
+ if (JSON_MODE) {
1131
+ console.log(JSON.stringify({ logout: { context: name, local, server: server.outcome, ...(server.status ? { server_status: server.status } : {}), ...(hub && server.outcome !== "revoked" ? { revoke_in_panel: hub } : {}) } }, null, 2));
1132
+ } else {
1133
+ console.log(local === "cleared" ? `✓ Yerel giriş silindi (context "${name}").` : `✗ Yerel giriş SİLİNEMEDİ (context "${name}"): ${redact(localError?.message ?? String(localError))}`);
1134
+ switch (server.outcome) {
1135
+ case "revoked":
1136
+ console.log("✓ Sunucudaki CLI bağlantısı iptal edildi.");
1137
+ break;
1138
+ case "not_applicable":
1139
+ console.log(" Sunucuda iptal edilecek bir CLI girişi yok: bu context yapıştırılmış bir token/anahtar taşıyordu; onu panelden iptal edebilirsin.");
1140
+ break;
1141
+ case "unreachable":
1142
+ console.log(`✗ Sunucudaki bağlantı İPTAL EDİLMEDİ (platforma ulaşılamadı${server.status ? `, HTTP ${server.status}` : ""}) — panelden kes: ${hub}`);
1143
+ break;
1144
+ case "refused":
1145
+ console.log(`✗ Sunucudaki bağlantı İPTAL EDİLMEDİ (platform isteği reddetti, HTTP ${server.status}) — panelden kes: ${hub}`);
1146
+ break;
1147
+ default:
1148
+ console.log(`✗ Sunucudaki bağlantı İPTAL EDİLMEDİ (kayıtlı giriş okunamadı) — panelden kes: ${hub}`);
1149
+ }
1150
+ }
1151
+ if (!ok) {
1152
+ if (!JSON_MODE) console.error(`logout: local ${local}, server ${server.outcome} — not complete (exit 4).`);
1153
+ process.exit(4);
1154
+ }
839
1155
  }
840
1156
 
841
1157
  async function linkCommand(rest) {
@@ -847,8 +1163,7 @@ async function linkCommand(rest) {
847
1163
  if (!flagContext && !process.env.BLOCOFY_CONTEXT && !envCtx) {
848
1164
  throw new TargetError("TARGET_CONTEXT_REQUIRED", "`blocofy link` needs the context to bind: pass --context <name> (see `blocofy contexts`).", {});
849
1165
  }
850
- const resolved = await resolveContext({ flagContext, envContextName: process.env.BLOCOFY_CONTEXT || null, envCtx, getStore: () => loadStore(), binding: null });
851
- const secrets = resolved.env ? resolved.env.secrets : readSecrets(resolved.name, resolved.context);
1166
+ const { resolved, secrets } = await credentialsFor(await resolveContext({ flagContext, envContextName: process.env.BLOCOFY_CONTEXT || null, envCtx, getStore: () => loadStore(), binding: null }));
852
1167
  registerSecret(secrets.devToken);
853
1168
  registerSecret(secrets.apiKey);
854
1169
  assertCredentialTypes({ resolved, secrets });
@@ -888,6 +1203,31 @@ async function targetCommand(rest) {
888
1203
  else printTarget(t.display, { stream: process.stdout });
889
1204
  }
890
1205
 
1206
+ /**
1207
+ * ADR-0014 §5 — the secrets of a resolved context. A browser-login context answers with its (renewed) CLI token in
1208
+ * both places: the v1 API at its platform origin and, when the site has a domain, the renderer's `/api/dev`.
1209
+ * Returns `{ resolved, secrets, renewToken }` (`renewToken`: a getter for long-running commands, else null).
1210
+ */
1211
+ async function credentialsFor(resolved) {
1212
+ activeContext = resolved.name;
1213
+ if (resolved.env) return { resolved, secrets: resolved.env.secrets, renewToken: null };
1214
+ const ctx = resolved.context;
1215
+ if (!ctx.oauth) return { resolved, secrets: readSecrets(resolved.name, ctx), renewToken: null };
1216
+ const access = await accessTokenFor(resolved.name);
1217
+ registerSecret(access);
1218
+ const view = { ...ctx, api: { url: ctx.oauth.url, secret: ctx.oauth.secret } };
1219
+ if (ctx.oauth.dev_url) view.dev = { url: ctx.oauth.dev_url, secret: ctx.oauth.secret };
1220
+ return {
1221
+ resolved: { ...resolved, context: view, oauth: true },
1222
+ secrets: { devToken: ctx.oauth.dev_url ? access : null, apiKey: access },
1223
+ renewToken: async () => {
1224
+ const t = await accessTokenFor(resolved.name);
1225
+ registerSecret(t);
1226
+ return t;
1227
+ },
1228
+ };
1229
+ }
1230
+
891
1231
  /** "BLOCOFY_CONTEXT=beta, env credentials" — the stated context choices an explicit --context overrode. */
892
1232
  function overridesLabel(ignored) {
893
1233
  return ignored.map((a) => (a.source === "env" ? "env credentials" : `${a.source}=${a.name}`)).join(", ");
@@ -931,7 +1271,7 @@ async function prepareTarget({ command, commandClass, dir, flags, needs, mode, r
931
1271
  const { newBinding } = enforceBindingPolicy({ commandClass, binding, dir, command });
932
1272
  const envCtx = envContext();
933
1273
  let cachedStore = null;
934
- const resolved = await resolveContext({
1274
+ const chosen = await resolveContext({
935
1275
  flagContext: typeof flags.context === "string" ? flags.context : null,
936
1276
  envContextName: process.env.BLOCOFY_CONTEXT || null,
937
1277
  envCtx,
@@ -941,14 +1281,17 @@ async function prepareTarget({ command, commandClass, dir, flags, needs, mode, r
941
1281
  isTTY: Boolean(process.stdin.isTTY && process.stderr.isTTY),
942
1282
  prompt: promptContext,
943
1283
  });
944
- precheckContext({ binding, resolved });
945
- const secrets = resolved.env ? resolved.env.secrets : readSecrets(resolved.name, resolved.context);
1284
+ precheckContext({ binding, resolved: chosen });
1285
+ const { resolved, secrets, renewToken } = await credentialsFor(chosen);
946
1286
  registerSecret(secrets.devToken);
947
1287
  registerSecret(secrets.apiKey);
948
1288
  assertCredentialTypes({ resolved, secrets });
949
1289
 
950
1290
  const hasDev = Boolean(resolved.context.dev && secrets.devToken);
951
1291
  const hasApi = Boolean(resolved.context.api && secrets.apiKey);
1292
+ if (needs === "dev" && !hasDev && resolved.oauth) {
1293
+ throw new TargetError("LOGIN_REQUIRED", `Context "${resolved.name}" is a CLI login, but the site has no domain yet, so the theme-file endpoints (/api/dev) cannot be reached. Nothing was sent. Give the site a domain in the panel, then log in again: blocofy login --context ${resolved.name}`, { context: resolved.name }, 1);
1294
+ }
952
1295
  if (needs === "dev" && !hasDev) {
953
1296
  throw new TargetError("LOGIN_REQUIRED", `Login required: context "${resolved.name}" has no dev token. Run \`blocofy login${resolved.env ? "" : ` --context ${resolved.name}`}\` (or set BLOCOFY_URL + BLOCOFY_TOKEN).`, { context: resolved.name }, 1);
954
1297
  }
@@ -985,6 +1328,7 @@ async function prepareTarget({ command, commandClass, dir, flags, needs, mode, r
985
1328
  binding,
986
1329
  newBinding,
987
1330
  display,
1331
+ renewToken,
988
1332
  };
989
1333
  }
990
1334
 
@@ -1036,6 +1380,64 @@ async function themePull(rest) {
1036
1380
  bindAfterPull(target, dir);
1037
1381
  }
1038
1382
 
1383
+ // ── draft-only logins write into their own theme work (ADR-0014 §3.5, P4 follow-up) ───────────────────────
1384
+
1385
+ /** Profiles that never write a live or implicit target: their writes go to their own theme work. */
1386
+ const DRAFT_ONLY_PROFILES = new Set(["theme-dev", "review", "service-ci"]);
1387
+
1388
+ /** The project's saved work: `.blocofy/local.json` (theme work start / init), else `.blocofy/init.json`. */
1389
+ function savedWorkOf(binding) {
1390
+ const local = readSavedWork(binding);
1391
+ if (local?.handle && local.theme) return local;
1392
+ let init = null;
1393
+ try {
1394
+ init = readInitState(binding.root);
1395
+ } catch {
1396
+ init = null;
1397
+ }
1398
+ if (init && isWorkHandle(init.work_handle) && String(init.site_id) === String(binding.project.site_id)) {
1399
+ return { handle: init.work_handle, theme: typeof init.work_theme === "string" ? init.work_theme : null };
1400
+ }
1401
+ return local?.handle ? local : null;
1402
+ }
1403
+
1404
+ /**
1405
+ * Offline (no request): when the context this command will use carries a draft-only profile (a browser login, or a
1406
+ * recorded profile), `{ profile, work }` with the project's saved work (or null); otherwise null — then the command
1407
+ * behaves as before. Any resolution problem returns null and is reported by `prepareTarget` as usual.
1408
+ */
1409
+ async function draftOnlyDefaults(dir, flags) {
1410
+ let binding;
1411
+ let resolved;
1412
+ try {
1413
+ binding = findBinding(dir);
1414
+ resolved = await resolveContext({ flagContext: typeof flags.context === "string" ? flags.context : null, envContextName: process.env.BLOCOFY_CONTEXT || null, envCtx: envContext(), getStore: () => loadStore(), binding, isTTY: false, prompt: null });
1415
+ } catch {
1416
+ return null;
1417
+ }
1418
+ const profile = resolved.context?.oauth?.profile ?? resolved.context?.profile ?? null;
1419
+ if (!profile || !DRAFT_ONLY_PROFILES.has(profile.id)) return null;
1420
+ return { profile, work: binding ? savedWorkOf(binding) : null };
1421
+ }
1422
+
1423
+ function themeWorkRequired(profile, command) {
1424
+ return withLines(
1425
+ new TargetError(
1426
+ "THEME_WORK_REQUIRED",
1427
+ `This login is draft-only (profile ${profile.id}): \`${command}\` writes only into its own theme work, and this project has no saved work. Nothing was sent. Set one up: blocofy init <dir> (a new project) or blocofy theme work start (this project); or name the target: --work <wk_…> / --instance <theme>.`,
1428
+ { profile: profile.id },
1429
+ 3,
1430
+ ),
1431
+ [
1432
+ `Bu giriş yalnız taslak üzerinde çalışır ("${profile.label ?? profile.id}"): \`${command}\` yalnız kendi tema çalışmasına yazar ve bu projede kayıtlı bir tema çalışması yok. Hiçbir şey gönderilmedi.`,
1433
+ " Yeni proje: blocofy init <dizin> · bu projede yeni çalışma: blocofy theme work start",
1434
+ " Ya da hedefi açıkça ver: --work <wk_…> / --instance <tema>",
1435
+ ],
1436
+ );
1437
+ }
1438
+
1439
+ const savedWorkNote = (work) => `Kayıtlı tema çalışması kullanılıyor: ${work.handle}${work.theme ? ` (tema ${work.theme})` : ""} — başka bir hedef için --work / --instance ver.`;
1440
+
1039
1441
  async function themePush(rest) {
1040
1442
  const { flags, positionals } = parseArgsOrExit(rest, KNOWN.themePush);
1041
1443
  const dir = resolve(positionals[0] ?? process.cwd());
@@ -1052,7 +1454,17 @@ async function themePush(rest) {
1052
1454
  // Theme work: `--work <wk_…>` names the target itself — that work's own draft theme, read from the v1 API (the
1053
1455
  // work belongs to the API key) and written through the dev token as `--draft --instance <work theme>`. Both pairs
1054
1456
  // must resolve to the same site (prepareTarget "both"); the work must be open. Never live.
1055
- const workHandle = flags.work === undefined ? null : flags.work;
1457
+ // A draft-only login with no explicit target writes into the project's saved work (explicit flags win).
1458
+ let savedWork = null;
1459
+ if (flags.work === undefined && !instanceFlag && !flags.live) {
1460
+ const d = await draftOnlyDefaults(dir, flags);
1461
+ if (d) {
1462
+ if (!d.work) throw themeWorkRequired(d.profile, "theme push");
1463
+ savedWork = d.work.handle;
1464
+ if (!JSON_MODE) console.error(savedWorkNote(d.work));
1465
+ }
1466
+ }
1467
+ const workHandle = flags.work === undefined ? savedWork : flags.work;
1056
1468
  let workTarget = null;
1057
1469
  if (workHandle !== null) {
1058
1470
  if (!isWorkHandle(workHandle)) throw new TargetError("USAGE", "--work needs a work handle (wk_…, from `blocofy theme work start`). Nothing was sent.", {}, 1);
@@ -2147,12 +2559,22 @@ async function themeDev(rest) {
2147
2559
 
2148
2560
  // CF-T2: draft sync mutates the site (remote-mutation, binding required); `--no-sync` only renders (read).
2149
2561
  const noSync = Boolean(flags["no-sync"]);
2562
+ // A draft-only login syncs into the project's saved work's theme unless --instance names another target.
2563
+ let savedInstance = null;
2564
+ if (!noSync && typeof flags.instance !== "string") {
2565
+ const d = await draftOnlyDefaults(themeDir, flags);
2566
+ if (d) {
2567
+ if (!d.work?.theme) throw themeWorkRequired(d.profile, "theme dev");
2568
+ savedInstance = d.work.theme;
2569
+ if (!JSON_MODE) console.error(savedWorkNote(d.work));
2570
+ }
2571
+ }
2150
2572
  const target = await prepareTarget({ command: "theme dev", commandClass: noSync ? "read" : "remote-mutation", dir: themeDir, flags, needs: "dev", mode: noSync ? "read · local preview" : "draft" });
2151
2573
  const creds = target.dev;
2152
2574
  const port = Number(flags.port) || 3030;
2153
2575
  // #989: `--instance <handle>` names the draft to sync into, for a site where the platform refuses to pick one. Draft
2154
2576
  // sync never writes the live theme, so the live theme's handle is refused here.
2155
- const devInstance = typeof flags.instance === "string" ? flags.instance : null;
2577
+ const devInstance = typeof flags.instance === "string" ? flags.instance : savedInstance;
2156
2578
  if (devInstance && instanceMaybeLive(devInstance, target.identity?.liveThemeId ?? null)) {
2157
2579
  console.error(`✗ ${devInstance} is (or could not be told apart from) the LIVE theme. 'theme dev' syncs to a draft only; pick a draft handle (\`blocofy status\`) or use --no-sync.`);
2158
2580
  process.exit(2);
@@ -2228,7 +2650,8 @@ async function themeDev(rest) {
2228
2650
  const handle = startDevServer({
2229
2651
  dir: themeDir,
2230
2652
  url: creds.url,
2231
- token: creds.token,
2653
+ // A CLI login's access token lives 10 minutes: the server asks for a fresh one per request.
2654
+ token: target.renewToken ?? creds.token,
2232
2655
  port,
2233
2656
  // Taslak senkronu dev session'a BAĞLI DEĞİL: `pushTheme({draft:true})` /api/dev/theme'e gider ve
2234
2657
  // session'dan hiçbir veri kullanmaz. Bu satır `Boolean(session)` iken, session 410 alınca senkron
@@ -2653,6 +3076,137 @@ async function themeWorkCancel(rest) {
2653
3076
  console.log(`✓ Çalışma iptal edildi: ${handle}. Canlı site değişmedi; çalışmanın teması tema kitaplığında duruyor.`);
2654
3077
  }
2655
3078
 
3079
+ // ── blocofy init (ADR-0014 §5.6, wave P4) ─────────────────────────────────────────────────────────────────
3080
+
3081
+ const INIT_USAGE = "blocofy init [dir] [--site <handle|slug>] [--context <name>] [--api-url <url>] [--no-browser] [--insecure-storage]";
3082
+
3083
+ /** The context a resumed init directory recorded (`.blocofy/local.json`), if any. */
3084
+ function savedInitContext(dir) {
3085
+ try {
3086
+ const local = JSON.parse(readFileSync(join(dir, ".blocofy", "local.json"), "utf8"));
3087
+ return typeof local?.context === "string" && local.context ? local.context : null;
3088
+ } catch {
3089
+ return null;
3090
+ }
3091
+ }
3092
+
3093
+ /**
3094
+ * `blocofy init [dir]`: pre-checks without any request; then the credential (a saved context, env credentials, or a
3095
+ * browser login on a terminal); then the state machine of lib/init.mjs. Exit 0 only when a preview exists and the live
3096
+ * theme read back is the one read before; 5 when the live theme changed meanwhile; 3 for a directory/site refusal.
3097
+ */
3098
+ async function initCommand(rest) {
3099
+ const { flags, positionals } = parseArgsOrExit(rest, KNOWN.init);
3100
+ if (positionals.length > 1) throw new TargetError("USAGE", `Usage: ${INIT_USAGE}`, {}, 1);
3101
+ const dir = resolve(positionals[0] ?? process.cwd());
3102
+ const siteArg = typeof flags.site === "string" ? flags.site : null;
3103
+ const unattended = isUnattended();
3104
+
3105
+ // 1. Pre-checks: nothing sent, nothing written.
3106
+ const pre = inspectInitDir(dir);
3107
+ if (pre.kind === "dirty") {
3108
+ throw new InitError("INIT_DIR_NOT_EMPTY", `${dir} is not empty and is not a Blocofy project. Nothing was written. Run \`blocofy init\` in a new, empty directory (init never overwrites files).`, {
3109
+ exitCode: 3,
3110
+ details: { dir },
3111
+ lines: ["Bu dizin boş değil ve bir Blocofy projesi değil; hiçbir şeyin üzerine yazılmadı.", " Boş, yeni bir dizinde çalıştır: blocofy init <yeni-dizin>"],
3112
+ });
3113
+ }
3114
+ if (pre.kind === "legacy_project") {
3115
+ throw new InitError("INIT_ALREADY_BOUND", `${dir} is already bound to a site (by \`link\` or \`theme pull\`); init does not take it over. Nothing was written. In that project use: blocofy theme work start`, {
3116
+ exitCode: 3,
3117
+ details: { dir },
3118
+ lines: ["Bu dizin zaten bir siteye bağlı (link ya da theme pull ile); init onu sahiplenmez. Hiçbir şey yazılmadı.", " O projede yeni bir tema çalışması başlat: blocofy theme work start"],
3119
+ });
3120
+ }
3121
+ if (siteArg && pre.kind === "resume" && String(pre.init.site_id) !== siteArg && pre.project?.site_slug !== siteArg) {
3122
+ throw new InitError("INIT_SITE_MISMATCH", `${dir} was set up for site ${pre.project?.site_slug ?? pre.init.site_id}, not ${siteArg}. Nothing was sent or written.`, { exitCode: 3, details: { dir } });
3123
+ }
3124
+ // Unattended: never a browser, never a guessed site.
3125
+ if (unattended && !siteArg) {
3126
+ throw new InitError("INIT_SITE_REQUIRED", "In a non-interactive run, init needs the site named explicitly: --site <handle|slug> (and a saved --context or env credentials). Nothing was sent.", {
3127
+ exitCode: 3,
3128
+ lines: ["Etkileşimsiz çalıştırmada init hangi siteye kurulacağını tahmin etmez; hiçbir şey gönderilmedi.", " Siteyi açıkça ver: blocofy init <dizin> --site <site> --context <giriş>"],
3129
+ });
3130
+ }
3131
+
3132
+ // 2. The credential.
3133
+ const envCtx = envContext();
3134
+ let contextName = typeof flags.context === "string" ? flags.context : process.env.BLOCOFY_CONTEXT || (envCtx ? ENV_CONTEXT : null) || (pre.kind === "resume" ? savedInitContext(dir) : null);
3135
+ if (!contextName) {
3136
+ if (unattended) {
3137
+ throw new InitError("INIT_LOGIN_REQUIRED", "No credential for init: pass --context <name> of a saved login, or set env credentials. A non-interactive run never opens a browser. Nothing was sent.", { exitCode: 3 });
3138
+ }
3139
+ ({ name: contextName } = await browserLoginAndSave({ flags, contextName: null, siteArg }));
3140
+ }
3141
+ const chosen = await resolveContext({ flagContext: contextName, envContextName: null, envCtx, getStore: () => loadStore(), binding: null });
3142
+ const { resolved, secrets, renewToken } = await credentialsFor(chosen);
3143
+ registerSecret(secrets.devToken);
3144
+ registerSecret(secrets.apiKey);
3145
+ assertCredentialTypes({ resolved, secrets });
3146
+ if (!(resolved.context.api && secrets.apiKey) || !(resolved.context.dev && secrets.devToken)) {
3147
+ throw new TargetError("LOGIN_REQUIRED", `Context "${resolved.name}" cannot run init: it needs the v1 API (theme work, preview) and the theme files endpoint. Log in with \`blocofy login\` (one login covers both) or add the missing pair.`, { context: resolved.name }, 1);
3148
+ }
3149
+ const identity = await verifyTarget({ resolved, secrets, binding: null, retry });
3150
+ for (const w of identity.warnings ?? []) printWarning(w, { json: JSON_MODE });
3151
+ if (siteArg && !siteMatches(identity.site, siteArg)) {
3152
+ throw new InitError("INIT_SITE_MISMATCH", `Context "${resolved.name}" is for ${identity.site.slug ?? identity.site.id}, not ${siteArg}. Nothing was sent or written.`, { exitCode: 3, details: { context: resolved.name, site: identity.site.id } });
3153
+ }
3154
+ if (!JSON_MODE) printTarget(targetData({ site: identity.site, url: resolved.context.api.url, platformOrigin: identity.platformOrigin, contextName: resolved.name, contextSource: chosen.source, contextOverrides: [], bindingLabel: pre.kind === "resume" ? "this init directory" : "none (new init)", command: "init", mode: "draft · new work" }));
3155
+
3156
+ // 3. The state machine.
3157
+ const api = initApi({
3158
+ apiUrl: resolved.context.api.url,
3159
+ devUrl: resolved.context.dev.url,
3160
+ token: renewToken ?? secrets.apiKey,
3161
+ devToken: renewToken ?? secrets.devToken,
3162
+ onRetry,
3163
+ });
3164
+ const result = await runInit({
3165
+ dir,
3166
+ identity,
3167
+ contextName: resolved.env ? ENV_CONTEXT : resolved.name,
3168
+ profile: resolved.context.oauth?.profile ?? null,
3169
+ api,
3170
+ log: (line) => {
3171
+ if (!JSON_MODE) console.error(line);
3172
+ },
3173
+ });
3174
+
3175
+ const rel = relative(process.cwd(), dir) || ".";
3176
+ if (!result.liveUnchanged) {
3177
+ throw new InitError("INIT_LIVE_CHANGED", `The live theme read back after init (${result.liveAfter ?? "none"}) is not the one read before it started (${result.liveBefore ?? "none"}). init never writes the live site; the change came from elsewhere. Not reported as a success.`, {
3178
+ exitCode: 5,
3179
+ details: { live_before: result.liveBefore, live_after: result.liveAfter, work: result.work.id },
3180
+ lines: [
3181
+ `Canlı tema init başladığından beri değişti (önce: ${result.liveBefore ?? "yok"}, şimdi: ${result.liveAfter ?? "yok"}). Bu yüzden başarı denmedi.`,
3182
+ " init canlı siteye yazmaz; değişiklik panelden ya da başka bir bağlantıdan gelmiş olabilir. Panelde tema geçmişine bak.",
3183
+ ` Çalışman ve dosyaların yerinde: ${result.work.id} → ${rel}`,
3184
+ ],
3185
+ });
3186
+ }
3187
+ if (result.state !== "previewed") {
3188
+ throw new InitError("INIT_PREVIEW_UNAVAILABLE", `The project is set up (work ${result.work.id}, files in ${rel}) and the live site did not change, but no preview link could be made (${result.preview}: the work's theme has no page with a plain address). Run \`blocofy init\` again to retry the preview.`, {
3189
+ exitCode: 1,
3190
+ details: { work: result.work.id, preview: result.preview },
3191
+ lines: [
3192
+ "Proje hazır ve canlı siten değişmedi, ama önizleme bağlantısı oluşturulamadı: çalışmanın temasında adresi olan bir sayfa yok.",
3193
+ ` Aynı dizinde yeniden çalıştırınca yalnız önizleme denenir: blocofy init ${rel}`,
3194
+ ],
3195
+ });
3196
+ }
3197
+ if (JSON_MODE) {
3198
+ console.log(JSON.stringify({ init: { dir, state: result.state, work: { id: result.work.id, theme: result.work.theme }, preview_url: result.previewUrl, preview_created_earlier: result.previewCreatedEarlier, live_unchanged: true, live_theme: result.liveAfter, context: resolved.name, site: identity.site } }, null, 2));
3199
+ return;
3200
+ }
3201
+ console.log("✓ Taslak hazır. Canlı siten değişmedi.");
3202
+ console.log(` Çalışma: ${result.work.id} (tema ${result.work.theme}) — dosyalar: ${rel}`);
3203
+ if (result.previewUrl) console.log(` Önizleme (bir kez gösterilir; paylaşılabilir, süresi dolar): ${result.previewUrl}`);
3204
+ else console.log(" Önizleme bağlantısı daha önce oluşturuldu (bağlantılar bir kez gösterilir).");
3205
+ console.log(`Sonraki adım: dosyaları düzenle, sonra blocofy theme push ${rel} --draft --work ${result.work.id}`);
3206
+ console.log(` Yayın için insan onayı iste: blocofy theme work request-approval ${result.work.id}`);
3207
+ console.log(`technical: live theme ${result.liveAfter ?? "none"} read before and after; state in ${join(rel, ".blocofy", "init.json")}`);
3208
+ }
3209
+
2656
3210
  const THEME_WORK_USAGE = "blocofy theme work start|status|resume|seal|request-approval|cancel … (see `blocofy --help`)";
2657
3211
 
2658
3212
  async function themeWork(rest) {
@@ -2868,6 +3422,7 @@ function commandKey(a, b) {
2868
3422
  // command → handler. Every failure exits through failAndExit (exit codes 1/2/3, --json envelope last).
2869
3423
  const COMMANDS = {
2870
3424
  login: login,
3425
+ init: initCommand,
2871
3426
  contexts: contextsCommand,
2872
3427
  use: useCommand,
2873
3428
  logout: logoutCommand,