@wix/himalaya-cli 0.1673.0 → 0.1674.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.
@@ -207,11 +207,15 @@ export interface WixJoinProgramResponse {
207
207
  * SINGLE_PAYMENT and return the Wix Payments order as paymentPendingOptions.orderId.
208
208
  * mayPreparePayment rechecks the caller's checkout guard before creating that order.
209
209
  * beforeWrite lets a resumed caller revalidate its confirmed member after asynchronous reads.
210
+ * withdrawnParticipantId names a participation the caller freshly verified as withdrawn.
211
+ * Only its matching historical application is replaced; another current participant is resumed.
210
212
  * @scope member
211
213
  */
212
214
  export declare function joinProgram(programId: string, options?: {
213
215
  mayPreparePayment?: () => boolean;
214
216
  beforeWrite?: () => Promise<void>;
217
+ withdrawnParticipantId?: string;
218
+ resumeExistingParticipant?: boolean;
215
219
  }): Promise<WixJoinProgramResponse>;
216
220
  /** The cashier handle to settle, or "" when no payable order is available. */
217
221
  export declare function payableIdOf(participant?: WixJoinedParticipant): string;
@@ -52,18 +52,42 @@ async function joinProgram(programId, options) {
52
52
  currentReadSucceeded = true;
53
53
  } catch {
54
54
  }
55
- if (!currentReadSucceeded) {
55
+ if (!currentReadSucceeded && options?.resumeExistingParticipant === false) {
56
+ try {
57
+ const member = await wixCall("GET", "/members/v1/members/my");
58
+ if (!member?.member?.id) throw new Error("Current member unavailable");
59
+ const found = await queryJoinApplications({ memberId: member.member.id, programIds: [programId] });
60
+ const paging = found?.pagingMetadata;
61
+ if (!Array.isArray(found?.joinApplications) || found.joinApplications.length || paging?.hasNext === true || paging?.hasNext !== false && paging?.cursors?.next) {
62
+ throw new Error("Application absence is unknown");
63
+ }
64
+ } catch {
65
+ throw joinProgramError("join_application_unavailable", "current join application must be verified before creating enrollment");
66
+ }
67
+ }
68
+ const noCurrentApplication = currentReadSucceeded && !!response && typeof response === "object" && !Array.isArray(response) && response.joinApplication === void 0;
69
+ const historical = !!options?.withdrawnParticipantId && !!response?.joinApplication?.id && response.joinApplication.programId === programId && response.joinApplication.status === "APPROVED" && response.joinApplication.participantId === options.withdrawnParticipantId;
70
+ if (currentReadSucceeded && !historical && response?.joinApplication?.participantId && options?.resumeExistingParticipant === false) {
71
+ throw joinProgramError("invalid_join_application", "existing participation must be verified before resuming enrollment");
72
+ }
73
+ if (!currentReadSucceeded || noCurrentApplication || historical) {
56
74
  await options?.beforeWrite?.();
57
75
  response = await wixCall("POST", JOIN_APPLICATIONS, { joinApplication: { programId } });
58
76
  }
59
77
  let application = response?.joinApplication;
60
78
  if (!application?.id || application.programId !== programId) throw joinProgramError("invalid_join_application", "invalid join application");
79
+ if (options?.withdrawnParticipantId && application.participantId === options.withdrawnParticipantId) {
80
+ throw joinProgramError("invalid_join_application", "a withdrawn participant cannot confirm a new enrollment");
81
+ }
61
82
  if (application.status === "APPROVED" && ["PAYMENT_PENDING", "PAYMENT_FAILED", "PAYMENT_CANCELED"].includes(application.paymentStatus ?? "")) {
62
83
  if (options?.mayPreparePayment && !options.mayPreparePayment()) throw joinProgramError("payment_preparation_withdrawn", "payment preparation withdrawn");
63
84
  await options?.beforeWrite?.();
64
85
  const prepared = await wixCall("POST", `${JOIN_APPLICATIONS}/${encodeURIComponent(application.id)}/prepare-payment`, { paymentType: "SINGLE_PAYMENT" });
65
86
  if (prepared?.joinApplication?.id !== application.id || prepared.joinApplication.programId !== programId) throw joinProgramError("invalid_prepared_application", "invalid prepared application");
66
87
  application = prepared.joinApplication;
88
+ if (options?.withdrawnParticipantId && application.participantId === options.withdrawnParticipantId) {
89
+ throw joinProgramError("invalid_join_application", "a withdrawn participant cannot confirm a new enrollment");
90
+ }
67
91
  }
68
92
  const participant = { programId, memberId: application.memberId };
69
93
  if (application.status === "APPROVAL_PENDING") return { participant: { ...participant, state: "APPROVAL_PENDING" } };
package/dist/cli.mjs CHANGED
@@ -650,12 +650,15 @@ __export(config_exports, {
650
650
  BUILTIN_TARGETS: () => BUILTIN_TARGETS,
651
651
  clearControlToken: () => clearControlToken,
652
652
  defaultTargetsPath: () => defaultTargetsPath,
653
+ loadPendingDeviceLogin: () => loadPendingDeviceLogin,
653
654
  loadSiteClient: () => loadSiteClient,
654
655
  loadTargetsFile: () => loadTargetsFile,
655
656
  resolveTarget: () => resolveTarget,
656
657
  resolveTargetName: () => resolveTargetName,
657
658
  saveControlToken: () => saveControlToken,
658
- saveSiteClient: () => saveSiteClient
659
+ savePendingDeviceLogin: () => savePendingDeviceLogin,
660
+ saveSiteClient: () => saveSiteClient,
661
+ swapPendingDeviceLogin: () => swapPendingDeviceLogin
659
662
  });
660
663
  import { homedir } from "node:os";
661
664
  import { join, dirname } from "node:path";
@@ -670,7 +673,8 @@ function loadTargetsFile(path2 = defaultTargetsPath()) {
670
673
  function saveControlToken(target, token, path2 = defaultTargetsPath()) {
671
674
  const file2 = loadTargetsFile(path2);
672
675
  file2.targets = file2.targets ?? {};
673
- file2.targets[target] = { ...file2.targets[target], controlToken: token };
676
+ const { pendingDeviceLogin: _superseded, ...rest } = file2.targets[target] ?? {};
677
+ file2.targets[target] = { ...rest, controlToken: token };
674
678
  writeTargetsFilePrivate(path2, file2);
675
679
  return path2;
676
680
  }
@@ -682,6 +686,35 @@ function saveSiteClient(target, msid, client4, path2 = defaultTargetsPath()) {
682
686
  writeTargetsFilePrivate(path2, file2);
683
687
  return path2;
684
688
  }
689
+ function savePendingDeviceLogin(target, pending2, path2 = defaultTargetsPath()) {
690
+ const file2 = loadTargetsFile(path2);
691
+ const t2 = file2.targets?.[target];
692
+ if (!pending2 && !t2?.pendingDeviceLogin) return path2;
693
+ file2.targets = file2.targets ?? {};
694
+ const next = { ...t2 };
695
+ if (pending2) next.pendingDeviceLogin = pending2;
696
+ else delete next.pendingDeviceLogin;
697
+ file2.targets[target] = next;
698
+ writeTargetsFilePrivate(path2, file2);
699
+ return path2;
700
+ }
701
+ function swapPendingDeviceLogin(target, deviceCode, next, path2 = defaultTargetsPath()) {
702
+ const file2 = loadTargetsFile(path2);
703
+ const t2 = file2.targets?.[target];
704
+ if (t2?.pendingDeviceLogin?.deviceCode !== deviceCode) return false;
705
+ const copy = { ...t2 };
706
+ if (next) copy.pendingDeviceLogin = next;
707
+ else delete copy.pendingDeviceLogin;
708
+ file2.targets[target] = copy;
709
+ writeTargetsFilePrivate(path2, file2);
710
+ return true;
711
+ }
712
+ function loadPendingDeviceLogin(target, path2 = defaultTargetsPath()) {
713
+ const p2 = loadTargetsFile(path2).targets?.[target]?.pendingDeviceLogin;
714
+ if (!p2 || typeof p2 !== "object") return void 0;
715
+ 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);
716
+ return ok5 ? p2 : void 0;
717
+ }
685
718
  function loadSiteClient(msid, target, path2 = defaultTargetsPath()) {
686
719
  const targets = loadTargetsFile(path2).targets ?? {};
687
720
  const key3 = msid.toLowerCase();
@@ -707,8 +740,10 @@ function writeTargetsFilePrivate(path2, file2) {
707
740
  }
708
741
  function clearControlToken(target, path2 = defaultTargetsPath()) {
709
742
  const file2 = loadTargetsFile(path2);
710
- if (file2.targets?.[target]?.controlToken) {
711
- delete file2.targets[target].controlToken;
743
+ const t2 = file2.targets?.[target];
744
+ if (t2?.controlToken || t2?.pendingDeviceLogin) {
745
+ delete t2.controlToken;
746
+ delete t2.pendingDeviceLogin;
712
747
  writeFileSync(path2, JSON.stringify(file2, null, 2) + "\n");
713
748
  }
714
749
  return path2;
@@ -15949,6 +15984,7 @@ function webViewOriginAllowed(url, origins) {
15949
15984
  }
15950
15985
  var init_webview_origin = __esm({
15951
15986
  "../../core/ts/src/webview-origin.ts"() {
15987
+ "use strict";
15952
15988
  init_define_HHP_CATALOG();
15953
15989
  }
15954
15990
  });
@@ -31399,7 +31435,6 @@ function resolveIdiom(tokens2, ctx = {}) {
31399
31435
  var IDIOM_CONTEXTS, UNSAFE_KEYS;
31400
31436
  var init_idiom = __esm({
31401
31437
  "../../core/ts/src/idiom.ts"() {
31402
- "use strict";
31403
31438
  init_define_HHP_CATALOG();
31404
31439
  IDIOM_CONTEXTS = {
31405
31440
  ios: { native: ["ios"] },
@@ -152695,6 +152730,7 @@ var wix_owner_exports = {};
152695
152730
  __export(wix_owner_exports, {
152696
152731
  TOKEN_EXCHANGE_URL: () => TOKEN_EXCHANGE_URL,
152697
152732
  WIX_CLI_FIX: () => WIX_CLI_FIX,
152733
+ WIX_TOKEN_RE: () => WIX_TOKEN_RE,
152698
152734
  WIX_VIDEO_GATEWAY_URL: () => WIX_VIDEO_GATEWAY_URL,
152699
152735
  WixApiError: () => WixApiError,
152700
152736
  WixTokenError: () => WixTokenError,
@@ -152727,6 +152763,9 @@ function resolveSiteId(flag2) {
152727
152763
  }
152728
152764
  return id;
152729
152765
  }
152766
+ function redactWixCredentials(s2) {
152767
+ return s2.replace(WIX_CREDENTIAL_G, (m2) => `${/^(IDN2|IST|OauthNG\.JWS|SRV\.JWS)/.exec(m2)?.[1] ?? "token"}.<redacted>`);
152768
+ }
152730
152769
  async function siteToken(msid, spawnImpl = spawn3, fetchImpl = fetch) {
152731
152770
  if (!process.env.WIX_TEST_TOKEN?.trim()) {
152732
152771
  const key3 = siteApiKey();
@@ -152812,7 +152851,7 @@ function refreshableSiteToken(msid, token) {
152812
152851
  }
152813
152852
  function redactTokens(v2) {
152814
152853
  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);
152854
+ return redactWixCredentials(s2).slice(0, 300);
152816
152855
  }
152817
152856
  function exchangeRefusal(status, body, msid) {
152818
152857
  const b2 = body ?? {};
@@ -152901,7 +152940,7 @@ async function mintToken(args, label4, cacheKey, spawnImpl) {
152901
152940
  const timer = setTimeout(
152902
152941
  () => done(() => reject(new WixTokenError(
152903
152942
  "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)}`,
152943
+ `\`${label4}\` printed no Wix token within ${TOKEN_MINT_TIMEOUT_MS}ms. Is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`,
152905
152944
  mintFailedFix(label4)
152906
152945
  ))),
152907
152946
  TOKEN_MINT_TIMEOUT_MS
@@ -152919,7 +152958,7 @@ async function mintToken(args, label4, cacheKey, spawnImpl) {
152919
152958
  child.on("error", (e2) => done(() => reject(spawnFailure(label4, e2))));
152920
152959
  child.on("exit", (code2) => done(() => reject(new WixTokenError(
152921
152960
  "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)}`,
152961
+ `\`${label4}\` exited (code ${code2}) without printing a Wix token \u2014 is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`,
152923
152962
  mintFailedFix(label4)
152924
152963
  ))));
152925
152964
  });
@@ -152927,7 +152966,7 @@ async function mintToken(args, label4, cacheKey, spawnImpl) {
152927
152966
  return token;
152928
152967
  }
152929
152968
  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>");
152969
+ const cleaned = redactWixCredentials(buf).replace(/\b[A-Za-z0-9_-]{40,}\b/g, "<redacted>");
152931
152970
  const trimmed = cleaned.trim();
152932
152971
  return trimmed ? `Output (credentials redacted):
152933
152972
  ${trimmed.slice(0, 300)}` : "It printed nothing.";
@@ -153022,14 +153061,17 @@ async function mapLimit(items, limit, fn2) {
153022
153061
  }));
153023
153062
  return results;
153024
153063
  }
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;
153064
+ 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
153065
  var init_wix_owner = __esm({
153027
153066
  "src/wix-owner.ts"() {
153028
153067
  init_define_HHP_CATALOG();
153029
153068
  API_BASE = "https://www.wixapis.com";
153030
153069
  WIX_VIDEO_GATEWAY_URL = "https://manage.wix.com/_api/vod/public/graphql";
153031
153070
  tokenCache = /* @__PURE__ */ new Map();
153032
- TOKEN_RE = /OauthNG\.JWS\.[A-Za-z0-9._-]+/;
153071
+ WIX_CREDENTIAL = "(?:IDN2|IST|OauthNG\\.JWS|SRV\\.JWS)\\.[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]*)*";
153072
+ WIX_TOKEN_RE = new RegExp(WIX_CREDENTIAL);
153073
+ TOKEN_RE = WIX_TOKEN_RE;
153074
+ WIX_CREDENTIAL_G = new RegExp(WIX_CREDENTIAL, "g");
153033
153075
  TOKEN_MINT_TIMEOUT_MS = 3e4;
153034
153076
  TOKEN_EXCHANGE_URL = `${API_BASE}/oauth2/token`;
153035
153077
  EXCHANGE_REFRESH_MARGIN_MS = 6e4;
@@ -247159,7 +247201,7 @@ async function accountToken2(spawnImpl = spawn7) {
247159
247201
  };
247160
247202
  const timer = setTimeout(
247161
247203
  () => 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)}`
247204
+ `\`wix token\` printed no Wix token within ${TOKEN_MINT_TIMEOUT_MS2}ms. Is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`
247163
247205
  ))),
247164
247206
  TOKEN_MINT_TIMEOUT_MS2
247165
247207
  );
@@ -247172,7 +247214,7 @@ async function accountToken2(spawnImpl = spawn7) {
247172
247214
  child.stderr?.on("data", scan);
247173
247215
  child.on("error", (e2) => done(() => reject(new Error(mintHelp2(e2.message)))));
247174
247216
  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)}`
247217
+ `\`wix token\` exited (code ${code2}) without printing a Wix token \u2014 is the Wix CLI logged in (\`wix login\`)? ${redactForError(out2)}`
247176
247218
  ))));
247177
247219
  });
247178
247220
  cached2 = token;
@@ -247234,7 +247276,7 @@ var init_wix_account2 = __esm({
247234
247276
  init_wix_owner();
247235
247277
  API_BASE2 = "https://www.wixapis.com";
247236
247278
  API_KEYS_URL = "https://manage.wix.com/account/api-keys";
247237
- TOKEN_RE2 = /OauthNG\.JWS\.[A-Za-z0-9._-]+/;
247279
+ TOKEN_RE2 = WIX_TOKEN_RE;
247238
247280
  TOKEN_MINT_TIMEOUT_MS2 = 3e4;
247239
247281
  DEFAULT_TIMEOUT_MS6 = Number(process.env.HIMI_WIX_TIMEOUT_MS) || 12e4;
247240
247282
  }
@@ -249628,7 +249670,8 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
249628
249670
  "input-evidence",
249629
249671
  "wix-token-stdin",
249630
249672
  "no-key",
249631
- "no-frame"
249673
+ "no-frame",
249674
+ "resume"
249632
249675
  ]);
249633
249676
  var SWITCH_FLAGS = new Set([...BOOLEAN_FLAGS].filter((name) => name !== "deep"));
249634
249677
  var SWITCH_CONSEQUENCE = {
@@ -249946,7 +249989,8 @@ var USAGE = `himi \u2014 the Himalaya authoring CLI (remote dev loop)
249946
249989
  NOT in git \u2014 prefer committing to assets/ instead)
249947
249990
  himi assets rm <name> [--live] drop an asset record; the next resolve falls back to the
249948
249991
  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]
249992
+ himi login [--browser|--device [--site <msid>] [--redirect-uri <uri>] [--no-wait]|--wix [--wix-token-stdin]|--dpx] [--target <t>] [--no-open]
249993
+ himi login --device --resume [--timeout <s>] [--target <t>]
249950
249994
  get + store a scoped control token for push/promote
249951
249995
  --browser: sign in with your own Wix account in a browser
249952
249996
  on THIS machine (NO VPN, no BO) -> use with --target wix
@@ -249962,6 +250006,10 @@ var USAGE = `himi \u2014 the Himalaya authoring CLI (remote dev loop)
249962
250006
  --site <msid>: the owner also connects that site; you
249963
250007
  get its Headless client id (no Wix token), kept per
249964
250008
  site for \`himi site client list\`
250009
+ --no-wait: print the URL + code and exit at once;
250010
+ then \`himi login --device --resume\` polls for at
250011
+ most --timeout seconds (default 50): exit 0 signed
250012
+ in, exit 3 (device_pending) not approved yet
249965
250013
  --dpx: Wix employee path via an existing BO session
249966
250014
  (internal; --target bo)
249967
250015
  himi apps [list] | claim <slug> [--display-name <n>] [--account-id <id>] [--cookie <c>]
@@ -250606,7 +250654,7 @@ var COMMANDS = [
250606
250654
  { 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
250655
  { 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
250656
  { 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>]" },
250657
+ { 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
250658
  { name: "logout", summary: "remove the stored control token for a target", required: "[--target <t>]" },
250611
250659
  { 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
250660
  { 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 +251582,10 @@ async function templateCommand(ctx) {
251534
251582
  } else if (Buffer.byteLength(JSON.stringify(plainSource), "utf8") <= MAX_PUBLISH_BODY_BYTES && publishReleaseWireBytes(payload, publishMeta) <= MAX_PUBLISH_BODY_BYTES) {
251535
251583
  sendPayload = payload;
251536
251584
  bodyGzipped = true;
251585
+ } else if (publishReleaseWireBytes(gzipped, publishMeta) <= MAX_PUBLISH_BODY_BYTES) {
251586
+ sendPayload = gzipped;
251587
+ templateBodyBytes = gzBytes;
251588
+ bodyGzipped = true;
251537
251589
  }
251538
251590
  }
251539
251591
  if (templateBodyBytes > MAX_PUBLISH_BODY_BYTES && !bodyGzipped) {
@@ -256642,7 +256694,8 @@ init_cli_shared();
256642
256694
  var LOGIN_HELP = `himi login \u2014 get a scoped serve-control token and store it in
256643
256695
  ~/.himalaya/serve-targets.json, so push / promote / preview need no pasted token.
256644
256696
 
256645
- himi login [--browser | --device [--site <msid>] [--redirect-uri <uri>] | --wix [--wix-token-stdin] | --dpx] [--target <t>] [--no-open]
256697
+ himi login [--browser | --device [--site <msid>] [--redirect-uri <uri>] [--no-wait] | --wix [--wix-token-stdin] | --dpx] [--target <t>] [--no-open]
256698
+ himi login --device --resume [--timeout <s>] [--target <t>]
256646
256699
 
256647
256700
  MODES \u2014 pick by who is at the keyboard
256648
256701
  --browser YOUR OWN Wix account, in a browser. No VPN, no BO. The DEFAULT when the target
@@ -256671,6 +256724,16 @@ MODES \u2014 pick by who is at the keyboard
256671
256724
  (a public value; no Wix token), kept per site for \`himi site client list\`
256672
256725
  and \`himi site analyze --client-id\`. --redirect-uri <uri> is the redirect
256673
256726
  that client must carry (default himalaya-demo-app://oauth/callback).
256727
+ --no-wait CAN'T RUN ONE COMMAND FOR 10 MINUTES, or only see its output when it
256728
+ exits? Start with --no-wait: it prints the URL, the code and the expiry (JSON:
256729
+ pending, verificationUri, verificationUriComplete, userCode, expiresAt, resume),
256730
+ keeps the pending login in serve-targets.json (owner-only) and exits 0 at once.
256731
+ Show the owner the link and the code, then run
256732
+ himi login --device --resume [--timeout <s>]
256733
+ until it exits 0. Each resume polls for at most --timeout SECONDS (default 50,
256734
+ max 600) and keeps the plane's slow-down between calls. Exit 3 with
256735
+ code "device_pending" means not approved yet: run it again. Exit 1 with
256736
+ device_code_expired / device_access_denied / device_not_started means start over.
256674
256737
  --dpx Wix EMPLOYEE. Reads the BO session at ~/.dpx/session/token (dpx 2.x:
256675
256738
  \`dpx auth login\` then \`dpx auth token > ~/.dpx/session/token\`). Internal
256676
256739
  targets only (--target bo); VPN-gated.
@@ -256702,6 +256765,8 @@ function credentialSwapNotice(prevToken, nextToken, target) {
256702
256765
  }
256703
256766
  var DEVICE_MAX_WAIT_MS = 10 * 60 * 1e3;
256704
256767
  var DEVICE_DEFAULT_INTERVAL_SEC = 5;
256768
+ var DEVICE_RESUME_DEFAULT_TIMEOUT_SEC = 50;
256769
+ var DEVICE_PENDING_EXIT = 3;
256705
256770
  function deviceSiteOutcome(ctx, target, site) {
256706
256771
  const out2 = { ...site };
256707
256772
  if (site.msid && site.clientId) {
@@ -256724,20 +256789,21 @@ function deviceSiteOutcome(ctx, target, site) {
256724
256789
  }
256725
256790
  return out2;
256726
256791
  }
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
- });
256792
+ var deviceClock = (ctx) => ctx.deps.clock ?? { now: () => Date.now(), sleep: (ms2) => new Promise((r3) => setTimeout(r3, ms2)) };
256793
+ var devicePoster = (base) => (path2, body, timeoutMs = 3e4) => fetch(`${base}${path2}`, {
256794
+ method: "POST",
256795
+ headers: { "content-type": "application/json", accept: "application/json" },
256796
+ body: JSON.stringify(body),
256797
+ redirect: "error",
256798
+ signal: AbortSignal.timeout(timeoutMs)
256799
+ });
256800
+ var deviceResumeCommand = (target) => `himi login --device --resume --target ${target}`;
256801
+ async function startDeviceGrant(ctx, target, base, siteReq) {
256802
+ const { io: io2 } = ctx;
256803
+ const clock = deviceClock(ctx);
256738
256804
  let start;
256739
256805
  try {
256740
- start = await post("/v1/owner/device/code", {
256806
+ start = await devicePoster(base)("/v1/owner/device/code", {
256741
256807
  ...siteReq.site ? { site: siteReq.site } : {},
256742
256808
  ...siteReq.redirectUri ? { redirect_uri: siteReq.redirectUri } : {}
256743
256809
  });
@@ -256757,12 +256823,74 @@ async function deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq =
256757
256823
  return 1;
256758
256824
  }
256759
256825
  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`);
256826
+ return {
256827
+ deviceCode: grant.device_code,
256828
+ userCode: grant.user_code,
256829
+ verificationUri: grant.verification_uri,
256830
+ ...grant.verification_uri_complete ? { verificationUriComplete: grant.verification_uri_complete } : {},
256831
+ expiresAt: clock.now() + Math.min(expiresMs || DEVICE_MAX_WAIT_MS, DEVICE_MAX_WAIT_MS),
256832
+ interval: Math.max(1, Number(grant.interval) || DEVICE_DEFAULT_INTERVAL_SEC)
256833
+ };
256834
+ }
256835
+ function classifyDevicePoll(resp, body, interval, target) {
256836
+ if (resp.ok && body.token) return { kind: "ok", token: body.token };
256837
+ if (body.error === "authorization_pending") return { kind: "pending" };
256838
+ if (resp.status === 429) {
256839
+ return { kind: "backoff", interval: Math.max(interval + 5, Number(body.retryAfterSec) || Number(resp.headers.get("retry-after")) || 0) };
256840
+ }
256841
+ if (body.error === "slow_down") return { kind: "backoff", interval: Math.max(interval + 5, Number(body.interval) || 0) };
256842
+ const code2 = body.error === "access_denied" ? "device_access_denied" : body.error === "expired_token" ? "device_code_expired" : "device_login_failed";
256843
+ return {
256844
+ kind: "fail",
256845
+ final: code2 !== "device_login_failed",
256846
+ envelope: {
256847
+ ok: false,
256848
+ code: code2,
256849
+ status: resp.status,
256850
+ error: body.error ?? "device login failed",
256851
+ ...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)
256852
+ }
256853
+ };
256854
+ }
256855
+ function storeDeviceToken(ctx, target, prevControlToken, token, body) {
256856
+ const storedAt = saveControlToken(target, token);
256857
+ let exp;
256858
+ try {
256859
+ exp = JSON.parse(Buffer.from(token.split(".")[0], "base64url").toString("utf8")).exp;
256860
+ } catch {
256861
+ }
256862
+ const swap = credentialSwapNotice(prevControlToken, token, target);
256863
+ const site = body.site && typeof body.site === "object" ? deviceSiteOutcome(ctx, target, body.site) : void 0;
256864
+ ctx.print({
256865
+ ok: true,
256866
+ via: "device",
256867
+ target,
256868
+ sub: body.sub,
256869
+ exp,
256870
+ scope: body.scope,
256871
+ storedAt,
256872
+ ...site ? { site } : {},
256873
+ ...swap ? { notice: swap } : {},
256874
+ ...Array.isArray(body.scope) && body.scope.length === 0 ? { hint: "you own no apps yet \u2014 claim one with `himi apps claim <slug>`" } : {}
256875
+ });
256876
+ return 0;
256877
+ }
256878
+ function showDeviceCode(ctx, grant, tail) {
256879
+ const link3 = grant.verificationUriComplete ?? grant.verificationUri;
256880
+ ctx.io.error("To sign in, the Wix account owner opens this link on any device where they are signed in to wix.com:");
256881
+ ctx.io.error(` ${link3}`);
256882
+ ctx.io.error(`and approves code ${grant.userCode} (or opens ${grant.verificationUri} and types it). ${tail}`);
256883
+ }
256884
+ async function deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq = {}) {
256885
+ const { io: io2 } = ctx;
256886
+ const clock = deviceClock(ctx);
256887
+ const base = ownerIssue.replace(/\/$/, "");
256888
+ const post = devicePoster(base);
256889
+ const grant = await startDeviceGrant(ctx, target, base, siteReq);
256890
+ if (typeof grant === "number") return grant;
256891
+ const deadline = grant.expiresAt;
256892
+ let interval = grant.interval;
256893
+ showDeviceCode(ctx, grant, `Waiting up to ${Math.round((deadline - clock.now()) / 6e4)} minutes\u2026`);
256766
256894
  for (; ; ) {
256767
256895
  if (clock.now() + interval * 1e3 > deadline) {
256768
256896
  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,53 +256899,151 @@ async function deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq =
256771
256899
  await clock.sleep(interval * 1e3);
256772
256900
  let resp;
256773
256901
  try {
256774
- resp = await post("/v1/owner/device/token", { device_code: grant.device_code });
256902
+ resp = await post("/v1/owner/device/token", { device_code: grant.deviceCode });
256775
256903
  } catch {
256776
256904
  continue;
256777
256905
  }
256778
256906
  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);
256907
+ const step = classifyDevicePoll(resp, body, interval, target);
256908
+ if (step.kind === "ok") return storeDeviceToken(ctx, target, prevControlToken, step.token, body);
256909
+ if (step.kind === "pending") continue;
256910
+ if (step.kind === "backoff") {
256911
+ interval = step.interval;
256805
256912
  continue;
256806
256913
  }
256807
- if (body.error === "slow_down") {
256808
- interval = Math.max(interval + 5, Number(body.interval) || 0);
256809
- continue;
256810
- }
256811
- const code2 = body.error === "access_denied" ? "device_access_denied" : body.error === "expired_token" ? "device_code_expired" : "device_login_failed";
256914
+ io2.error(JSON.stringify(step.envelope));
256915
+ return 1;
256916
+ }
256917
+ }
256918
+ async function deviceLoginStart(ctx, target, ownerIssue, siteReq) {
256919
+ const clock = deviceClock(ctx);
256920
+ const base = ownerIssue.replace(/\/$/, "");
256921
+ const grant = await startDeviceGrant(ctx, target, base, siteReq);
256922
+ if (typeof grant === "number") return grant;
256923
+ savePendingDeviceLogin(target, {
256924
+ deviceCode: grant.deviceCode,
256925
+ userCode: grant.userCode,
256926
+ verificationUri: grant.verificationUri,
256927
+ ...grant.verificationUriComplete ? { verificationUriComplete: grant.verificationUriComplete } : {},
256928
+ ownerIssue: base,
256929
+ interval: grant.interval,
256930
+ expiresAt: grant.expiresAt,
256931
+ lastPollAt: clock.now(),
256932
+ ...siteReq.site ? { site: siteReq.site } : {},
256933
+ ...siteReq.redirectUri ? { redirectUri: siteReq.redirectUri } : {}
256934
+ });
256935
+ const resume2 = deviceResumeCommand(target);
256936
+ const expiresAt = new Date(grant.expiresAt).toISOString();
256937
+ showDeviceCode(ctx, grant, `Then run \`${resume2}\` until it succeeds (the code expires at ${expiresAt}).`);
256938
+ ctx.print({
256939
+ ok: true,
256940
+ pending: true,
256941
+ via: "device",
256942
+ target,
256943
+ verificationUri: grant.verificationUri,
256944
+ ...grant.verificationUriComplete ? { verificationUriComplete: grant.verificationUriComplete } : {},
256945
+ userCode: grant.userCode,
256946
+ expiresAt,
256947
+ interval: grant.interval,
256948
+ resume: resume2
256949
+ });
256950
+ return 0;
256951
+ }
256952
+ async function deviceLoginResume(ctx, target, prevControlToken, timeoutSec) {
256953
+ const { io: io2 } = ctx;
256954
+ const clock = deviceClock(ctx);
256955
+ const p2 = loadPendingDeviceLogin(target);
256956
+ if (!p2) {
256812
256957
  io2.error(JSON.stringify({
256813
256958
  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)
256959
+ code: "device_not_started",
256960
+ error: `no device login is pending for target "${target}"`,
256961
+ hint: `start one with \`himi login --device --no-wait --target ${target}\` (a login that succeeded, was denied or expired is no longer pending)`
256818
256962
  }));
256819
256963
  return 1;
256820
256964
  }
