@wix/himalaya-cli 0.1673.0 → 0.1675.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/dist/cli.mjs CHANGED
@@ -51,6 +51,7 @@ __export(client_exports, {
51
51
  MAX_PUBLISH_BODY_BYTES: () => MAX_PUBLISH_BODY_BYTES,
52
52
  ServeCliClient: () => ServeCliClient,
53
53
  encodePublishBody: () => encodePublishBody,
54
+ measurePublishBody: () => measurePublishBody,
54
55
  publishReleaseBody: () => publishReleaseBody,
55
56
  publishReleaseBodyBytes: () => publishReleaseBodyBytes,
56
57
  publishReleaseWireBytes: () => publishReleaseWireBytes
@@ -66,12 +67,19 @@ function publishReleaseWireBytes(payload, meta, draft = false) {
66
67
  return encodePublishBody(publishReleaseBody(payload, meta, draft)).bytes.byteLength;
67
68
  }
68
69
  function encodePublishBody(body) {
69
- const plain2 = Buffer.from(JSON.stringify(body), "utf8");
70
+ return encodePlainPublishBody(Buffer.from(JSON.stringify(body), "utf8"));
71
+ }
72
+ function encodePlainPublishBody(plain2) {
70
73
  if (plain2.byteLength <= MAX_PUBLISH_BODY_BYTES || plain2.byteLength > MAX_DECODED_PUBLISH_BODY_BYTES) {
71
74
  return { bytes: plain2, gzip: false };
72
75
  }
73
76
  return { bytes: gzipSync(plain2), gzip: true };
74
77
  }
78
+ function measurePublishBody(payload, meta, draft = false) {
79
+ const plain2 = Buffer.from(JSON.stringify(publishReleaseBody(payload, meta, draft)), "utf8");
80
+ const { bytes: bytes2, gzip } = encodePlainPublishBody(plain2);
81
+ return { bodyBytes: plain2.byteLength, wireBytes: bytes2.byteLength, gzip };
82
+ }
75
83
  var MAX_PUBLISH_BODY_BYTES, MAX_DECODED_PUBLISH_BODY_BYTES, CREDENTIAL_HEADERS, ServeCliClient;
76
84
  var init_client = __esm({
77
85
  "../serve-cli/src/client.ts"() {
@@ -650,12 +658,15 @@ __export(config_exports, {
650
658
  BUILTIN_TARGETS: () => BUILTIN_TARGETS,
651
659
  clearControlToken: () => clearControlToken,
652
660
  defaultTargetsPath: () => defaultTargetsPath,
661
+ loadPendingDeviceLogin: () => loadPendingDeviceLogin,
653
662
  loadSiteClient: () => loadSiteClient,
654
663
  loadTargetsFile: () => loadTargetsFile,
655
664
  resolveTarget: () => resolveTarget,
656
665
  resolveTargetName: () => resolveTargetName,
657
666
  saveControlToken: () => saveControlToken,
658
- saveSiteClient: () => saveSiteClient
667
+ savePendingDeviceLogin: () => savePendingDeviceLogin,
668
+ saveSiteClient: () => saveSiteClient,
669
+ swapPendingDeviceLogin: () => swapPendingDeviceLogin
659
670
  });
660
671
  import { homedir } from "node:os";
661
672
  import { join, dirname } from "node:path";
@@ -670,7 +681,8 @@ function loadTargetsFile(path2 = defaultTargetsPath()) {
670
681
  function saveControlToken(target, token, path2 = defaultTargetsPath()) {
671
682
  const file2 = loadTargetsFile(path2);
672
683
  file2.targets = file2.targets ?? {};
673
- file2.targets[target] = { ...file2.targets[target], controlToken: token };
684
+ const { pendingDeviceLogin: _superseded, ...rest } = file2.targets[target] ?? {};
685
+ file2.targets[target] = { ...rest, controlToken: token };
674
686
  writeTargetsFilePrivate(path2, file2);
675
687
  return path2;
676
688
  }
@@ -682,6 +694,35 @@ function saveSiteClient(target, msid, client4, path2 = defaultTargetsPath()) {
682
694
  writeTargetsFilePrivate(path2, file2);
683
695
  return path2;
684
696
  }
697
+ function savePendingDeviceLogin(target, pending2, path2 = defaultTargetsPath()) {
698
+ const file2 = loadTargetsFile(path2);
699
+ const t2 = file2.targets?.[target];
700
+ if (!pending2 && !t2?.pendingDeviceLogin) return path2;
701
+ file2.targets = file2.targets ?? {};
702
+ const next = { ...t2 };
703
+ if (pending2) next.pendingDeviceLogin = pending2;
704
+ else delete next.pendingDeviceLogin;
705
+ file2.targets[target] = next;
706
+ writeTargetsFilePrivate(path2, file2);
707
+ return path2;
708
+ }
709
+ function swapPendingDeviceLogin(target, deviceCode, next, path2 = defaultTargetsPath()) {
710
+ const file2 = loadTargetsFile(path2);
711
+ const t2 = file2.targets?.[target];
712
+ if (t2?.pendingDeviceLogin?.deviceCode !== deviceCode) return false;
713
+ const copy = { ...t2 };
714
+ if (next) copy.pendingDeviceLogin = next;
715
+ else delete copy.pendingDeviceLogin;
716
+ file2.targets[target] = copy;
717
+ writeTargetsFilePrivate(path2, file2);
718
+ return true;
719
+ }
720
+ function loadPendingDeviceLogin(target, path2 = defaultTargetsPath()) {
721
+ const p2 = loadTargetsFile(path2).targets?.[target]?.pendingDeviceLogin;
722
+ if (!p2 || typeof p2 !== "object") return void 0;
723
+ const ok5 = typeof p2.deviceCode === "string" && p2.deviceCode !== "" && typeof p2.ownerIssue === "string" && typeof p2.userCode === "string" && typeof p2.verificationUri === "string" && Number.isFinite(p2.interval) && Number.isFinite(p2.expiresAt) && Number.isFinite(p2.lastPollAt);
724
+ return ok5 ? p2 : void 0;
725
+ }
685
726
  function loadSiteClient(msid, target, path2 = defaultTargetsPath()) {
686
727
  const targets = loadTargetsFile(path2).targets ?? {};
687
728
  const key3 = msid.toLowerCase();
@@ -707,8 +748,10 @@ function writeTargetsFilePrivate(path2, file2) {
707
748
  }
708
749
  function clearControlToken(target, path2 = defaultTargetsPath()) {
709
750
  const file2 = loadTargetsFile(path2);
710
- if (file2.targets?.[target]?.controlToken) {
711
- delete file2.targets[target].controlToken;
751
+ const t2 = file2.targets?.[target];
752
+ if (t2?.controlToken || t2?.pendingDeviceLogin) {
753
+ delete t2.controlToken;
754
+ delete t2.pendingDeviceLogin;
712
755
  writeFileSync(path2, JSON.stringify(file2, null, 2) + "\n");
713
756
  }
714
757
  return path2;
@@ -3108,6 +3151,7 @@ __export(dist_jobs_exports, {
3108
3151
  distJobSpec: () => distJobSpec,
3109
3152
  encodeDistParams: () => encodeDistParams,
3110
3153
  failureCodesOf: () => failureCodesOf,
3154
+ hasJobServiceEnded: () => hasJobServiceEnded,
3111
3155
  isBorrowableIosId: () => isBorrowableIosId,
3112
3156
  isSuccess: () => isSuccess,
3113
3157
  isTerminal: () => isTerminal,
@@ -3125,6 +3169,9 @@ __export(dist_jobs_exports, {
3125
3169
  function isTerminal(status) {
3126
3170
  return !!status && !IN_FLIGHT.has(status);
3127
3171
  }
3172
+ function hasJobServiceEnded(status) {
3173
+ return !!status && JOB_SERVICE_ENDED.has(status);
3174
+ }
3128
3175
  function isSuccess(status) {
3129
3176
  return status === "SUCCESS";
3130
3177
  }
@@ -3445,7 +3492,7 @@ function distJobSpec(req) {
3445
3492
  ...req.xcodeVersion ? { xcodeVersion: req.xcodeVersion } : {}
3446
3493
  };
3447
3494
  }
3448
- var DIST_ERROR_CODES, APPLE_ERROR_CODES_MAX, IN_FLIGHT, SCOPE_CREATE, SCOPE_READ, SCOPE_CANCEL, DEFAULT_BASE_URL, DEFAULT_OAUTH_URL, TOKEN_TTL_MS, JobServiceError, JobServiceBroker, CUSTOMER_UPLOAD_LEASE_MS, CUSTOMER_UPLOAD_RETRY_DELAYS_MS, CUSTOMER_UPLOAD_MAX_ATTEMPTS, CUSTOMER_UPLOAD_ABANDONED, MAX_MEASURABLE_IDENTITY_WINDOW, DIST_SHELLS, DEFAULT_DIST_SHELL, DEFAULT_BORROWABLE_IOS_IDS, BUNDLE_ID_RE, DEFAULT_DIST_SIGNING, WIX_MANAGED_SIGNING_ALIASES, DEFAULT_ANDROID_SIGNING, ANDROID_SIGNING_POLICIES, ANDROID_SIGNING_ALIASES, DEFAULT_ANDROID_FORMAT, ANDROID_FORMATS, ANDROID_FORMAT_NOT_BUILT, ANDROID_FORMAT_WRONG_SIGNER, ANDROID_FORMAT_NOT_REQUESTED, DEFAULT_ANDROID_BUILD_TYPE, ANDROID_BUILD_TYPES, ANDROID_BUILD_TYPE_NOT_BUILT, DEFAULT_GIT_URL, DIST_PACKAGE_NAME, DIST_PARAMS_FLAG, MAX_COMMAND_CHARS;
3495
+ var DIST_ERROR_CODES, APPLE_ERROR_CODES_MAX, IN_FLIGHT, JOB_SERVICE_ENDED, SCOPE_CREATE, SCOPE_READ, SCOPE_CANCEL, DEFAULT_BASE_URL, DEFAULT_OAUTH_URL, TOKEN_TTL_MS, JobServiceError, JobServiceBroker, CUSTOMER_UPLOAD_LEASE_MS, CUSTOMER_UPLOAD_RETRY_DELAYS_MS, CUSTOMER_UPLOAD_MAX_ATTEMPTS, CUSTOMER_UPLOAD_ABANDONED, MAX_MEASURABLE_IDENTITY_WINDOW, DIST_SHELLS, DEFAULT_DIST_SHELL, DEFAULT_BORROWABLE_IOS_IDS, BUNDLE_ID_RE, DEFAULT_DIST_SIGNING, WIX_MANAGED_SIGNING_ALIASES, DEFAULT_ANDROID_SIGNING, ANDROID_SIGNING_POLICIES, ANDROID_SIGNING_ALIASES, DEFAULT_ANDROID_FORMAT, ANDROID_FORMATS, ANDROID_FORMAT_NOT_BUILT, ANDROID_FORMAT_WRONG_SIGNER, ANDROID_FORMAT_NOT_REQUESTED, DEFAULT_ANDROID_BUILD_TYPE, ANDROID_BUILD_TYPES, ANDROID_BUILD_TYPE_NOT_BUILT, DEFAULT_GIT_URL, DIST_PACKAGE_NAME, DIST_PARAMS_FLAG, MAX_COMMAND_CHARS;
3449
3496
  var init_dist_jobs = __esm({
3450
3497
  "../../core/serve-control/src/dist-jobs.ts"() {
3451
3498
  init_define_HHP_CATALOG();
@@ -3482,6 +3529,7 @@ var init_dist_jobs = __esm({
3482
3529
  ];
3483
3530
  APPLE_ERROR_CODES_MAX = 5;
3484
3531
  IN_FLIGHT = /* @__PURE__ */ new Set(["CREATED", "QUEUED", "WORKING"]);
3532
+ JOB_SERVICE_ENDED = /* @__PURE__ */ new Set(["SUCCESS", "FAILURE", "CANCELED", "TIMEOUT", "INTERNAL_ERROR"]);
3485
3533
  SCOPE_CREATE = "MRE.JOB_CREATE";
3486
3534
  SCOPE_READ = "MRE.JOB_READ";
3487
3535
  SCOPE_CANCEL = "MRE.CANCEL_JOB";
@@ -15949,6 +15997,7 @@ function webViewOriginAllowed(url, origins) {
15949
15997
  }
15950
15998
  var init_webview_origin = __esm({
15951
15999
  "../../core/ts/src/webview-origin.ts"() {
16000
+ "use strict";
15952
16001
  init_define_HHP_CATALOG();
15953
16002
  }
15954
16003
  });
@@ -31399,7 +31448,6 @@ function resolveIdiom(tokens2, ctx = {}) {
31399
31448
  var IDIOM_CONTEXTS, UNSAFE_KEYS;
31400
31449
  var init_idiom = __esm({
31401
31450
  "../../core/ts/src/idiom.ts"() {
31402
- "use strict";
31403
31451
  init_define_HHP_CATALOG();
31404
31452
  IDIOM_CONTEXTS = {
31405
31453
  ios: { native: ["ios"] },
@@ -152695,6 +152743,7 @@ var wix_owner_exports = {};
152695
152743
  __export(wix_owner_exports, {
152696
152744
  TOKEN_EXCHANGE_URL: () => TOKEN_EXCHANGE_URL,
152697
152745
  WIX_CLI_FIX: () => WIX_CLI_FIX,
152746
+ WIX_TOKEN_RE: () => WIX_TOKEN_RE,
152698
152747
  WIX_VIDEO_GATEWAY_URL: () => WIX_VIDEO_GATEWAY_URL,
152699
152748
  WixApiError: () => WixApiError,
152700
152749
  WixTokenError: () => WixTokenError,
@@ -152727,6 +152776,9 @@ function resolveSiteId(flag2) {
152727
152776
  }
152728
152777
  return id;
152729
152778
  }
152779
+ function redactWixCredentials(s2) {
152780
+ return s2.replace(WIX_CREDENTIAL_G, (m2) => `${/^(IDN2|IST|OauthNG\.JWS|SRV\.JWS)/.exec(m2)?.[1] ?? "token"}.<redacted>`);
152781
+ }
152730
152782
  async function siteToken(msid, spawnImpl = spawn3, fetchImpl = fetch) {
152731
152783
  if (!process.env.WIX_TEST_TOKEN?.trim()) {
152732
152784
  const key3 = siteApiKey();
@@ -152812,7 +152864,7 @@ function refreshableSiteToken(msid, token) {
152812
152864
  }
152813
152865
  function redactTokens(v2) {
152814
152866
  const s2 = typeof v2 === "string" ? v2 : JSON.stringify(v2 ?? null);
152815
- return s2.replace(/OauthNG\.JWS\.[A-Za-z0-9._-]+/g, "OauthNG.JWS.<redacted>").slice(0, 300);
152867
+ return redactWixCredentials(s2).slice(0, 300);
152816
152868
  }
152817
152869
  function exchangeRefusal(status, body, msid) {
152818
152870
  const b2 = body ?? {};
@@ -152901,7 +152953,7 @@ async function mintToken(args, label4, cacheKey, spawnImpl) {
152901
152953
  const timer = setTimeout(
152902
152954
  () => done(() => reject(new WixTokenError(
152903
152955
  "wix_cli_token_failed",
152904
- `\`${label4}\` printed no OauthNG token within ${TOKEN_MINT_TIMEOUT_MS}ms. Is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`,
152956
+ `\`${label4}\` printed no Wix token within ${TOKEN_MINT_TIMEOUT_MS}ms. Is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`,
152905
152957
  mintFailedFix(label4)
152906
152958
  ))),
152907
152959
  TOKEN_MINT_TIMEOUT_MS
@@ -152919,7 +152971,7 @@ async function mintToken(args, label4, cacheKey, spawnImpl) {
152919
152971
  child.on("error", (e2) => done(() => reject(spawnFailure(label4, e2))));
152920
152972
  child.on("exit", (code2) => done(() => reject(new WixTokenError(
152921
152973
  "wix_cli_token_failed",
152922
- `\`${label4}\` exited (code ${code2}) without printing an OauthNG token \u2014 is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`,
152974
+ `\`${label4}\` exited (code ${code2}) without printing a Wix token \u2014 is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`,
152923
152975
  mintFailedFix(label4)
152924
152976
  ))));
152925
152977
  });
@@ -152927,7 +152979,7 @@ async function mintToken(args, label4, cacheKey, spawnImpl) {
152927
152979
  return token;
152928
152980
  }
152929
152981
  function redactForError(buf) {
152930
- const cleaned = buf.replace(/OauthNG\.JWS\.[A-Za-z0-9._-]+/g, "OauthNG.JWS.<redacted>").replace(/\b[A-Za-z0-9_-]{40,}\b/g, "<redacted>");
152982
+ const cleaned = redactWixCredentials(buf).replace(/\b[A-Za-z0-9_-]{40,}\b/g, "<redacted>");
152931
152983
  const trimmed = cleaned.trim();
152932
152984
  return trimmed ? `Output (credentials redacted):
152933
152985
  ${trimmed.slice(0, 300)}` : "It printed nothing.";
@@ -153022,14 +153074,17 @@ async function mapLimit(items, limit, fn2) {
153022
153074
  }));
153023
153075
  return results;
153024
153076
  }
153025
- var API_BASE, WIX_VIDEO_GATEWAY_URL, tokenCache, TOKEN_RE, TOKEN_MINT_TIMEOUT_MS, TOKEN_EXCHANGE_URL, EXCHANGE_REFRESH_MARGIN_MS, EXCHANGE_DEFAULT_TTL_S, exchangeCache, recentExchanged, RECENT_EXCHANGED_PER_SITE, exchangeInFlight, SITE_TOKEN_EXCHANGE_FIX, ACCOUNT_TOKEN_KEY, WIX_CLI_FIX, WixTokenError, WixApiError, DEFAULT_TIMEOUT_MS;
153077
+ var API_BASE, WIX_VIDEO_GATEWAY_URL, tokenCache, WIX_CREDENTIAL, WIX_TOKEN_RE, TOKEN_RE, WIX_CREDENTIAL_G, TOKEN_MINT_TIMEOUT_MS, TOKEN_EXCHANGE_URL, EXCHANGE_REFRESH_MARGIN_MS, EXCHANGE_DEFAULT_TTL_S, exchangeCache, recentExchanged, RECENT_EXCHANGED_PER_SITE, exchangeInFlight, SITE_TOKEN_EXCHANGE_FIX, ACCOUNT_TOKEN_KEY, WIX_CLI_FIX, WixTokenError, WixApiError, DEFAULT_TIMEOUT_MS;
153026
153078
  var init_wix_owner = __esm({
153027
153079
  "src/wix-owner.ts"() {
153028
153080
  init_define_HHP_CATALOG();
153029
153081
  API_BASE = "https://www.wixapis.com";
153030
153082
  WIX_VIDEO_GATEWAY_URL = "https://manage.wix.com/_api/vod/public/graphql";
153031
153083
  tokenCache = /* @__PURE__ */ new Map();
153032
- TOKEN_RE = /OauthNG\.JWS\.[A-Za-z0-9._-]+/;
153084
+ WIX_CREDENTIAL = "(?:IDN2|IST|OauthNG\\.JWS|SRV\\.JWS)\\.[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]*)*";
153085
+ WIX_TOKEN_RE = new RegExp(WIX_CREDENTIAL);
153086
+ TOKEN_RE = WIX_TOKEN_RE;
153087
+ WIX_CREDENTIAL_G = new RegExp(WIX_CREDENTIAL, "g");
153033
153088
  TOKEN_MINT_TIMEOUT_MS = 3e4;
153034
153089
  TOKEN_EXCHANGE_URL = `${API_BASE}/oauth2/token`;
153035
153090
  EXCHANGE_REFRESH_MARGIN_MS = 6e4;
@@ -220391,6 +220446,73 @@ var init_release_patch2 = __esm({
220391
220446
  }
220392
220447
  });
220393
220448
 
220449
+ // src/publish-admission.ts
220450
+ var publish_admission_exports = {};
220451
+ __export(publish_admission_exports, {
220452
+ admitPublishBody: () => admitPublishBody,
220453
+ compressedPublishEligibility: () => compressedPublishEligibility,
220454
+ compressionNote: () => compressionNote,
220455
+ planCompressedUpload: () => planCompressedUpload,
220456
+ publishSizeFields: () => publishSizeFields
220457
+ });
220458
+ function compressedPublishEligibility(token) {
220459
+ if (!token) return "unknown";
220460
+ const parts = token.split(".");
220461
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return "unknown";
220462
+ const claims = decodeControlTokenClaims(token);
220463
+ if (!claims) return "unknown";
220464
+ if (claims.selfServe === true || claims.siteLease !== void 0) return "self_serve";
220465
+ if (claims.selfServe !== void 0) return "unknown";
220466
+ return typeof claims.sub === "string" && typeof claims.role === "string" && typeof claims.exp === "number" ? "eligible" : "unknown";
220467
+ }
220468
+ function admitPublishBody(size, ctx) {
220469
+ if (size.bodyBytes <= MAX_PUBLISH_BODY_BYTES) return { ok: true };
220470
+ if (size.bodyBytes > MAX_DECODED_PUBLISH_BODY_BYTES) return { ok: false, compressedUpload: "decoded_limit_exceeded" };
220471
+ if (ctx.eligibility === "self_serve") return { ok: false, compressedUpload: "self_serve_credential" };
220472
+ if (ctx.eligibility !== "eligible") return { ok: false, compressedUpload: "credential_unverified" };
220473
+ if (!size.gzip || size.wireBytes > MAX_PUBLISH_BODY_BYTES) return { ok: false, compressedUpload: "wire_limit_exceeded" };
220474
+ return { ok: true };
220475
+ }
220476
+ function planCompressedUpload(size, reserveBytes, gzipBytes) {
220477
+ const planningBytes = size.bodyBytes + reserveBytes;
220478
+ const planningWireBytes = planningBytes <= MAX_PUBLISH_BODY_BYTES || planningBytes > MAX_DECODED_PUBLISH_BODY_BYTES ? planningBytes : (size.gzip ? size.wireBytes : gzipBytes()) + reserveBytes;
220479
+ return {
220480
+ planningWireBytes,
220481
+ fitsIfEligible: planningBytes <= MAX_DECODED_PUBLISH_BODY_BYTES && planningWireBytes <= MAX_PUBLISH_BODY_BYTES
220482
+ };
220483
+ }
220484
+ function publishSizeFields(size, compressedUpload) {
220485
+ return {
220486
+ overageBytes: Math.max(0, size.bodyBytes - MAX_PUBLISH_BODY_BYTES),
220487
+ decodedLimit: MAX_DECODED_PUBLISH_BODY_BYTES,
220488
+ decodedOverageBytes: Math.max(0, size.bodyBytes - MAX_DECODED_PUBLISH_BODY_BYTES),
220489
+ // Only when the client would actually compress this body; over the decoded cap it is sent plain.
220490
+ ...size.gzip ? {
220491
+ wireBytes: size.wireBytes,
220492
+ wireLimit: MAX_PUBLISH_BODY_BYTES,
220493
+ wireOverageBytes: Math.max(0, size.wireBytes - MAX_PUBLISH_BODY_BYTES)
220494
+ } : {},
220495
+ compressedUpload
220496
+ };
220497
+ }
220498
+ function compressionNote(size, refusal2) {
220499
+ return COMPRESSION_NOTES[refusal2](size);
220500
+ }
220501
+ var COMPRESSION_NOTES;
220502
+ var init_publish_admission = __esm({
220503
+ "src/publish-admission.ts"() {
220504
+ init_define_HHP_CATALOG();
220505
+ init_owner_claim();
220506
+ init_client();
220507
+ COMPRESSION_NOTES = {
220508
+ decoded_limit_exceeded: () => `The body is over the ${MAX_DECODED_PUBLISH_BODY_BYTES}-byte decoded limit, so no transport can carry it.`,
220509
+ self_serve_credential: (s2) => `A gzip upload (${s2.wireBytes} bytes) is not accepted for a self-serve credential, which keeps the ${MAX_PUBLISH_BODY_BYTES}-byte plain limit.`,
220510
+ credential_unverified: (s2) => `A gzip upload (${s2.wireBytes} bytes) is accepted only for a provisioned, non-self-serve control token, and this credential cannot be read as one, so the ${MAX_PUBLISH_BODY_BYTES}-byte plain limit applies.`,
220511
+ wire_limit_exceeded: (s2) => `Even gzipped, the upload is ${s2.wireBytes} bytes, over the ${MAX_PUBLISH_BODY_BYTES}-byte wire limit.`
220512
+ };
220513
+ }
220514
+ });
220515
+
220394
220516
  // src/publish-size.ts
220395
220517
  var publish_size_exports = {};
220396
220518
  __export(publish_size_exports, {
@@ -247159,7 +247281,7 @@ async function accountToken2(spawnImpl = spawn7) {
247159
247281
  };
247160
247282
  const timer = setTimeout(
247161
247283
  () => done(() => reject(new Error(
247162
- `\`wix token\` printed no OauthNG token within ${TOKEN_MINT_TIMEOUT_MS2}ms. Is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`
247284
+ `\`wix token\` printed no Wix token within ${TOKEN_MINT_TIMEOUT_MS2}ms. Is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`
247163
247285
  ))),
247164
247286
  TOKEN_MINT_TIMEOUT_MS2
247165
247287
  );
@@ -247172,7 +247294,7 @@ async function accountToken2(spawnImpl = spawn7) {
247172
247294
  child.stderr?.on("data", scan);
247173
247295
  child.on("error", (e2) => done(() => reject(new Error(mintHelp2(e2.message)))));
247174
247296
  child.on("exit", (code2) => done(() => reject(new Error(
247175
- `\`wix token\` exited (code ${code2}) without printing an OauthNG token \u2014 is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`
247297
+ `\`wix token\` exited (code ${code2}) without printing a Wix token \u2014 is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`
247176
247298
  ))));
247177
247299
  });
247178
247300
  cached2 = token;
@@ -247234,7 +247356,7 @@ var init_wix_account2 = __esm({
247234
247356
  init_wix_owner();
247235
247357
  API_BASE2 = "https://www.wixapis.com";
247236
247358
  API_KEYS_URL = "https://manage.wix.com/account/api-keys";
247237
- TOKEN_RE2 = /OauthNG\.JWS\.[A-Za-z0-9._-]+/;
247359
+ TOKEN_RE2 = WIX_TOKEN_RE;
247238
247360
  TOKEN_MINT_TIMEOUT_MS2 = 3e4;
247239
247361
  DEFAULT_TIMEOUT_MS6 = Number(process.env.HIMI_WIX_TIMEOUT_MS) || 12e4;
247240
247362
  }
@@ -248239,6 +248361,7 @@ var init_push_errors = __esm({
248239
248361
  "push_failed",
248240
248362
  "binary_capability_gap",
248241
248363
  "depth_budget_exceeded",
248364
+ "compressed_publish_unsupported",
248242
248365
  "one_app_readiness_failed",
248243
248366
  "placeholder_site_binding",
248244
248367
  "auth_provider_invalid"
@@ -249426,7 +249549,7 @@ async function publishSizeCommand(ctx) {
249426
249549
  const { appId: appId3, contentDir: contentDir2, loadAuthoring: loadAuthoring2, resolutionFlag: resolutionFlag2, commandScratchDir: commandScratchDir2 } = await Promise.resolve().then(() => (init_cli_shared(), cli_shared_exports));
249427
249550
  const { collectAppSource: collectAppSource2, secretFindings: secretFindings2, zipAppSource: zipAppSource2, MAX_APP_SOURCE_BYTES: MAX_APP_SOURCE_BYTES2 } = await Promise.resolve().then(() => (init_app_source(), app_source_exports));
249428
249551
  const { composeReleasePayload: composeReleasePayload2, loadReleaseFromDir: loadReleaseFromDir2 } = await Promise.resolve().then(() => (init_release(), release_exports));
249429
- const { publishReleaseBodyBytes: publishReleaseBodyBytes2, MAX_PUBLISH_BODY_BYTES: MAX_PUBLISH_BODY_BYTES2 } = await Promise.resolve().then(() => (init_client(), client_exports));
249552
+ const { measurePublishBody: measurePublishBody2, publishReleaseBody: publishReleaseBody2, publishReleaseBodyBytes: publishReleaseBodyBytes2, MAX_PUBLISH_BODY_BYTES: MAX_PUBLISH_BODY_BYTES2, MAX_DECODED_PUBLISH_BODY_BYTES: MAX_DECODED_PUBLISH_BODY_BYTES2 } = await Promise.resolve().then(() => (init_client(), client_exports));
249430
249553
  if (reserveBytes > MAX_PUBLISH_BODY_BYTES2) return fail10("invalid_usage", "--reserve-bytes exceeds the entire publish budget", {}, 2);
249431
249554
  const { installContainedDevModuleRealm: installContainedDevModuleRealm2 } = await Promise.resolve().then(() => (init_contained_dev_module(), contained_dev_module_exports));
249432
249555
  const { installContainedAppConfigRealm: installContainedAppConfigRealm2 } = await Promise.resolve().then(() => (init_app_config_loader(), app_config_loader_exports));
@@ -249474,9 +249597,15 @@ async function publishSizeCommand(ctx) {
249474
249597
  const archive = zipAppSource2(collected.entries);
249475
249598
  const encoded3 = archive.toString("base64");
249476
249599
  const payload = await loadReleaseFromDir2(declared, out2);
249477
- const bodyBytes = publishReleaseBodyBytes2(composeReleasePayload2(payload, app2, encoded3), void 0, true);
249600
+ const releaseBody = composeReleasePayload2(payload, app2, encoded3);
249601
+ const { bodyBytes, wireBytes, gzip } = measurePublishBody2(releaseBody, void 0, true);
249478
249602
  const minimumBodyBytes = publishReleaseBodyBytes2(composeReleasePayload2(payload, "", encoded3), void 0, true);
249479
249603
  const planningBytes = bodyBytes + reserveBytes;
249604
+ const { planCompressedUpload: planCompressedUpload2 } = await Promise.resolve().then(() => (init_publish_admission(), publish_admission_exports));
249605
+ const { gzipSync: gzipSync3 } = await import("node:zlib");
249606
+ const plan = planCompressedUpload2({ bodyBytes, wireBytes, gzip }, reserveBytes, () => {
249607
+ return gzipSync3(Buffer.from(JSON.stringify(publishReleaseBody2(releaseBody, void 0, true)), "utf8")).byteLength;
249608
+ });
249480
249609
  const report9 = {
249481
249610
  app: app2,
249482
249611
  declared,
@@ -249492,6 +249621,21 @@ async function publishSizeCommand(ctx) {
249492
249621
  planningBytes,
249493
249622
  planningOverageBytes: Math.max(0, planningBytes - MAX_PUBLISH_BODY_BYTES2),
249494
249623
  withinMeasuredBudget: planningBytes <= MAX_PUBLISH_BODY_BYTES2 && encoded3.length <= MAX_APP_SOURCE_BYTES2,
249624
+ // What a compressed upload would cost, for planning ONLY. Whether push may send one depends
249625
+ // on the publisher credential, which this command never reads: it does not establish
249626
+ // eligibility, and the verdict above (`withinMeasuredBudget`, the exit code) stays on the
249627
+ // plain limit. A body under the plain limit goes out plain, so `wireBytes` equals `bodyBytes`
249628
+ // there; `planningWireBytes` is explained at `planCompressedUpload`.
249629
+ compressedUpload: {
249630
+ transport: gzip ? "gzip" : "plain",
249631
+ wireBytes,
249632
+ wireLimit: MAX_PUBLISH_BODY_BYTES2,
249633
+ decodedLimit: MAX_DECODED_PUBLISH_BODY_BYTES2,
249634
+ planningWireBytes: plan.planningWireBytes,
249635
+ fitsIfEligible: plan.fitsIfEligible && encoded3.length <= MAX_APP_SOURCE_BYTES2,
249636
+ eligibility: "not_evaluated",
249637
+ note: "Provisional and credential-free. A gzip upload is admitted only for a provisioned, non-self-serve control token that himi push can read; self-serve tokens and opaque proxy credentials (including the One App migration worker's draft broker) keep the plain limit. Final push remeasures the complete envelope."
249638
+ },
249495
249639
  source: { archivedBytes: archive.length, encodedBytes: encoded3.length, limit: MAX_APP_SOURCE_BYTES2, files: collected.entries.length, skipped: collected.skipped },
249496
249640
  screens: Object.keys(payload.screens).length,
249497
249641
  bundles: Object.keys(payload.bundles).length,
@@ -249628,7 +249772,8 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
249628
249772
  "input-evidence",
249629
249773
  "wix-token-stdin",
249630
249774
  "no-key",
249631
- "no-frame"
249775
+ "no-frame",
249776
+ "resume"
249632
249777
  ]);
249633
249778
  var SWITCH_FLAGS = new Set([...BOOLEAN_FLAGS].filter((name) => name !== "deep"));
249634
249779
  var SWITCH_CONSEQUENCE = {
@@ -249946,7 +250091,8 @@ var USAGE = `himi \u2014 the Himalaya authoring CLI (remote dev loop)
249946
250091
  NOT in git \u2014 prefer committing to assets/ instead)
249947
250092
  himi assets rm <name> [--live] drop an asset record; the next resolve falls back to the
249948
250093
  baked copy (bytes survive until a retention pass)
249949
- himi login [--browser|--device [--site <msid>] [--redirect-uri <uri>]|--wix [--wix-token-stdin]|--dpx] [--target <t>] [--no-open]
250094
+ himi login [--browser|--device [--site <msid>] [--redirect-uri <uri>] [--no-wait]|--wix [--wix-token-stdin]|--dpx] [--target <t>] [--no-open]
250095
+ himi login --device --resume [--timeout <s>] [--target <t>]
249950
250096
  get + store a scoped control token for push/promote
249951
250097
  --browser: sign in with your own Wix account in a browser
249952
250098
  on THIS machine (NO VPN, no BO) -> use with --target wix
@@ -249962,6 +250108,10 @@ var USAGE = `himi \u2014 the Himalaya authoring CLI (remote dev loop)
249962
250108
  --site <msid>: the owner also connects that site; you
249963
250109
  get its Headless client id (no Wix token), kept per
249964
250110
  site for \`himi site client list\`
250111
+ --no-wait: print the URL + code and exit at once;
250112
+ then \`himi login --device --resume\` polls for at
250113
+ most --timeout seconds (default 50): exit 0 signed
250114
+ in, exit 3 (device_pending) not approved yet
249965
250115
  --dpx: Wix employee path via an existing BO session
249966
250116
  (internal; --target bo)
249967
250117
  himi apps [list] | claim <slug> [--display-name <n>] [--account-id <id>] [--cookie <c>]
@@ -250015,6 +250165,12 @@ var USAGE = `himi \u2014 the Himalaya authoring CLI (remote dev loop)
250015
250165
  the LARGEST entries by name \u2014 move those out, or push with
250016
250166
  --no-source (which costs you himi pull for that release).
250017
250167
  Not the same limit as the whole publish body.
250168
+ The WHOLE body is capped at 8388608 bytes of JSON. Over
250169
+ that, a provisioned (not self-serve) control token sends
250170
+ it gzipped: up to 33554432 bytes decoded and 8388608 on
250171
+ the wire. A self-serve login or an opaque credential
250172
+ keeps the plain cap. A refusal names bodyBytes, wireBytes, both limits
250173
+ and compressedUpload (why gzip did not apply).
250018
250174
  himi push --only <selector>[,<selector>\u2026] (--draft|--live) [--from-release <id>]
250019
250175
  [--accept-regressions] [--accept-partial] [--app <slug>]
250020
250176
  publish ONLY the named items, derived from the app's live
@@ -250591,7 +250747,7 @@ var COMMANDS = [
250591
250747
  { name: "init", summary: "scaffold a starter content package (OTA-only; no native shells). --template <t> starts from a full reference app (branded-lite = consumer storefront over a Wix site; owner-lite = owner CRUD/management) instead of the minimal counter; --templates lists bundled ones; --remote fetches the template off the serve plane (falls back to the bundled copy offline). The new app also gets its agent files (the same set `himi agent-init` writes: AGENTS.md, CLAUDE.md, the himalaya skill, HIMALAYA.md, a SessionStart hook) so the next session started inside it picks the work up; --no-agent skips them. It also makes the build board (.himi/studio/, exactly as `himi studio --no-open` does \u2014 it never opens a browser), so every later render, test, validate, push and progress entry refreshes it; and, for a template bundled with this CLI, it makes the FIRST PICTURE itself (never for a --remote one: that is its publisher's code, and a render runs it on this machine, so next[] leaves the render to the agent after it has read the code): exactly `himi render <homeScreenId> --png --mocks --device iphone` (offline \u2014 no request; never --live; --mocks loads the app's recorded data when it has any), run as a child it kills after a time budget, writing .himi/shots/<home>.png and journaling it (by: himi) as the STARTING POINT (\"Starting point: the <template> template, before any of your changes\") so the board and the journal hold a picture when init returns. init also records the source it wrote (.himi/init-source.json: a content fingerprint, Markdown left out), and the first home PNG render after the source diverges from it is journaled once as \"First look at your app\" \u2014 reported as `firstLook: {image}` or `{skipped: <reason>}`, never a failed init; `--no-first-look` skips it (for scripts and CI that render themselves). For a bundled template (never a --remote one \u2014 the preview would build and serve its publisher's code) init also STARTS the live preview itself: `himi run --watch --content <dir> --port <p> --no-open --idle-exit 30`, detached in its own process group with its output in .himi/watch.log, never waited for (the url is chosen before it builds), recorded in .himi/watch.json, and reported as `watch: {started, pid, url, board, log}` \u2014 or `{skipped: <reason>}` for a `CI` environment, a test runner, a watch already running, or a start that failed (never a failed init). Nothing else skips it: outside CI it is started, and `watch.note` says an opt-out was ignored. The envelope LEADS with `doNow`: three lines to run now (the consent preflight, the live preview \u2014 its url and board when init started it, else `himi run --watch --content <dir> &` with the board's path \u2014 and the postcard line), and ENDS with the same lines as `doNowAgain`, so an agent that reads only the head or only the tail (`| tail`) gets them; at a terminal they are also printed as plain text on stderr, before the JSON and again after it. Its `next[]` LEADS with the steps for THIS session, in this order for every app \u2014 the offline first render and that picture's `himi progress` postcard (only when init could not make the picture), the skill's consent preflight (authorize or mock any Wix or external startup request; with none, go straight on), and only then the live preview (the running one's url, or `himi run --watch &` when init did not start it) \u2014 ahead of the next-session guidance", required: "<name> [--dir] [--template <t>] [--remote] [--base44-app-id <id>] [--base44-app-url <https://tenant>] [--no-agent] [--no-first-look] | --templates" },
250592
250748
  { name: "template", summary: "starter-template catalog + publishing. Every template is a SHOWCASE APP \u2014 a real published release you can open running before you start from it. `list` prints available templates with metadata (title/description/tags) plus each one's start prompt \u2014 pass --remote to include the serve-plane catalog so an agent can pick one; `prompt <name>` prints just that sentence for one template (the skill URL is the public door, or the plane named by --target/--serve-url); `publish` publishes an app AS a `himi init --template` (needs a himalaya.template.json; builds a previewable release + attaches the scaffold source; --source-dir overrides which tree becomes the source, --name sets the template name; bakes a launcher icon \u2014 --icon <png>, or the committed template-icons/<name>.png \u2014 and extracts accent/palette gallery meta from the scaffold's tokens.json; --visibility unlisted keeps it out of the /v1/templates catalog \u2014 templates default to public; --source-hash prints the sourceHash and iconHash a publish would be stored under, with no build or network, and exits); `trim --keep <ids>` cuts an app scaffolded from a template down to those screens (the home, and any screen the navigation pins such as a drawer body, always stays) \u2014 it deletes the other SCREENS/TEMPLATED entries whole, prunes navigation (linkableScreens, tabBar, drawer, deep links, surfaces) and drops tier5-src workers no kept screen uses, then runs validate --strict and rolls everything back if it fails (--force keeps it, --dry-run writes nothing). A kept screen that links to a removed one is refused unless --links follow (keep those too) or --links drop (remove the taps). Adopting one: `inspect` writes the adoption inventory (.himi/adopt.json: screens, workers, which screens can call Wix/network on appear \u2014 bootsOffline \u2014 placeholder and sample copy, proposed Data access rows, typed-journey stubs); `screens` lists, shows, rewrites or adds ONE dev/index.ts entry (`--upsert --from <screens.json>` writes many generated ones as plain JSON entries, replacing existing ids); `sweep` replaces sample identity/copy inside string literals; `recommend` ranks the catalog for a business description or a site's verticals; `trim --from-spec` takes the kept screens from SPEC.md's Screen catalogue", required: "list [--remote] | prompt <name> | publish [--dir <app>] [--source-dir <dir>] [--name <n>] [--icon <png>] [--visibility public|unlisted] [--target <t>] [--source-hash] | trim --keep <id,id,\u2026>|--from-spec [SPEC.md] [--content <dir>] [--links follow|drop] [--dry-run] [--force] | inspect [--content <dir>] [--dry-run] | screens [--show <id>] [--write <id> --from <file>] [--add <id> --from <file>] [--upsert --from <screens.json>] | sweep --set 'Old=>New' | --map <file> [--dry-run] | recommend [--text <t>] [--verticals a,b] [--book <dir>] [--remote]" },
250593
250749
  { name: "build", summary: "compile tier5-src/<name>/index.ts -> dist/bundles/<name>.bundle.js with esbuild (--binary = resolve published @himalaya/*); semantic TypeScript checking belongs to himi validate. Warns (never fails) when a copied tier5-src/_shared file differs from every copy this CLI's templates ship, naming the file and the `cp` that refreshes it; a `// himi:forked` line in a file skips it", required: "[--content <dir>] [--binary]" },
250594
- { name: "publish-size", summary: "local build and early draft-publish budget measurement with the source archive included. Uses the same release payload and JSON serializer as push; skips network, owner lookup, claim, publish and final evidence gates. Reports exact provisional bodyBytes, the 8388608-byte limit, remaining/overage bytes and a planning reserve (default 65536) for future metadata. A changed slug or additional metadata requires remeasurement; final push remains authoritative. Does not certify publication readiness.", required: "[--content <dir>] [--app <slug>] [--reserve-bytes <n>] [--binary|--source]" },
250750
+ { name: "publish-size", summary: "local build and early draft-publish budget measurement with the source archive included. Uses the same release payload and JSON serializer as push; skips network, owner lookup, claim, publish and final evidence gates. Reports exact provisional bodyBytes, the 8388608-byte limit, remaining/overage bytes and a planning reserve (default 65536) for future metadata, plus compressedUpload: the gzip size push would send and whether it would fit the wire and decoded limits IF the publisher credential is eligible. It reads no credential, so it never establishes that; its verdict stays on the plain limit. A changed slug or additional metadata requires remeasurement; final push remains authoritative. Does not certify publication readiness.", required: "[--content <dir>] [--app <slug>] [--reserve-bytes <n>] [--binary|--source]" },
250595
250751
  { name: "functions", summary: "inspect/invoke server functions and operate durable jobs or schedules", required: "list|describe|openapi|invoke | jobs list|get|cancel|retry|dlq | schedule describe|invoke [--app <a>] [--environment preview|production] [--release <id>]" },
250596
250752
  { name: "eject", summary: "take ownership of a shared flow module (auth|checkout|screens): copies its source into tier5-src/_ejected/ and repoints this package's imports at the copy. The ladder's escape hatch \u2014 for when the factory options cannot express what you need. AFTER EJECTING, CENTRAL FIXES NO LONGER REACH THIS APP, including future corrections to the fail-closed entitlement and confirm-the-session rules. The floor is unaffected: credentials still go only through the native auth actions and money only through the cashier rail.", required: "<auth|checkout|screens> [--content <dir>]" },
250597
250753
  { name: "validate", summary: 'lint the content package (no push): fixed-contract TypeScript checking for tier5-src workers + schema/proto + token refs + component allowlist + $service bindings + strict-enum foot-guns + capability decls + worker boot dry-run + build/compile failures + copied tier5-src/_shared files that differ from this CLI\'s (a `stale-shared` warning, never promoted by --strict; `// himi:forked` in a file skips it). Type issues are advisory warnings normally; --strict promotes them and hygiene warnings to errors. Exit 1 on any error. Off-repo, the CLI supplies its compiler and SDK declarations. A PASSING validate after a source change also refreshes the home picture: exactly `himi render <homeScreenId> --png --mocks --device iphone` (offline, never --live; with recorded data \u2014 dev/net-mocks.json or cms seed rows \u2014 the picture shows it, and without, its postcard calls it an offline preview), run as a child it kills after 30 seconds, writing .himi/shots/<home>.png \u2014 whose own postcard logic then journals "First look at your app" or, after ten minutes of postcard silence, "Still building" \u2014 reported as `homePicture: {image}` (with `postcard` when one was journaled) or `{skipped: <reason>}`, never a failed validate. Skipped for a validate with errors, a home shot already current, CI or a test runner, and code nobody asked to run: a --remote template still unchanged since init.', required: "[--content <dir>] [--strict]" },
@@ -250606,7 +250762,7 @@ var COMMANDS = [
250606
250762
  { name: "data", summary: "read-only plan or explicitly provision/seed declared KV and Wix Data resources. Preview and production are separate scopes. KV administration uses the operator data plane from --data-url/HIMI_DATA_ADMIN_URL and HIMI_DATA_ADMIN_TOKEN; draft push never calls it.", required: "plan|create|seed [--site <msid>] [--environment preview|production] [--content <dir>] [--data-url <url>] [--dry-run] [--force]" },
250607
250763
  { name: "icons", summary: "list the valid Icon.name vocabulary (an unknown name renders a fallback glyph; validate warns on unknown names) (offline)", required: "[--json]" },
250608
250764
  { name: "icon", summary: "the app's LAUNCHER icon \u2014 the home-screen / store mark, which is BINARY-floor and never over-the-air (distinct from `himi icons`, the in-screen glyph vocabulary). `status`/`check` report what this app would actually ship and validate it against both stores: exact 1024x1024, no tRNS chunk, non-interlaced, and \u2014 when the optional image toolchain is installed \u2014 no transparent regions (Apple permits an alpha channel but not transparent pixels: ITMS-90717), no pre-masked corners, no letterboxed wordmark; they also print the store-policy checklist no checker can decide. `set <file.png>` installs supplied art, `from-site` installs the logo `himi site analyze` downloaded, `from-one-app` preserves the hash-verified collected app mark (requires the image toolchain), and `generate` makes a gradient tile + glyph \u2014 these commands trim, flatten onto the app's accent, write the 1024 opaque master plus the 512 Play listing icon (Play wants 32-bit WITH alpha, so it is a separate file), and DECLARE it in himalaya.content.json, without which the release bakes no icon at all", required: "[status|check] | set <file.png> | from-one-app [--evidence-dir <dir>] | from-site [--book <dir>] | generate [--glyph <g>] [--accent <hex>] | glyphs [--content <dir>] [--json]" },
250609
- { name: "login", summary: "obtain a scoped serve-control token from Wix identity and store it in ~/.himalaya/serve-targets.json (so push/promote need no hand-pasted token). Four modes: --browser (your own Wix account, no VPN/BO), --device (an agent holding NO credential, whose browser cannot reach the owner: prints a URL and a code, the owner approves from any browser signed in to Wix, and the poll stores the same token; with --site <msid> the owner also connects that site and the agent gets its Headless client id, no Wix token), --wix (HEADLESS \u2014 the owner's held Wix token piped with --wix-token-stdin or set as WIX_TOKEN, else WIX_API_KEY, else the machine's own Wix CLI credential; the mode a CI pod or agent container can satisfy \u2014 any valid Wix token is the owner), --dpx (Wix employee, reads ~/.dpx/session/token). RFC 0026 WS3.", required: "[--browser|--device [--site <msid>] [--redirect-uri <uri>]|--wix [--wix-token-stdin]|--dpx] [--target <t>] [--issue-url <url>]" },
250765
+ { name: "login", summary: "obtain a scoped serve-control token from Wix identity and store it in ~/.himalaya/serve-targets.json (so push/promote need no hand-pasted token). Four modes: --browser (your own Wix account, no VPN/BO), --device (an agent holding NO credential, whose browser cannot reach the owner: prints a URL and a code, the owner approves from any browser signed in to Wix, and the poll stores the same token; with --site <msid> the owner also connects that site and the agent gets its Headless client id, no Wix token; --no-wait prints the URL and code and exits at once, then `--device --resume [--timeout <s>]` polls for at most that many seconds (default 50) and exits 0 signed in or 3 with code device_pending, for a caller that cannot run one command for minutes or sees output only when a command exits), --wix (HEADLESS \u2014 the owner's held Wix token piped with --wix-token-stdin or set as WIX_TOKEN, else WIX_API_KEY, else the machine's own Wix CLI credential; the mode a CI pod or agent container can satisfy \u2014 any valid Wix token is the owner), --dpx (Wix employee, reads ~/.dpx/session/token). RFC 0026 WS3.", required: "[--browser|--device [--site <msid>] [--redirect-uri <uri>] [--no-wait]|--wix [--wix-token-stdin]|--dpx] [--target <t>] [--issue-url <url>] | --device --resume [--timeout <s>] [--target <t>]" },
250610
250766
  { name: "logout", summary: "remove the stored control token for a target", required: "[--target <t>]" },
250611
250767
  { name: "connector", summary: "personal access tokens for the hosted MCP connector (Wix Native App Builder), for an AI tool that cannot sign in with OAuth (e.g. Base44's builder): `token create` opens a Wix sign-in page and prints a long-lived token once, to paste into the tool as `Authorization: Bearer <token>`; `token list` / `token revoke <id>` manage them with the `himi login --browser` token. The token can only build and publish DRAFTS.", required: "token create [--name <n>] [--days <1-90>] [--no-open] | token list | token revoke <id> [--target <t>]" },
250612
250768
  { name: "notify", summary: "Hosted --all-members requires --yes for a live send; --dry-run checks ownership/readiness and counts approved recipients without sending. `setup` optionally configures Branded/Ping from local customer key files; `status --refresh` reads live backend readiness. Setup may be deferred while building. These use serve-control and require owner plus Wix account authentication. `send`, `tokens`, `doctor`: send a REAL push notification to registered devices (RFC 0036 WS5) \u2014 APNs .p8 over HTTP/2 for iOS, FCM v1 for Android. `send` targets one device (--token / --device <registry id>) or fans out to the whole app (--all), reporting a per-device result; a token the provider says is uninstalled (APNs 410 Unregistered / FCM UNREGISTERED) is auto-disabled, while a merely wrong one (BadDeviceToken \u2014 usually a sandbox/production mismatch) is recorded and left enabled. `tokens` lists the registry. `doctor` reports which credentials resolve and which sender each platform picks. Talks to the admin-server via --admin-url/HIMALAYA_ADMIN_URL, authenticated with --admin-session/HIMALAYA_ADMIN_SESSION. `send --provider ping` is the hosted alternative: the serve plane sends to one site member (--member-email) or all approved members (--all-members) through Ping as Himalaya, with owner login instead of provider keys, and reports acceptance, never delivery. NOT `himi push`, which publishes a release.", required: "setup|status [--content <dir>] [--target <t>] [--refresh] [--yes] [--no-push-setup] | send --provider ping [--content <dir>] [--app <a>] [--site <msid>] (--member-email <email> | --all-members (--dry-run | --yes)) --title <s> [--body <s>] --link <url> [--request-id <uuid>] [--dry-run] [--json] | send|tokens|doctor [--app <a>] [--token <t> | --device <id> | --all] [--title <s>] [--body <s>] [--link <url>] [--platform ios|android] [--badge <n>] [--channel <id>] [--silent] [--dry-run] [--json]" },
@@ -251534,6 +251690,10 @@ async function templateCommand(ctx) {
251534
251690
  } else if (Buffer.byteLength(JSON.stringify(plainSource), "utf8") <= MAX_PUBLISH_BODY_BYTES && publishReleaseWireBytes(payload, publishMeta) <= MAX_PUBLISH_BODY_BYTES) {
251535
251691
  sendPayload = payload;
251536
251692
  bodyGzipped = true;
251693
+ } else if (publishReleaseWireBytes(gzipped, publishMeta) <= MAX_PUBLISH_BODY_BYTES) {
251694
+ sendPayload = gzipped;
251695
+ templateBodyBytes = gzBytes;
251696
+ bodyGzipped = true;
251537
251697
  }
251538
251698
  }
251539
251699
  if (templateBodyBytes > MAX_PUBLISH_BODY_BYTES && !bodyGzipped) {
@@ -253793,9 +253953,12 @@ async function pushCommand(ctx) {
253793
253953
  } } : {}
253794
253954
  };
253795
253955
  const publishBodyFor = (slug) => composeReleasePayload(payload, slug, appSourceB64);
253796
- const publishBodyBytesFor = (slug) => publishReleaseBodyBytes(publishBodyFor(slug), meta, draft);
253797
- const refuseOversizedBody = async (slug, bodyBytes) => {
253956
+ const publishBodySizeFor = (slug) => measurePublishBody(publishBodyFor(slug), meta, draft);
253957
+ const { admitPublishBody: admitPublishBody2, compressedPublishEligibility: compressedPublishEligibility2, compressionNote: compressionNote2, publishSizeFields: publishSizeFields2 } = await Promise.resolve().then(() => (init_publish_admission(), publish_admission_exports));
253958
+ const eligibility = compressedPublishEligibility2(pushToken);
253959
+ const refuseOversizedBody = async (slug, size, compressedUpload) => {
253798
253960
  const { publishBodyBreakdown: publishBodyBreakdown2 } = await Promise.resolve().then(() => (init_publish_size(), publish_size_exports));
253961
+ const bodyBytes = size.bodyBytes;
253799
253962
  const withoutSource = appSourceB64 ? bodyBytes - appSourceB64.length : bodyBytes;
253800
253963
  io2.error(JSON.stringify(pushFailure2("publish_body_too_large", {
253801
253964
  ok: false,
@@ -253804,15 +253967,20 @@ async function pushCommand(ctx) {
253804
253967
  error: "publish_body_too_large",
253805
253968
  bodyBytes,
253806
253969
  limit: MAX_PUBLISH_BODY_BYTES,
253970
+ // Added beside `bodyBytes`/`limit`, which keep their meaning (plain JSON against the plain
253971
+ // cap): the decoded and wire caps, the gzip size when the client would compress this body,
253972
+ // and why that compressed upload was not admitted.
253973
+ ...publishSizeFields2(size, compressedUpload),
253807
253974
  ...appSourceB64 ? { appSourceBytes: appSourceB64.length } : {},
253808
253975
  // What to cut: each part's share of the body, with its largest entries by name.
253809
253976
  breakdown: publishBodyBreakdown2(publishBodyFor(slug), bodyBytes),
253810
- hint: appSourceB64 && withoutSource <= MAX_PUBLISH_BODY_BYTES ? "push with --no-source to publish without the source archive (this release then cannot be restored with `himi pull`), or trim the app's assets and bundles" : "trim the app's assets and bundles \u2014 this release is over the limit even without the source archive, so --no-source would not help"
253977
+ hint: (appSourceB64 && withoutSource <= MAX_PUBLISH_BODY_BYTES ? "push with --no-source to publish without the source archive (this release then cannot be restored with `himi pull`), or trim the app's assets and bundles" : "trim the app's assets and bundles \u2014 this release is over the limit even without the source archive, so --no-source would not help") + `. ${compressionNote2(size, compressedUpload)}`
253811
253978
  })));
253812
253979
  return 1;
253813
253980
  };
253814
- const composedBodyBytes = publishBodyBytesFor(app2);
253815
- if (composedBodyBytes > MAX_PUBLISH_BODY_BYTES) return refuseOversizedBody(app2, composedBodyBytes);
253981
+ const composedSize = publishBodySizeFor(app2);
253982
+ const composedAdmission = admitPublishBody2(composedSize, { eligibility });
253983
+ if (!composedAdmission.ok) return refuseOversizedBody(app2, composedSize, composedAdmission.compressedUpload);
253816
253984
  let autoClaimed = false;
253817
253985
  let adoptedSlug;
253818
253986
  if (flags["no-claim"] !== true) {
@@ -253838,8 +254006,9 @@ async function pushCommand(ctx) {
253838
254006
  }
253839
254007
  }
253840
254008
  if (adoptedSlug) {
253841
- const adoptedBodyBytes = publishBodyBytesFor(app2);
253842
- if (adoptedBodyBytes > MAX_PUBLISH_BODY_BYTES) return refuseOversizedBody(app2, adoptedBodyBytes);
254009
+ const adoptedSize = publishBodySizeFor(app2);
254010
+ const adoptedAdmission = admitPublishBody2(adoptedSize, { eligibility });
254011
+ if (!adoptedAdmission.ok) return refuseOversizedBody(app2, adoptedSize, adoptedAdmission.compressedUpload);
253843
254012
  }
253844
254013
  const publishPayload = publishBodyFor(app2);
253845
254014
  let r3;
@@ -253867,6 +254036,20 @@ async function pushCommand(ctx) {
253867
254036
  }));
253868
254037
  return 1;
253869
254038
  }
254039
+ if (!r3.ok && r3.json?.code === "compressed_publish_unsupported") {
254040
+ const j2 = r3.json;
254041
+ print(pushFailure2("compressed_publish_unsupported", {
254042
+ ok: false,
254043
+ app: app2,
254044
+ pushed: false,
254045
+ error: "compressed_publish_unsupported",
254046
+ status: r3.status,
254047
+ ...typeof j2.sentBytes === "number" ? { sentBytes: j2.sentBytes } : {},
254048
+ ...typeof j2.planeCountedBytes === "number" ? { planeCountedBytes: j2.planeCountedBytes } : {},
254049
+ hint: j2.hint
254050
+ }));
254051
+ return 1;
254052
+ }
253870
254053
  if (!r3.ok) {
253871
254054
  const authHint = pushAuthHint(r3.status, pushToken, pushTarget, !!ownerIssue);
253872
254055
  const hint = authHint ?? releaseIdExistsHint(r3.status, r3.json);
@@ -256642,7 +256825,8 @@ init_cli_shared();
256642
256825
  var LOGIN_HELP = `himi login \u2014 get a scoped serve-control token and store it in
256643
256826
  ~/.himalaya/serve-targets.json, so push / promote / preview need no pasted token.
256644
256827
 
256645
- himi login [--browser | --device [--site <msid>] [--redirect-uri <uri>] | --wix [--wix-token-stdin] | --dpx] [--target <t>] [--no-open]
256828
+ himi login [--browser | --device [--site <msid>] [--redirect-uri <uri>] [--no-wait] | --wix [--wix-token-stdin] | --dpx] [--target <t>] [--no-open]
256829
+ himi login --device --resume [--timeout <s>] [--target <t>]
256646
256830
 
256647
256831
  MODES \u2014 pick by who is at the keyboard
256648
256832
  --browser YOUR OWN Wix account, in a browser. No VPN, no BO. The DEFAULT when the target
@@ -256671,6 +256855,16 @@ MODES \u2014 pick by who is at the keyboard
256671
256855
  (a public value; no Wix token), kept per site for \`himi site client list\`
256672
256856
  and \`himi site analyze --client-id\`. --redirect-uri <uri> is the redirect
256673
256857
  that client must carry (default himalaya-demo-app://oauth/callback).
256858
+ --no-wait CAN'T RUN ONE COMMAND FOR 10 MINUTES, or only see its output when it
256859
+ exits? Start with --no-wait: it prints the URL, the code and the expiry (JSON:
256860
+ pending, verificationUri, verificationUriComplete, userCode, expiresAt, resume),
256861
+ keeps the pending login in serve-targets.json (owner-only) and exits 0 at once.
256862
+ Show the owner the link and the code, then run
256863
+ himi login --device --resume [--timeout <s>]
256864
+ until it exits 0. Each resume polls for at most --timeout SECONDS (default 50,
256865
+ max 600) and keeps the plane's slow-down between calls. Exit 3 with
256866
+ code "device_pending" means not approved yet: run it again. Exit 1 with
256867
+ device_code_expired / device_access_denied / device_not_started means start over.
256674
256868
  --dpx Wix EMPLOYEE. Reads the BO session at ~/.dpx/session/token (dpx 2.x:
256675
256869
  \`dpx auth login\` then \`dpx auth token > ~/.dpx/session/token\`). Internal
256676
256870
  targets only (--target bo); VPN-gated.
@@ -256702,6 +256896,8 @@ function credentialSwapNotice(prevToken, nextToken, target) {
256702
256896
  }
256703
256897
  var DEVICE_MAX_WAIT_MS = 10 * 60 * 1e3;
256704
256898
  var DEVICE_DEFAULT_INTERVAL_SEC = 5;
256899
+ var DEVICE_RESUME_DEFAULT_TIMEOUT_SEC = 50;
256900
+ var DEVICE_PENDING_EXIT = 3;
256705
256901
  function deviceSiteOutcome(ctx, target, site) {
256706
256902
  const out2 = { ...site };
256707
256903
  if (site.msid && site.clientId) {
@@ -256724,20 +256920,21 @@ function deviceSiteOutcome(ctx, target, site) {
256724
256920
  }
256725
256921
  return out2;
256726
256922
  }
256727
- async function deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq = {}) {
256728
- const { io: io2, print } = ctx;
256729
- const clock = ctx.deps.clock ?? { now: () => Date.now(), sleep: (ms2) => new Promise((r3) => setTimeout(r3, ms2)) };
256730
- const base = ownerIssue.replace(/\/$/, "");
256731
- const post = (path2, body) => fetch(`${base}${path2}`, {
256732
- method: "POST",
256733
- headers: { "content-type": "application/json", accept: "application/json" },
256734
- body: JSON.stringify(body),
256735
- redirect: "error",
256736
- signal: AbortSignal.timeout(3e4)
256737
- });
256923
+ var deviceClock = (ctx) => ctx.deps.clock ?? { now: () => Date.now(), sleep: (ms2) => new Promise((r3) => setTimeout(r3, ms2)) };
256924
+ var devicePoster = (base) => (path2, body, timeoutMs = 3e4) => fetch(`${base}${path2}`, {
256925
+ method: "POST",
256926
+ headers: { "content-type": "application/json", accept: "application/json" },
256927
+ body: JSON.stringify(body),
256928
+ redirect: "error",
256929
+ signal: AbortSignal.timeout(timeoutMs)
256930
+ });
256931
+ var deviceResumeCommand = (target) => `himi login --device --resume --target ${target}`;
256932
+ async function startDeviceGrant(ctx, target, base, siteReq) {
256933
+ const { io: io2 } = ctx;
256934
+ const clock = deviceClock(ctx);
256738
256935
  let start;
256739
256936
  try {
256740
- start = await post("/v1/owner/device/code", {
256937
+ start = await devicePoster(base)("/v1/owner/device/code", {
256741
256938
  ...siteReq.site ? { site: siteReq.site } : {},
256742
256939
  ...siteReq.redirectUri ? { redirect_uri: siteReq.redirectUri } : {}
256743
256940
  });
@@ -256757,12 +256954,74 @@ async function deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq =
256757
256954
  return 1;
256758
256955
  }
256759
256956
  const expiresMs = Math.max(0, Number(grant.expires_in) || 0) * 1e3;
256760
- const deadline = clock.now() + Math.min(expiresMs || DEVICE_MAX_WAIT_MS, DEVICE_MAX_WAIT_MS);
256761
- let interval = Math.max(1, Number(grant.interval) || DEVICE_DEFAULT_INTERVAL_SEC);
256762
- const link3 = grant.verification_uri_complete ?? grant.verification_uri;
256763
- io2.error("To sign in, the Wix account owner opens this link on any device where they are signed in to wix.com:");
256764
- io2.error(` ${link3}`);
256765
- io2.error(`and approves code ${grant.user_code} (or opens ${grant.verification_uri} and types it). Waiting up to ${Math.round((deadline - clock.now()) / 6e4)} minutes\u2026`);
256957
+ return {
256958
+ deviceCode: grant.device_code,
256959
+ userCode: grant.user_code,
256960
+ verificationUri: grant.verification_uri,
256961
+ ...grant.verification_uri_complete ? { verificationUriComplete: grant.verification_uri_complete } : {},
256962
+ expiresAt: clock.now() + Math.min(expiresMs || DEVICE_MAX_WAIT_MS, DEVICE_MAX_WAIT_MS),
256963
+ interval: Math.max(1, Number(grant.interval) || DEVICE_DEFAULT_INTERVAL_SEC)
256964
+ };
256965
+ }
256966
+ function classifyDevicePoll(resp, body, interval, target) {
256967
+ if (resp.ok && body.token) return { kind: "ok", token: body.token };
256968
+ if (body.error === "authorization_pending") return { kind: "pending" };
256969
+ if (resp.status === 429) {
256970
+ return { kind: "backoff", interval: Math.max(interval + 5, Number(body.retryAfterSec) || Number(resp.headers.get("retry-after")) || 0) };
256971
+ }
256972
+ if (body.error === "slow_down") return { kind: "backoff", interval: Math.max(interval + 5, Number(body.interval) || 0) };
256973
+ const code2 = body.error === "access_denied" ? "device_access_denied" : body.error === "expired_token" ? "device_code_expired" : "device_login_failed";
256974
+ return {
256975
+ kind: "fail",
256976
+ final: code2 !== "device_login_failed",
256977
+ envelope: {
256978
+ ok: false,
256979
+ code: code2,
256980
+ status: resp.status,
256981
+ error: body.error ?? "device login failed",
256982
+ ...body.error === "access_denied" ? { hint: "the owner denied this sign-in" } : body.error === "expired_token" ? { hint: "the code expired before it was approved \u2014 run `himi login --device` again" } : ownerPlaneHint(resp.status, body.error, target)
256983
+ }
256984
+ };
256985
+ }
256986
+ function storeDeviceToken(ctx, target, prevControlToken, token, body) {
256987
+ const storedAt = saveControlToken(target, token);
256988
+ let exp;
256989
+ try {
256990
+ exp = JSON.parse(Buffer.from(token.split(".")[0], "base64url").toString("utf8")).exp;
256991
+ } catch {
256992
+ }
256993
+ const swap = credentialSwapNotice(prevControlToken, token, target);
256994
+ const site = body.site && typeof body.site === "object" ? deviceSiteOutcome(ctx, target, body.site) : void 0;
256995
+ ctx.print({
256996
+ ok: true,
256997
+ via: "device",
256998
+ target,
256999
+ sub: body.sub,
257000
+ exp,
257001
+ scope: body.scope,
257002
+ storedAt,
257003
+ ...site ? { site } : {},
257004
+ ...swap ? { notice: swap } : {},
257005
+ ...Array.isArray(body.scope) && body.scope.length === 0 ? { hint: "you own no apps yet \u2014 claim one with `himi apps claim <slug>`" } : {}
257006
+ });
257007
+ return 0;
257008
+ }
257009
+ function showDeviceCode(ctx, grant, tail) {
257010
+ const link3 = grant.verificationUriComplete ?? grant.verificationUri;
257011
+ ctx.io.error("To sign in, the Wix account owner opens this link on any device where they are signed in to wix.com:");
257012
+ ctx.io.error(` ${link3}`);
257013
+ ctx.io.error(`and approves code ${grant.userCode} (or opens ${grant.verificationUri} and types it). ${tail}`);
257014
+ }
257015
+ async function deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq = {}) {
257016
+ const { io: io2 } = ctx;
257017
+ const clock = deviceClock(ctx);
257018
+ const base = ownerIssue.replace(/\/$/, "");
257019
+ const post = devicePoster(base);
257020
+ const grant = await startDeviceGrant(ctx, target, base, siteReq);
257021
+ if (typeof grant === "number") return grant;
257022
+ const deadline = grant.expiresAt;
257023
+ let interval = grant.interval;
257024
+ showDeviceCode(ctx, grant, `Waiting up to ${Math.round((deadline - clock.now()) / 6e4)} minutes\u2026`);
256766
257025
  for (; ; ) {
256767
257026
  if (clock.now() + interval * 1e3 > deadline) {
256768
257027
  io2.error(JSON.stringify({ ok: false, code: "device_timed_out", error: "timed out waiting for the owner to approve", hint: "run `himi login --device` again for a new code" }));
@@ -256771,52 +257030,150 @@ async function deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq =
256771
257030
  await clock.sleep(interval * 1e3);
256772
257031
  let resp;
256773
257032
  try {
256774
- resp = await post("/v1/owner/device/token", { device_code: grant.device_code });
257033
+ resp = await post("/v1/owner/device/token", { device_code: grant.deviceCode });
256775
257034
  } catch {
256776
257035
  continue;
256777
257036
  }
256778
257037
  const body = await resp.json().catch(() => ({}));
256779
- if (resp.ok && body.token) {
256780
- const storedAt = saveControlToken(target, body.token);
256781
- let exp;
256782
- try {
256783
- exp = JSON.parse(Buffer.from(body.token.split(".")[0], "base64url").toString("utf8")).exp;
256784
- } catch {
256785
- }
256786
- const swap = credentialSwapNotice(prevControlToken, body.token, target);
256787
- const site = body.site && typeof body.site === "object" ? deviceSiteOutcome(ctx, target, body.site) : void 0;
256788
- print({
256789
- ok: true,
256790
- via: "device",
256791
- target,
256792
- sub: body.sub,
256793
- exp,
256794
- scope: body.scope,
256795
- storedAt,
256796
- ...site ? { site } : {},
256797
- ...swap ? { notice: swap } : {},
256798
- ...Array.isArray(body.scope) && body.scope.length === 0 ? { hint: "you own no apps yet \u2014 claim one with `himi apps claim <slug>`" } : {}
256799
- });
256800
- return 0;
256801
- }
256802
- if (body.error === "authorization_pending") continue;
256803
- if (resp.status === 429) {
256804
- interval = Math.max(interval + 5, Number(body.retryAfterSec) || Number(resp.headers.get("retry-after")) || 0);
256805
- continue;
256806
- }
256807
- if (body.error === "slow_down") {
256808
- interval = Math.max(interval + 5, Number(body.interval) || 0);
257038
+ const step = classifyDevicePoll(resp, body, interval, target);
257039
+ if (step.kind === "ok") return storeDeviceToken(ctx, target, prevControlToken, step.token, body);
257040
+ if (step.kind === "pending") continue;
257041
+ if (step.kind === "backoff") {
257042
+ interval = step.interval;
256809
257043
  continue;
256810
257044
  }
256811
- const code2 = body.error === "access_denied" ? "device_access_denied" : body.error === "expired_token" ? "device_code_expired" : "device_login_failed";
257045
+ io2.error(JSON.stringify(step.envelope));
257046
+ return 1;
257047
+ }
257048
+ }
257049
+ async function deviceLoginStart(ctx, target, ownerIssue, siteReq) {
257050
+ const clock = deviceClock(ctx);
257051
+ const base = ownerIssue.replace(/\/$/, "");
257052
+ const grant = await startDeviceGrant(ctx, target, base, siteReq);
257053
+ if (typeof grant === "number") return grant;
257054
+ savePendingDeviceLogin(target, {
257055
+ deviceCode: grant.deviceCode,
257056
+ userCode: grant.userCode,
257057
+ verificationUri: grant.verificationUri,
257058
+ ...grant.verificationUriComplete ? { verificationUriComplete: grant.verificationUriComplete } : {},
257059
+ ownerIssue: base,
257060
+ interval: grant.interval,
257061
+ expiresAt: grant.expiresAt,
257062
+ lastPollAt: clock.now(),
257063
+ ...siteReq.site ? { site: siteReq.site } : {},
257064
+ ...siteReq.redirectUri ? { redirectUri: siteReq.redirectUri } : {}
257065
+ });
257066
+ const resume2 = deviceResumeCommand(target);
257067
+ const expiresAt = new Date(grant.expiresAt).toISOString();
257068
+ showDeviceCode(ctx, grant, `Then run \`${resume2}\` until it succeeds (the code expires at ${expiresAt}).`);
257069
+ ctx.print({
257070
+ ok: true,
257071
+ pending: true,
257072
+ via: "device",
257073
+ target,
257074
+ verificationUri: grant.verificationUri,
257075
+ ...grant.verificationUriComplete ? { verificationUriComplete: grant.verificationUriComplete } : {},
257076
+ userCode: grant.userCode,
257077
+ expiresAt,
257078
+ interval: grant.interval,
257079
+ resume: resume2
257080
+ });
257081
+ return 0;
257082
+ }
257083
+ async function deviceLoginResume(ctx, target, prevControlToken, timeoutSec) {
257084
+ const { io: io2 } = ctx;
257085
+ const clock = deviceClock(ctx);
257086
+ const p2 = loadPendingDeviceLogin(target);
257087
+ if (!p2) {
256812
257088
  io2.error(JSON.stringify({
256813
257089
  ok: false,
256814
- code: code2,
256815
- status: resp.status,
256816
- error: body.error ?? "device login failed",
256817
- ...body.error === "access_denied" ? { hint: "the owner denied this sign-in" } : body.error === "expired_token" ? { hint: "the code expired before it was approved \u2014 run `himi login --device` again" } : ownerPlaneHint(resp.status, body.error, target)
257090
+ code: "device_not_started",
257091
+ error: `no device login is pending for target "${target}"`,
257092
+ hint: `start one with \`himi login --device --no-wait --target ${target}\` (a login that succeeded, was denied or expired is no longer pending)`
257093
+ }));
257094
+ return 1;
257095
+ }
257096
+ const issuerRefusal = ownerIssuerRefusal(p2.ownerIssue);
257097
+ if (issuerRefusal) {
257098
+ io2.error(JSON.stringify(issuerRefusal));
257099
+ return 2;
257100
+ }
257101
+ const post = devicePoster(p2.ownerIssue);
257102
+ const resume2 = deviceResumeCommand(target);
257103
+ const deadline = clock.now() + timeoutSec * 1e3;
257104
+ let interval = p2.interval;
257105
+ let lastPollAt = p2.lastPollAt;
257106
+ const keep = () => swapPendingDeviceLogin(target, p2.deviceCode, { ...p2, interval, lastPollAt });
257107
+ const clear = () => swapPendingDeviceLogin(target, p2.deviceCode, void 0);
257108
+ const superseded = () => {
257109
+ io2.error(JSON.stringify({
257110
+ ok: false,
257111
+ code: "device_superseded",
257112
+ error: "this device login was replaced (a newer `--no-wait`, another login or a logout) before it finished; nothing was stored",
257113
+ hint: `run \`${resume2}\` for the current pending login, or \`himi login --device --no-wait\` for a new one`
256818
257114
  }));
256819
257115
  return 1;
257116
+ };
257117
+ const stillPending = (wait) => {
257118
+ keep();
257119
+ const expiresAt = new Date(p2.expiresAt).toISOString();
257120
+ io2.error(`Still waiting for the owner to approve code ${p2.userCode} at ${p2.verificationUriComplete ?? p2.verificationUri}. Run \`${resume2}\` again (the code expires at ${expiresAt}).`);
257121
+ ctx.print({
257122
+ ok: false,
257123
+ pending: true,
257124
+ code: "device_pending",
257125
+ via: "device",
257126
+ target,
257127
+ error: "the owner has not approved the sign-in yet",
257128
+ userCode: p2.userCode,
257129
+ verificationUri: p2.verificationUri,
257130
+ ...p2.verificationUriComplete ? { verificationUriComplete: p2.verificationUriComplete } : {},
257131
+ expiresAt,
257132
+ interval,
257133
+ retryAfterSec: Math.ceil(wait / 1e3),
257134
+ resume: resume2
257135
+ });
257136
+ return DEVICE_PENDING_EXIT;
257137
+ };
257138
+ for (; ; ) {
257139
+ const now = clock.now();
257140
+ const wait = Math.max(0, lastPollAt + interval * 1e3 - now);
257141
+ if (now + wait >= p2.expiresAt) {
257142
+ clear();
257143
+ io2.error(JSON.stringify({
257144
+ ok: false,
257145
+ code: "device_code_expired",
257146
+ error: "the device code expired before the owner approved it",
257147
+ hint: "run `himi login --device --no-wait` again for a new code"
257148
+ }));
257149
+ return 1;
257150
+ }
257151
+ if (now + wait >= deadline) return stillPending(wait);
257152
+ await clock.sleep(wait);
257153
+ const left = deadline - clock.now();
257154
+ if (left <= 0) return stillPending(0);
257155
+ lastPollAt = clock.now();
257156
+ let resp;
257157
+ try {
257158
+ resp = await post("/v1/owner/device/token", { device_code: p2.deviceCode }, Math.min(3e4, left));
257159
+ } catch {
257160
+ continue;
257161
+ }
257162
+ const body = await resp.json().catch(() => ({}));
257163
+ const step = classifyDevicePoll(resp, body, interval, target);
257164
+ if (step.kind === "ok") {
257165
+ if (!clear()) return superseded();
257166
+ return storeDeviceToken(ctx, target, prevControlToken, step.token, body);
257167
+ }
257168
+ if (step.kind === "pending") continue;
257169
+ if (step.kind === "backoff") {
257170
+ interval = step.interval;
257171
+ continue;
257172
+ }
257173
+ if (step.final) clear();
257174
+ else keep();
257175
+ io2.error(JSON.stringify(step.envelope));
257176
+ return 1;
256820
257177
  }
256821
257178
  }
256822
257179
  async function loginCommand(ctx) {
@@ -256837,6 +257194,33 @@ async function loginCommand(ctx) {
256837
257194
  io2.error(JSON.stringify({ error: e2.message }));
256838
257195
  return 2;
256839
257196
  }
257197
+ const noWait = flags["no-wait"] === true;
257198
+ const resume2 = flags.resume === true;
257199
+ if ((noWait || resume2 || flags.timeout !== void 0) && !flags.device) {
257200
+ io2.error(JSON.stringify({ error: "--no-wait / --resume / --timeout belong to `himi login --device`" }));
257201
+ return 2;
257202
+ }
257203
+ if (noWait && resume2) {
257204
+ io2.error(JSON.stringify({ error: "--no-wait starts a device login and --resume finishes one: pass one of them" }));
257205
+ return 2;
257206
+ }
257207
+ if (flags.timeout !== void 0 && !resume2) {
257208
+ io2.error(JSON.stringify({ error: "--timeout bounds `himi login --device --resume` only; plain --device waits up to the code's lifetime" }));
257209
+ return 2;
257210
+ }
257211
+ if (resume2 && (flags.site !== void 0 || flags["redirect-uri"] !== void 0)) {
257212
+ io2.error(JSON.stringify({ error: "--site / --redirect-uri go on the start (`himi login --device --no-wait --site <msid>`); --resume polls the login that start began" }));
257213
+ return 2;
257214
+ }
257215
+ let resumeTimeoutSec = DEVICE_RESUME_DEFAULT_TIMEOUT_SEC;
257216
+ if (flags.timeout !== void 0) {
257217
+ const t2 = num3(flags.timeout);
257218
+ if (t2 === void 0 || !Number.isInteger(t2) || t2 < 1 || t2 > DEVICE_MAX_WAIT_MS / 1e3) {
257219
+ io2.error(JSON.stringify({ error: `--timeout is a whole number of SECONDS from 1 to ${DEVICE_MAX_WAIT_MS / 1e3}, got ${JSON.stringify(flags.timeout)}`, hint: `the default, ${DEVICE_RESUME_DEFAULT_TIMEOUT_SEC}, fits a 60-second command limit` }));
257220
+ return 2;
257221
+ }
257222
+ resumeTimeoutSec = t2;
257223
+ }
256840
257224
  const siteFlag = str3(flags.site);
256841
257225
  const redirectFlag = str3(flags["redirect-uri"]);
256842
257226
  if ((flags.site !== void 0 || flags["redirect-uri"] !== void 0) && !flags.device) {
@@ -256864,6 +257248,7 @@ async function loginCommand(ctx) {
256864
257248
  io2.error(JSON.stringify({ error: "--device is its own login mode: drop --wix / --browser / --dpx" }));
256865
257249
  return 2;
256866
257250
  }
257251
+ if (resume2) return deviceLoginResume(ctx, target, prevControlToken, resumeTimeoutSec);
256867
257252
  if (!ownerIssue) {
256868
257253
  io2.error(JSON.stringify({
256869
257254
  error: `no owner issuer for target "${target}"`,
@@ -256876,10 +257261,12 @@ async function loginCommand(ctx) {
256876
257261
  io2.error(JSON.stringify(issuerRefusal2));
256877
257262
  return 2;
256878
257263
  }
256879
- return deviceLogin(ctx, target, ownerIssue, prevControlToken, {
257264
+ const siteReq = {
256880
257265
  ...siteFlag ? { site: siteFlag.trim().toLowerCase() } : {},
256881
257266
  ...redirectFlag?.trim() ? { redirectUri: redirectFlag.trim() } : {}
256882
- });
257267
+ };
257268
+ if (noWait) return deviceLoginStart(ctx, target, ownerIssue, siteReq);
257269
+ return deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq);
256883
257270
  }
256884
257271
  if (flags.wix) {
256885
257272
  if (!ownerIssue) {