256965
+ const issuerRefusal = ownerIssuerRefusal(p2.ownerIssue);
256966
+ if (issuerRefusal) {
256967
+ io2.error(JSON.stringify(issuerRefusal));
256968
+ return 2;
256969
+ }
256970
+ const post = devicePoster(p2.ownerIssue);
256971
+ const resume2 = deviceResumeCommand(target);
256972
+ const deadline = clock.now() + timeoutSec * 1e3;
256973
+ let interval = p2.interval;
256974
+ let lastPollAt = p2.lastPollAt;
256975
+ const keep = () => swapPendingDeviceLogin(target, p2.deviceCode, { ...p2, interval, lastPollAt });
256976
+ const clear = () => swapPendingDeviceLogin(target, p2.deviceCode, void 0);
256977
+ const superseded = () => {
256978
+ io2.error(JSON.stringify({
256979
+ ok: false,
256980
+ code: "device_superseded",
256981
+ error: "this device login was replaced (a newer `--no-wait`, another login or a logout) before it finished; nothing was stored",
256982
+ hint: `run \`${resume2}\` for the current pending login, or \`himi login --device --no-wait\` for a new one`
256983
+ }));
256984
+ return 1;
256985
+ };
256986
+ const stillPending = (wait) => {
256987
+ keep();
256988
+ const expiresAt = new Date(p2.expiresAt).toISOString();
256989
+ 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}).`);
256990
+ ctx.print({
256991
+ ok: false,
256992
+ pending: true,
256993
+ code: "device_pending",
256994
+ via: "device",
256995
+ target,
256996
+ error: "the owner has not approved the sign-in yet",
256997
+ userCode: p2.userCode,
256998
+ verificationUri: p2.verificationUri,
256999
+ ...p2.verificationUriComplete ? { verificationUriComplete: p2.verificationUriComplete } : {},
257000
+ expiresAt,
257001
+ interval,
257002
+ retryAfterSec: Math.ceil(wait / 1e3),
257003
+ resume: resume2
257004
+ });
257005
+ return DEVICE_PENDING_EXIT;
257006
+ };
257007
+ for (; ; ) {
257008
+ const now = clock.now();
257009
+ const wait = Math.max(0, lastPollAt + interval * 1e3 - now);
257010
+ if (now + wait >= p2.expiresAt) {
257011
+ clear();
257012
+ io2.error(JSON.stringify({
257013
+ ok: false,
257014
+ code: "device_code_expired",
257015
+ error: "the device code expired before the owner approved it",
257016
+ hint: "run `himi login --device --no-wait` again for a new code"
257017
+ }));
257018
+ return 1;
257019
+ }
257020
+ if (now + wait >= deadline) return stillPending(wait);
257021
+ await clock.sleep(wait);
257022
+ const left = deadline - clock.now();
257023
+ if (left <= 0) return stillPending(0);
257024
+ lastPollAt = clock.now();
257025
+ let resp;
257026
+ try {
257027
+ resp = await post("/v1/owner/device/token", { device_code: p2.deviceCode }, Math.min(3e4, left));
257028
+ } catch {
257029
+ continue;
257030
+ }
257031
+ const body = await resp.json().catch(() => ({}));
257032
+ const step = classifyDevicePoll(resp, body, interval, target);
257033
+ if (step.kind === "ok") {
257034
+ if (!clear()) return superseded();
257035
+ return storeDeviceToken(ctx, target, prevControlToken, step.token, body);
257036
+ }
257037
+ if (step.kind === "pending") continue;
257038
+ if (step.kind === "backoff") {
257039
+ interval = step.interval;
257040
+ continue;
257041
+ }
257042
+ if (step.final) clear();
257043
+ else keep();
257044
+ io2.error(JSON.stringify(step.envelope));
257045
+ return 1;
257046
+ }
256821
257047
  }
256822
257048
  async function loginCommand(ctx) {
256823
257049
  const { io: io2, flags, print, targetName } = ctx;
@@ -256837,6 +257063,33 @@ async function loginCommand(ctx) {
256837
257063
  io2.error(JSON.stringify({ error: e2.message }));
256838
257064
  return 2;
256839
257065
  }
257066
+ const noWait = flags["no-wait"] === true;
257067
+ const resume2 = flags.resume === true;
257068
+ if ((noWait || resume2 || flags.timeout !== void 0) && !flags.device) {
257069
+ io2.error(JSON.stringify({ error: "--no-wait / --resume / --timeout belong to `himi login --device`" }));
257070
+ return 2;
257071
+ }
257072
+ if (noWait && resume2) {
257073
+ io2.error(JSON.stringify({ error: "--no-wait starts a device login and --resume finishes one: pass one of them" }));
257074
+ return 2;
257075
+ }
257076
+ if (flags.timeout !== void 0 && !resume2) {
257077
+ io2.error(JSON.stringify({ error: "--timeout bounds `himi login --device --resume` only; plain --device waits up to the code's lifetime" }));
257078
+ return 2;
257079
+ }
257080
+ if (resume2 && (flags.site !== void 0 || flags["redirect-uri"] !== void 0)) {
257081
+ 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" }));
257082
+ return 2;
257083
+ }
257084
+ let resumeTimeoutSec = DEVICE_RESUME_DEFAULT_TIMEOUT_SEC;
257085
+ if (flags.timeout !== void 0) {
257086
+ const t2 = num3(flags.timeout);
257087
+ if (t2 === void 0 || !Number.isInteger(t2) || t2 < 1 || t2 > DEVICE_MAX_WAIT_MS / 1e3) {
257088
+ 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` }));
257089
+ return 2;
257090
+ }
257091
+ resumeTimeoutSec = t2;
257092
+ }
256840
257093
  const siteFlag = str3(flags.site);
256841
257094
  const redirectFlag = str3(flags["redirect-uri"]);
256842
257095
  if ((flags.site !== void 0 || flags["redirect-uri"] !== void 0) && !flags.device) {
@@ -256864,6 +257117,7 @@ async function loginCommand(ctx) {
256864
257117
  io2.error(JSON.stringify({ error: "--device is its own login mode: drop --wix / --browser / --dpx" }));
256865
257118
  return 2;
256866
257119
  }
257120
+ if (resume2) return deviceLoginResume(ctx, target, prevControlToken, resumeTimeoutSec);
256867
257121
  if (!ownerIssue) {
256868
257122
  io2.error(JSON.stringify({
256869
257123
  error: `no owner issuer for target "${target}"`,
@@ -256876,10 +257130,12 @@ async function loginCommand(ctx) {
256876
257130
  io2.error(JSON.stringify(issuerRefusal2));
256877
257131
  return 2;
256878
257132
  }
256879
- return deviceLogin(ctx, target, ownerIssue, prevControlToken, {
257133
+ const siteReq = {
256880
257134
  ...siteFlag ? { site: siteFlag.trim().toLowerCase() } : {},
256881
257135
  ...redirectFlag?.trim() ? { redirectUri: redirectFlag.trim() } : {}
256882
- });
257136
+ };
257137
+ if (noWait) return deviceLoginStart(ctx, target, ownerIssue, siteReq);
257138
+ return deviceLogin(ctx, target, ownerIssue, prevControlToken, siteReq);
256883
257139
  }
256884
257140
  if (flags.wix) {
256885
257141
  if (!ownerIssue) {
@@ -38,9 +38,14 @@ This is not a whole-command migration: other CAPTCHA failures retain their legac
38
38
  | `device_access_denied` | The owner pressed Deny on the approve page. Exit 1. |
39
39
  | `device_code_expired` | The issuer reported the code expired before approval. Exit 1. |
40
40
  | `device_login_failed` | Any other poll failure; `status` and `error` carry the issuer's answer. Exit 1. |
41
+ | `device_not_started` | `himi login --device --resume` found no pending device login for the target: none was started with `--no-wait`, or it already succeeded, was denied or expired. Start one with `himi login --device --no-wait`. Exit 1. |
42
+ | `device_superseded` | `himi login --device --resume` was approved, or still pending, for a grant that is no longer the stored one: a newer `--no-wait`, another login or `himi logout` replaced it meanwhile. Nothing is stored and the newer pending login is left as it is. Run `--resume` again for the current one. Exit 1. |
43
+ | `device_pending` | Not a failure. `himi login --device --resume` used up its `--timeout` before the owner approved. Printed on **stdout** with `ok: false`, `pending: true`, `userCode`, `verificationUri`, `verificationUriComplete`, `expiresAt`, `interval`, `retryAfterSec` and `resume` (the command to run again). **Exit 3.** |
41
44
 
42
45
  A `429` while polling is not a failure: the CLI backs off by the plane's `retryAfterSec` and keeps waiting.
43
46
 
47
+ `himi login --device --no-wait` prints `{ ok: true, pending: true, via: "device", target, verificationUri, verificationUriComplete, userCode, expiresAt, interval, resume }` on stdout and exits 0 without waiting; its start failures carry the codes above. `--resume` then polls with the same backoff and codes and exits 0 with the usual success envelope, 3 with `device_pending`, or 1. With `--resume`, `device_code_expired` also means the code's lifetime passed locally, and `device_code_expired` and `device_access_denied` remove the pending login. Usage errors (`--resume` with `--no-wait`, `--site` or `--redirect-uri`; `--timeout` without `--resume` or outside 1–600 seconds) exit 2.
48
+
44
49
  ### `himi login --device --site`: `site.error` codes
45
50
 
46
51
  With `--site <msid>`, the success envelope (exit 0) carries a `site` block. On success it is
@@ -258,8 +258,16 @@ A bundle patch must repoint a screen at the new bytes (`push --only bundle:<name
258
258
  while screens still name the key they were built with — so bytes published alone land where
259
259
  nothing reads them.
260
260
 
261
- Caps are enforced at the door (413 `item_too_large`): a screen descriptor 256 KiB, a bundle 4 MiB,
262
- tokens and app-config 64 KiB each, and the whole body 8 MiB.
261
+ Caps are enforced at the door (413 `item_too_large`): a screen descriptor 256 KiB, a bundle, an
262
+ asset or the icon 4 MiB, tokens and app-config 64 KiB each, and the manifest 256 KiB as stored
263
+ (label 1 KiB, notes 16 KiB). The whole body is capped at 8 MiB (413 `payload_too_large`), except a
264
+ whole-release publish from an operator credential, which may be up to 32 MiB: `himi-serve` sends a
265
+ body over 8 MiB gzipped. A self-serve credential keeps the 8 MiB limit. A template's catalog view
266
+ (`source`, or `sourceGz` once inflated) may be up to 32 MiB only when an operator credential
267
+ publishes a reserved `himi-template-*` app; any other release that carries a catalog view keeps
268
+ 8 MiB (413 `item_too_large` for a plain view over it, `source_gz_inflated_too_large` for a
269
+ compressed one). `himi template publish` sends the view compressed, inside a gzip body, when that is the
270
+ only way the template fits.
263
271
 
264
272
  ## Consume (what a device / agent reads)
265
273
 
@@ -28969,8 +28969,8 @@
28969
28969
  {
28970
28970
  "name": "joinProgram",
28971
28971
  "kind": "function",
28972
- "jsdoc": "/**\n * Join as the signed-in member through Join Applications. Read the current\n * application first so an existing application is resumed without another create.\n * Approved paid applications prepare\n * SINGLE_PAYMENT and return the Wix Payments order as paymentPendingOptions.orderId.\n * mayPreparePayment rechecks the caller's checkout guard before creating that order.\n * beforeWrite lets a resumed caller revalidate its confirmed member after asynchronous reads.\n * @scope member\n */",
28973
- "decl": "export async function joinProgram(programId: string, options?: { mayPreparePayment?: () => boolean; beforeWrite?: () => Promise<void> }): Promise<WixJoinProgramResponse>;",
28972
+ "jsdoc": "/**\n * Join as the signed-in member through Join Applications. Read the current\n * application first so an existing application is resumed without another create.\n * Approved paid applications prepare\n * SINGLE_PAYMENT and return the Wix Payments order as paymentPendingOptions.orderId.\n * mayPreparePayment rechecks the caller's checkout guard before creating that order.\n * beforeWrite lets a resumed caller revalidate its confirmed member after asynchronous reads.\n * withdrawnParticipantId names a participation the caller freshly verified as withdrawn.\n * Only its matching historical application is replaced; another current participant is resumed.\n * @scope member\n */",
28973
+ "decl": "export async function joinProgram(programId: string, options?: { mayPreparePayment?: () => boolean; beforeWrite?: () => Promise<void>; withdrawnParticipantId?: string; resumeExistingParticipant?: boolean }): Promise<WixJoinProgramResponse>;",
28974
28974
  "scope": "member",
28975
28975
  "verificationChecked": true
28976
28976
  },
package/guides/skill.md CHANGED
@@ -185,6 +185,7 @@ and is also served at the public URL above. No repository access is required.
185
185
  - **Your platform already holds the owner's Wix session or token** (they connected their Wix account to it): that token **is** the owner. Any valid Wix token can manage that account's apps, publishing included. Pipe it in — `printf '%s' "$TOKEN" | himi login --wix --wix-token-stdin --target wix` — or set `WIX_TOKEN` and run `himi login --wix --target wix`. Never put a token on the command line (argv shows in `ps` and transcripts) or in a file you commit, and never print it.
186
186
  - **A server or CI job** with an account API key: `WIX_API_KEY` + `himi login --wix --target wix`.
187
187
  - **You hold no token at all:** run `himi login --device --target wix`. It prints a link and a short code. Show the owner both, ask them to open the link on any device where they are signed in to wix.com, check the code matches and approve, then wait: the command returns once they approve (up to 10 minutes). **If the app needs the owner's live site data, add `--site <msid>`** (and `--redirect-uri <uri>` when the app signs members in with its own redirect): the owner picks or confirms that site on the same approve page, and the result's `site` block carries the site's Headless client id (`site.clientId`, a public value — no Wix token reaches you). It is kept per site, so `himi site client list --site <msid>` answers with it afterwards. If `site` carries an `error` instead, the sign-in still worked: give the owner `site.fallbackUrl` to copy the client id from their dashboard.
188
+ - **If your environment can't run a command for about 10 minutes, or only shows a command's output once it exits,** don't run the waiting form. Run `himi login --device --no-wait --target wix` (with `--site` / `--redirect-uri` if you need them): it prints the link, the code and when the code expires, and exits at once. Show the owner the link and the code with whatever your environment uses to ask the user to act (a message, a "needs you" item), then run `himi login --device --resume --target wix` until it succeeds. Each resume waits at most 50 seconds (`--timeout <seconds>` changes that). Exit 3 with `code: "device_pending"` means the owner has not approved yet, so run it again; exit 0 means you are signed in. `device_code_expired`, `device_access_denied` or `device_not_started` mean start again with `--no-wait` and a new code.
188
189
  - **None of these:** stop and say exactly what is missing. Do not improvise another route to a himi token.
189
190
 
190
191
  This replaces only the sign-in. The approval gates above still apply to every side effect.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/himalaya-cli",
3
- "version": "0.1673.0",
3
+ "version": "0.1674.0",
4
4
  "type": "module",
5
5
  "description": "himi — the Himalaya authoring CLI. Build a Tier-5 content package on your own machine, push it to the production serve as a draft, preview it on web + Himi Player, and read worker logs back — the remote dev loop. Wraps @himalaya/serve-cli for transport.",
6
6
  "keywords": [
@@ -79,5 +79,5 @@
79
79
  "artifactId": "himalaya-cli"
80
80
  }
81
81
  },
82
- "falconPackageHash": "b49b090208e4ab091f45a960751972875090445b37a5d4203c79e429"
82
+ "falconPackageHash": "f69f803fd32a713057afe693a5a32f79ca17be5badafd6052fd1f8d0"
83
83
  }
@@ -5,6 +5,12 @@ import type { WixJoinApplication, WixParticipant } from "@himalaya/wix-online-pr
5
5
  export type Standing = "none" | "joined" | "completed" | "finished" | "suspended" | "pending" | "approved" | "invited";
6
6
 
7
7
  export function standingOf(ended: boolean, participant: WixParticipant | undefined, application: WixJoinApplication | undefined): Standing {
8
+ // A withdrawn participant is history even if its old progress says completed.
9
+ // Only its matching admitted application is history too; newer requests remain visible.
10
+ if (["LEFT", "REMOVED", "AUTO_REMOVED"].includes((participant?.enrollmentStatus ?? "").toUpperCase())) {
11
+ if (participant?.id && application?.participantId === participant.id && application.status?.toUpperCase() === "APPROVED") application = undefined;
12
+ participant = undefined;
13
+ }
8
14
  if (participant) {
9
15
  const progress = (participant.progressStatus ?? "").toUpperCase();
10
16
  const enrollment = (participant.enrollmentStatus ?? "").toUpperCase();
@@ -14,7 +14,7 @@
14
14
  // ProgressBar and two filters. The shared query controller is reused as it is.
15
15
  import { defineService as register, navigate } from "@himalaya/state";
16
16
  import {
17
- queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories,
17
+ queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories, searchMemberParticipation, participationsByProgram,
18
18
  type WixProgram, type WixProgramFull, type WixParticipant, type WixJoinApplication, type WixProgramCategory,
19
19
  } from "@himalaya/wix-online-programs";
20
20
  import { getMyMember } from "@himalaya/wix-members";
@@ -356,19 +356,47 @@ async function participationsFor(scope: Scope, firstPage: boolean, required: boo
356
356
  }
357
357
 
358
358
  /** Only where an application can exist: an unjoined PRIVATE, SECRET (invite-only) or priced program, for a member. */
359
- async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; unknown: Set<string> }> {
359
+ async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; reconciled: Participations; unknown: Set<string> }> {
360
360
  const result = new Map<string, WixJoinApplication>();
361
+ const reconciled: Participations = new Map();
361
362
  // A failed read is not "no application": those programs make no join claim (see programContent).
362
363
  const unknown = new Set<string>();
363
- if (!scope.memberId) return { map: result, unknown };
364
+ if (!scope.memberId) return { map: result, reconciled, unknown };
364
365
  const candidates = programs.filter((p) => !participations.has(p.id) && (accessType(p) === "PRIVATE" || accessType(p) === "SECRET" || !!commercePriceOf(p)));
365
- const settled = await Promise.allSettled(candidates.map((p) => getCurrentJoinApplication(p.id)));
366
+ const settled = await Promise.allSettled(candidates.map(async (p) => {
367
+ const response = await getCurrentJoinApplication(p.id);
368
+ const application = response?.joinApplication;
369
+ // A successful empty envelope is the API's documented "never applied" answer.
370
+ // An application object that is present still needs its full identity below.
371
+ if (response && typeof response === "object" && !Array.isArray(response) && application === undefined) return;
372
+ if (typeof application?.id !== "string" || !application.id || application.programId !== p.id
373
+ || typeof application.status !== "string" || !application.status
374
+ || (application.memberId && application.memberId !== scope.memberId)) {
375
+ throw new Error("Current application identity is unknown");
376
+ }
377
+ result.set(p.id, application);
378
+ if (application.status.toUpperCase() !== "APPROVED" || !application.participantId) return;
379
+ // The batch roster omits withdrawals. Only admitted applications absent from it
380
+ // need this scoped read (at most one per candidate on this page), so the shared
381
+ // standing fold can distinguish current access from a matching historical join.
382
+ try {
383
+ const response = await searchMemberParticipation(p.id, scope.memberId);
384
+ const participant = Array.isArray(response.participants) ? response.participants[0] : undefined;
385
+ if (!participant?.id || participant.memberId !== scope.memberId || participant.programId !== p.id
386
+ || (!participationsByProgram([participant]).has(p.id) && participant.id !== application.participantId)) {
387
+ throw new Error("Current participation is unknown");
388
+ }
389
+ reconciled.set(p.id, participant);
390
+ } catch {
391
+ result.delete(p.id);
392
+ unknown.add(p.id);
393
+ }
394
+ }));
366
395
  settled.forEach((outcome, i) => {
367
396
  // 404 / NOT_FOUND is the endpoint's "this member never applied"; any other rejection is unknown.
368
397
  if (outcome.status === "rejected") { if (!isNotFoundError(outcome.reason)) unknown.add(candidates[i].id); }
369
- else if (outcome.value.joinApplication?.status) result.set(candidates[i].id, outcome.value.joinApplication);
370
398
  });
371
- return { map: result, unknown };
399
+ return { map: result, reconciled, unknown };
372
400
  }
373
401
 
374
402
  async function statsFor(programs: WixProgram[]): Promise<Map<string, number>> {
@@ -453,7 +481,8 @@ async function fetchPage(filter: string, cursor: string): Promise<CollectionPage
453
481
  return { items: [], nextCursor: "", metadata };
454
482
  }
455
483
  const [counts, applications] = await Promise.all([statsFor(programs), applicationsFor(programs, participations, scope)]);
456
- const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
484
+ if (!sameScope(scope, await resolveScope())) throw memberAccessChanged();
485
+ const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id) ?? applications.reconciled.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
457
486
  // A revalidating load publishes nothing until it settles, so page 1 records the scope its later pages
458
487
  // are read under here, not only from the published snapshot.
459
488
  if (!cursor) pageScope = scope;
@@ -212,6 +212,7 @@ async function fetchProgram(id: string): Promise<WixProgram | undefined> {
212
212
  /** Whether the existing commerce flow may start (before the join) and continue (before the Wix
213
213
  * payment): a price refresh can move the program onto a route this flow must not charge. */
214
214
  interface CommerceGuards {
215
+ withdrawnParticipantId?: string;
215
216
  assertMember(): Promise<void>;
216
217
  mayStart(): boolean;
217
218
  mayContinue(): boolean;
@@ -222,7 +223,7 @@ async function enrollmentMessage(id: string, name: string, guards: CommerceGuard
222
223
  if (!guards.mayStart()) return blocked();
223
224
  let preparationWithdrawn = false;
224
225
  try {
225
- const joined = await joinProgram(id, { beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
+ const joined = await joinProgram(id, { withdrawnParticipantId: guards.withdrawnParticipantId, resumeExistingParticipant: false, beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
227
  if (!guards.mayContinue()) preparationWithdrawn = true;
227
228
  return !preparationWithdrawn;
228
229
  } });
@@ -396,7 +397,7 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
396
397
  // Authority stays in the host until the last asynchronous prerequisite completes:
397
398
  // expiry, cancellation or an intervening account switch can still revoke it.
398
399
  const permit = await continuation("consume", id);
399
- if (permit?.confirmed && permit.account) await enroll(permit.account);
400
+ if (inputId() === id && permit?.confirmed && permit.account) await enroll(permit.account, id);
400
401
  }
401
402
  }
402
403
  void resumeCommerce();
@@ -479,7 +480,7 @@ async function readStanding(id: string, seq: number): Promise<StandingRead | und
479
480
  }
480
481
  sameCancelledStanding = cancelledRow && !participant;
481
482
  feedbackKnown ||= applicationKnown || !!participant;
482
- next = standingOf(programEnded, participant, application);
483
+ next = standingOf(programEnded, participant ?? scoped[0], application);
483
484
  if (next !== "none") owner = member;
484
485
  if (failedFeedback && (applicationKnown || participant)) {
485
486
  failedFeedbackInvalidated ||= !!participant || applicationRead?.id !== failedFeedback.id
@@ -618,8 +619,9 @@ async function priceProgram(): Promise<void> {
618
619
  void svc.pricingPublish();
619
620
  }
620
621
 
621
- async function enroll(afterAuthAccount = ""): Promise<undefined> {
622
- const id = inputId();
622
+ async function enroll(afterAuthAccount = "", targetId = inputId()): Promise<undefined> {
623
+ const id = targetId;
624
+ if (id !== inputId()) return undefined;
623
625
  const reference = programReference();
624
626
  const context = standingContext;
625
627
  if (!reference || enrollmentInFlight || !standingForInput()) return undefined;
@@ -641,6 +643,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
641
643
  if (afterAuthAccount && member.email !== afterAuthAccount) return undefined;
642
644
  if (!member.email) {
643
645
  const request = await continuation("begin", id);
646
+ if (!ownsStanding(context, await memberAccess(), id)) {
647
+ if (request?.token) await continuation("cancel", id, request.token);
648
+ return undefined;
649
+ }
644
650
  if (request?.supported !== true || !request.token) {
645
651
  actionMessage = copyParam("program.signInUpdateRequired", "Update the app to sign in and continue enrollment.");
646
652
  return undefined;
@@ -658,9 +664,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
658
664
  return undefined;
659
665
  }
660
666
  await assertMemberAccess(member);
661
- if (afterAuthAccount) {
662
- // Branded's initPhase refetches participation after NOW_LOGGED_IN, before
663
- // joining. A settled participant need not have a current Join Application.
667
+ let rejoinParticipantId = "";
668
+ {
669
+ // Every join verifies current participation, including after a route change. A
670
+ // display snapshot never authorizes resuming an old admitted application.
664
671
  const memberId = (await getMyMember()).member?.id;
665
672
  if (!memberId) throw new Error("Current member unavailable");
666
673
  const response = await searchMemberParticipation(id, memberId);
@@ -670,15 +677,19 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
670
677
  const participant = response.participants[0];
671
678
  if (participant) {
672
679
  if (participant.memberId !== memberId || participant.programId !== id) throw new Error("Participation identity changed");
673
- const status = (participant.enrollmentStatus ?? "").toUpperCase();
674
- const progress = (participant.progressStatus ?? "").toUpperCase();
675
- if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
676
- actionMessage = ["COMPLETED", "FAILED"].includes(progress)
677
- ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
678
- : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
679
- return undefined;
680
- }
681
- if (!["LEFT", "REMOVED"].includes(status)) {
680
+ // Withdrawal wins over old completion/failure progress, including AUTO_REMOVED.
681
+ if (!participationsByProgram([participant]).has(id)) {
682
+ if (!participant.id) throw new Error("Withdrawn participant identity unavailable");
683
+ rejoinParticipantId = participant.id;
684
+ } else {
685
+ const status = (participant.enrollmentStatus ?? "").toUpperCase();
686
+ const progress = (participant.progressStatus ?? "").toUpperCase();
687
+ if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
688
+ actionMessage = ["COMPLETED", "FAILED"].includes(progress)
689
+ ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
690
+ : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
691
+ return undefined;
692
+ }
682
693
  actionMessage = copyParam("program.participationUnavailable", "Your current participation cannot be enrolled again.");
683
694
  return undefined;
684
695
  }
@@ -687,8 +698,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
687
698
  // joinProgram refreshes the current Join Application before creating anything. Its
688
699
  // existing-participant/private/paid and pending-payment guards remain authoritative.
689
700
  const message = await enrollmentMessage(id, content.name, {
701
+ withdrawnParticipantId: rejoinParticipantId || undefined,
690
702
  assertMember: async () => {
691
703
  await assertMemberAccess(member);
704
+ if (id !== inputId()) throw new Error("Program changed");
692
705
  if (!connectivity().online) throw new Error(offlineWriteMessage);
693
706
  },
694
707
  mayStart: () => id === inputId() && pricing.checkoutGuard(reference).allowed,
@@ -5,6 +5,12 @@ import type { WixJoinApplication, WixParticipant } from "@himalaya/wix-online-pr
5
5
  export type Standing = "none" | "joined" | "completed" | "finished" | "suspended" | "pending" | "approved" | "invited";
6
6
 
7
7
  export function standingOf(ended: boolean, participant: WixParticipant | undefined, application: WixJoinApplication | undefined): Standing {
8
+ // A withdrawn participant is history even if its old progress says completed.
9
+ // Only its matching admitted application is history too; newer requests remain visible.
10
+ if (["LEFT", "REMOVED", "AUTO_REMOVED"].includes((participant?.enrollmentStatus ?? "").toUpperCase())) {
11
+ if (participant?.id && application?.participantId === participant.id && application.status?.toUpperCase() === "APPROVED") application = undefined;
12
+ participant = undefined;
13
+ }
8
14
  if (participant) {
9
15
  const progress = (participant.progressStatus ?? "").toUpperCase();
10
16
  const enrollment = (participant.enrollmentStatus ?? "").toUpperCase();
@@ -14,7 +14,7 @@
14
14
  // ProgressBar and two filters. The shared query controller is reused as it is.
15
15
  import { defineService as register, navigate } from "@himalaya/state";
16
16
  import {
17
- queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories,
17
+ queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories, searchMemberParticipation, participationsByProgram,
18
18
  type WixProgram, type WixProgramFull, type WixParticipant, type WixJoinApplication, type WixProgramCategory,
19
19
  } from "@himalaya/wix-online-programs";
20
20
  import { getMyMember } from "@himalaya/wix-members";
@@ -356,19 +356,47 @@ async function participationsFor(scope: Scope, firstPage: boolean, required: boo
356
356
  }
357
357
 
358
358
  /** Only where an application can exist: an unjoined PRIVATE, SECRET (invite-only) or priced program, for a member. */
359
- async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; unknown: Set<string> }> {
359
+ async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; reconciled: Participations; unknown: Set<string> }> {
360
360
  const result = new Map<string, WixJoinApplication>();
361
+ const reconciled: Participations = new Map();
361
362
  // A failed read is not "no application": those programs make no join claim (see programContent).
362
363
  const unknown = new Set<string>();
363
- if (!scope.memberId) return { map: result, unknown };
364
+ if (!scope.memberId) return { map: result, reconciled, unknown };
364
365
  const candidates = programs.filter((p) => !participations.has(p.id) && (accessType(p) === "PRIVATE" || accessType(p) === "SECRET" || !!commercePriceOf(p)));
365
- const settled = await Promise.allSettled(candidates.map((p) => getCurrentJoinApplication(p.id)));
366
+ const settled = await Promise.allSettled(candidates.map(async (p) => {
367
+ const response = await getCurrentJoinApplication(p.id);
368
+ const application = response?.joinApplication;
369
+ // A successful empty envelope is the API's documented "never applied" answer.
370
+ // An application object that is present still needs its full identity below.
371
+ if (response && typeof response === "object" && !Array.isArray(response) && application === undefined) return;
372
+ if (typeof application?.id !== "string" || !application.id || application.programId !== p.id
373
+ || typeof application.status !== "string" || !application.status
374
+ || (application.memberId && application.memberId !== scope.memberId)) {
375
+ throw new Error("Current application identity is unknown");
376
+ }
377
+ result.set(p.id, application);
378
+ if (application.status.toUpperCase() !== "APPROVED" || !application.participantId) return;
379
+ // The batch roster omits withdrawals. Only admitted applications absent from it
380
+ // need this scoped read (at most one per candidate on this page), so the shared
381
+ // standing fold can distinguish current access from a matching historical join.
382
+ try {
383
+ const response = await searchMemberParticipation(p.id, scope.memberId);
384
+ const participant = Array.isArray(response.participants) ? response.participants[0] : undefined;
385
+ if (!participant?.id || participant.memberId !== scope.memberId || participant.programId !== p.id
386
+ || (!participationsByProgram([participant]).has(p.id) && participant.id !== application.participantId)) {
387
+ throw new Error("Current participation is unknown");
388
+ }
389
+ reconciled.set(p.id, participant);
390
+ } catch {
391
+ result.delete(p.id);
392
+ unknown.add(p.id);
393
+ }
394
+ }));
366
395
  settled.forEach((outcome, i) => {
367
396
  // 404 / NOT_FOUND is the endpoint's "this member never applied"; any other rejection is unknown.
368
397
  if (outcome.status === "rejected") { if (!isNotFoundError(outcome.reason)) unknown.add(candidates[i].id); }
369
- else if (outcome.value.joinApplication?.status) result.set(candidates[i].id, outcome.value.joinApplication);
370
398
  });
371
- return { map: result, unknown };
399
+ return { map: result, reconciled, unknown };
372
400
  }
373
401
 
374
402
  async function statsFor(programs: WixProgram[]): Promise<Map<string, number>> {
@@ -453,7 +481,8 @@ async function fetchPage(filter: string, cursor: string): Promise<CollectionPage
453
481
  return { items: [], nextCursor: "", metadata };
454
482
  }
455
483
  const [counts, applications] = await Promise.all([statsFor(programs), applicationsFor(programs, participations, scope)]);
456
- const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
484
+ if (!sameScope(scope, await resolveScope())) throw memberAccessChanged();
485
+ const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id) ?? applications.reconciled.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
457
486
  // A revalidating load publishes nothing until it settles, so page 1 records the scope its later pages
458
487
  // are read under here, not only from the published snapshot.
459
488
  if (!cursor) pageScope = scope;
@@ -212,6 +212,7 @@ async function fetchProgram(id: string): Promise<WixProgram | undefined> {
212
212
  /** Whether the existing commerce flow may start (before the join) and continue (before the Wix
213
213
  * payment): a price refresh can move the program onto a route this flow must not charge. */
214
214
  interface CommerceGuards {
215
+ withdrawnParticipantId?: string;
215
216
  assertMember(): Promise<void>;
216
217
  mayStart(): boolean;
217
218
  mayContinue(): boolean;
@@ -222,7 +223,7 @@ async function enrollmentMessage(id: string, name: string, guards: CommerceGuard
222
223
  if (!guards.mayStart()) return blocked();
223
224
  let preparationWithdrawn = false;
224
225
  try {
225
- const joined = await joinProgram(id, { beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
+ const joined = await joinProgram(id, { withdrawnParticipantId: guards.withdrawnParticipantId, resumeExistingParticipant: false, beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
227
  if (!guards.mayContinue()) preparationWithdrawn = true;
227
228
  return !preparationWithdrawn;
228
229
  } });
@@ -396,7 +397,7 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
396
397
  // Authority stays in the host until the last asynchronous prerequisite completes:
397
398
  // expiry, cancellation or an intervening account switch can still revoke it.
398
399
  const permit = await continuation("consume", id);
399
- if (permit?.confirmed && permit.account) await enroll(permit.account);
400
+ if (inputId() === id && permit?.confirmed && permit.account) await enroll(permit.account, id);
400
401
  }
401
402
  }
402
403
  void resumeCommerce();
@@ -479,7 +480,7 @@ async function readStanding(id: string, seq: number): Promise<StandingRead | und
479
480
  }
480
481
  sameCancelledStanding = cancelledRow && !participant;
481
482
  feedbackKnown ||= applicationKnown || !!participant;
482
- next = standingOf(programEnded, participant, application);
483
+ next = standingOf(programEnded, participant ?? scoped[0], application);
483
484
  if (next !== "none") owner = member;
484
485
  if (failedFeedback && (applicationKnown || participant)) {
485
486
  failedFeedbackInvalidated ||= !!participant || applicationRead?.id !== failedFeedback.id
@@ -618,8 +619,9 @@ async function priceProgram(): Promise<void> {
618
619
  void svc.pricingPublish();
619
620
  }
620
621
 
621
- async function enroll(afterAuthAccount = ""): Promise<undefined> {
622
- const id = inputId();
622
+ async function enroll(afterAuthAccount = "", targetId = inputId()): Promise<undefined> {
623
+ const id = targetId;
624
+ if (id !== inputId()) return undefined;
623
625
  const reference = programReference();
624
626
  const context = standingContext;
625
627
  if (!reference || enrollmentInFlight || !standingForInput()) return undefined;
@@ -641,6 +643,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
641
643
  if (afterAuthAccount && member.email !== afterAuthAccount) return undefined;
642
644
  if (!member.email) {
643
645
  const request = await continuation("begin", id);
646
+ if (!ownsStanding(context, await memberAccess(), id)) {
647
+ if (request?.token) await continuation("cancel", id, request.token);
648
+ return undefined;
649
+ }
644
650
  if (request?.supported !== true || !request.token) {
645
651
  actionMessage = copyParam("program.signInUpdateRequired", "Update the app to sign in and continue enrollment.");
646
652
  return undefined;
@@ -658,9 +664,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
658
664
  return undefined;
659
665
  }
660
666
  await assertMemberAccess(member);
661
- if (afterAuthAccount) {
662
- // Branded's initPhase refetches participation after NOW_LOGGED_IN, before
663
- // joining. A settled participant need not have a current Join Application.
667
+ let rejoinParticipantId = "";
668
+ {
669
+ // Every join verifies current participation, including after a route change. A
670
+ // display snapshot never authorizes resuming an old admitted application.
664
671
  const memberId = (await getMyMember()).member?.id;
665
672
  if (!memberId) throw new Error("Current member unavailable");
666
673
  const response = await searchMemberParticipation(id, memberId);
@@ -670,15 +677,19 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
670
677
  const participant = response.participants[0];
671
678
  if (participant) {
672
679
  if (participant.memberId !== memberId || participant.programId !== id) throw new Error("Participation identity changed");
673
- const status = (participant.enrollmentStatus ?? "").toUpperCase();
674
- const progress = (participant.progressStatus ?? "").toUpperCase();
675
- if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
676
- actionMessage = ["COMPLETED", "FAILED"].includes(progress)
677
- ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
678
- : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
679
- return undefined;
680
- }
681
- if (!["LEFT", "REMOVED"].includes(status)) {
680
+ // Withdrawal wins over old completion/failure progress, including AUTO_REMOVED.
681
+ if (!participationsByProgram([participant]).has(id)) {
682
+ if (!participant.id) throw new Error("Withdrawn participant identity unavailable");
683
+ rejoinParticipantId = participant.id;
684
+ } else {
685
+ const status = (participant.enrollmentStatus ?? "").toUpperCase();
686
+ const progress = (participant.progressStatus ?? "").toUpperCase();
687
+ if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
688
+ actionMessage = ["COMPLETED", "FAILED"].includes(progress)
689
+ ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
690
+ : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
691
+ return undefined;
692
+ }
682
693
  actionMessage = copyParam("program.participationUnavailable", "Your current participation cannot be enrolled again.");
683
694
  return undefined;
684
695
  }
@@ -687,8 +698,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
687
698
  // joinProgram refreshes the current Join Application before creating anything. Its
688
699
  // existing-participant/private/paid and pending-payment guards remain authoritative.
689
700
  const message = await enrollmentMessage(id, content.name, {
701
+ withdrawnParticipantId: rejoinParticipantId || undefined,
690
702
  assertMember: async () => {
691
703
  await assertMemberAccess(member);
704
+ if (id !== inputId()) throw new Error("Program changed");
692
705
  if (!connectivity().online) throw new Error(offlineWriteMessage);
693
706
  },
694
707
  mayStart: () => id === inputId() && pricing.checkoutGuard(reference).allowed,