@tinkerlandai/longplay-sdk 0.10.66 → 0.10.69

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -2
  3. package/dist/check-response-754GDUOJ.js +1 -0
  4. package/dist/{chunk-O5YYORDW.js → chunk-26QYDE7V.js} +1 -1
  5. package/dist/chunk-2BSDXKQS.js +1 -0
  6. package/dist/{chunk-SAPICYY3.js → chunk-2SSOV3OG.js} +1 -1
  7. package/dist/{chunk-N5HX3K5J.js → chunk-2ZMIM4MO.js} +1 -1
  8. package/dist/{chunk-AD35L6BX.js → chunk-3NV6NBQB.js} +1 -1
  9. package/dist/{chunk-MNICOIQ6.js → chunk-44ZJPQM6.js} +1 -1
  10. package/dist/{chunk-K675GO7R.js → chunk-57ZXT7AS.js} +1 -1
  11. package/dist/chunk-5MOJUGMA.js +1 -0
  12. package/dist/{chunk-RNCUAYLQ.js → chunk-5NCQOJR2.js} +1 -1
  13. package/dist/chunk-5U7LC2NL.js +1 -0
  14. package/dist/{chunk-IGE2UMXG.js → chunk-6C3ARFEL.js} +1 -1
  15. package/dist/{chunk-A22QPPNY.js → chunk-6GY2YT3U.js} +1 -1
  16. package/dist/{chunk-C5FSL4XH.js → chunk-BGCCW5QX.js} +2 -2
  17. package/dist/{chunk-JBN6ADWQ.js → chunk-CQ5EQNQA.js} +1 -1
  18. package/dist/{chunk-PQ4ISW55.js → chunk-CWBBW6QS.js} +1 -1
  19. package/dist/{chunk-PNX7Y2K3.js → chunk-DXNTXCSI.js} +1 -1
  20. package/dist/{chunk-OKPWZZZW.js → chunk-DZYMD4MJ.js} +1 -1
  21. package/dist/{chunk-FUP5JVDE.js → chunk-ECUGL7AO.js} +1 -1
  22. package/dist/{chunk-56YCOGQZ.js → chunk-EJSTRCBQ.js} +1 -1
  23. package/dist/{chunk-47FCHF3Y.js → chunk-EQ64JD4L.js} +1 -1
  24. package/dist/chunk-F5ABUGHD.js +1 -0
  25. package/dist/{chunk-EYTP23EK.js → chunk-G3YIPDT6.js} +1 -1
  26. package/dist/{chunk-M6MXJHJ5.js → chunk-GBUGEL6M.js} +1 -1
  27. package/dist/chunk-JAH62B6J.js +1 -0
  28. package/dist/{chunk-Q523TPZM.js → chunk-JW4MSBYN.js} +1 -1
  29. package/dist/{chunk-7EENIOSJ.js → chunk-KJTHMRSH.js} +1 -1
  30. package/dist/{chunk-KVLOMX2G.js → chunk-LBYMDTGD.js} +1 -1
  31. package/dist/{chunk-7OJIW75D.js → chunk-LUVTP4VU.js} +1 -1
  32. package/dist/{chunk-7D5462NE.js → chunk-MT4OQFDI.js} +1 -1
  33. package/dist/{chunk-74T76RE4.js → chunk-NEW77IDA.js} +1 -1
  34. package/dist/{chunk-G2OLUFYT.js → chunk-NNJ7W4KY.js} +1 -1
  35. package/dist/{chunk-ZWNWVMCH.js → chunk-Q4GG33R5.js} +1 -1
  36. package/dist/{chunk-5WFI36LF.js → chunk-QTXHF27F.js} +1 -1
  37. package/dist/{chunk-DCMA7W7N.js → chunk-RMR64P6V.js} +1 -1
  38. package/dist/{chunk-E3FUZSTM.js → chunk-SGOVJD5P.js} +1 -1
  39. package/dist/{chunk-HT5SLWWG.js → chunk-ST7XO45I.js} +1 -1
  40. package/dist/{chunk-YUL23NAW.js → chunk-T5SCW4IA.js} +1 -1
  41. package/dist/{chunk-XIBJF5E6.js → chunk-TFPLIX5E.js} +1 -1
  42. package/dist/{chunk-OFG3SGEX.js → chunk-TYJWRPJY.js} +1 -1
  43. package/dist/{chunk-YA5YKHDE.js → chunk-UFTKCFNI.js} +1 -1
  44. package/dist/{chunk-RHILCVPZ.js → chunk-UIR5CBCC.js} +1 -1
  45. package/dist/{chunk-TXVLJFZG.js → chunk-ULED3B5P.js} +1 -1
  46. package/dist/{chunk-QPVA644N.js → chunk-USH4WN6W.js} +1 -1
  47. package/dist/{chunk-45MWDZ42.js → chunk-VMYLTNDS.js} +1 -1
  48. package/dist/{chunk-3Q3DZEP3.js → chunk-WVTKVQLZ.js} +1 -1
  49. package/dist/{chunk-GE6RSO2C.js → chunk-YDPF2ZZW.js} +1 -1
  50. package/dist/{chunk-46USIMCJ.js → chunk-ZRU7WONE.js} +1 -1
  51. package/dist/{content-WWME7E27.js → content-66BI72XB.js} +1 -1
  52. package/dist/{funnel-host-purchase-XIGJ7P7M.js → funnel-host-purchase-YPAWZLXP.js} +1 -1
  53. package/dist/{funnel-host-recovery-paywall-POMEY6I2.js → funnel-host-recovery-paywall-KHBGMNS5.js} +1 -1
  54. package/dist/funnel-paywall-copies-A76T5V7B.js +1 -0
  55. package/dist/funnel-paywall-prerender-PNJXR4VC.js +1 -0
  56. package/dist/funnel-route-prediction-KFUCAJLL.js +1 -0
  57. package/dist/funnel-route-source-WEYKNM2C.js +1 -0
  58. package/dist/funnel-runtime-host-RWU52BJ7.js +1 -0
  59. package/dist/index.d.ts +10 -6
  60. package/dist/index.js +1 -1
  61. package/dist/merchant-bridge-contracts-RWNJHBTR.js +1 -0
  62. package/dist/native-shell.js +1 -1
  63. package/dist/openrouter.js +1 -1
  64. package/dist/operation-contracts-NNWS467N.js +1 -0
  65. package/dist/page.js +1 -1
  66. package/dist/paywall-BSY67NQL.js +1 -0
  67. package/dist/paywall-content-RAB5S6KB.js +1 -0
  68. package/dist/paywall-session-CRIGHMOQ.js +1 -0
  69. package/dist/popup.js +1 -1
  70. package/dist/react-native.js +1 -1
  71. package/dist/screen-renderer-H3FBGJZB.js +1 -0
  72. package/dist/server.js +1 -1
  73. package/dist/visual.js +1 -1
  74. package/package.json +1 -1
  75. package/dist/check-response-WOTPYNDN.js +0 -1
  76. package/dist/chunk-7NKBMAOB.js +0 -1
  77. package/dist/chunk-MUCDKWMP.js +0 -1
  78. package/dist/chunk-MUP7FNNY.js +0 -1
  79. package/dist/chunk-OT55LG4U.js +0 -1
  80. package/dist/chunk-ZLSZBGJG.js +0 -1
  81. package/dist/funnel-paywall-copies-DUZ3YX67.js +0 -1
  82. package/dist/funnel-paywall-prerender-5NU457SR.js +0 -1
  83. package/dist/funnel-route-prediction-EW3HVH46.js +0 -1
  84. package/dist/funnel-route-source-YVFAFCVG.js +0 -1
  85. package/dist/funnel-runtime-host-J2HWW5IN.js +0 -1
  86. package/dist/merchant-bridge-contracts-PNRVNTCN.js +0 -1
  87. package/dist/operation-contracts-6ORJSGYH.js +0 -1
  88. package/dist/paywall-YRB7LQUS.js +0 -1
  89. package/dist/paywall-content-QLJIOFR3.js +0 -1
  90. package/dist/paywall-session-Q6ZYXUOU.js +0 -1
  91. package/dist/screen-renderer-P6U5UBFX.js +0 -1
  92. /package/dist/{chunk-C5FSL4XH.js.LEGAL.txt → chunk-BGCCW5QX.js.LEGAL.txt} +0 -0
  93. /package/dist/{chunk-YLH3AYCK.js → chunk-S7NHVERO.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.69
4
+
5
+ - A purchase client whose device kept only a Start that never reached Longplay (no Run, purchase or command) no longer reports `blocked` with `RESULT_UNKNOWN` on every `refresh()`. The lookup forgets that Start and returns `idle` with `start`, so a host that treats `blocked` as an unfinished purchase stops asking the Customer to check an earlier purchase that does not exist. Explicit `retry()` before a refresh still resumes the retained Start with its original input
6
+
7
+ ## 0.10.68
8
+
9
+ - A Paywall mounted in another frame's document (such as a preview inside an iframe) starts again: since 0.10.66 its page-visibility listener passed this frame's AbortSignal to that document, which a frame may refuse. The listener is now removed when the Paywall ends
10
+
11
+ ## 0.10.67
12
+
13
+ - An entry whose last click started a Run that ended without presenting anything (for example a Funnel that finds this Customer ineligible and sends them to the merchant's own flow) is remembered on the device: the next pre-render of that entry paints nothing first and the click waits for its Run, instead of showing a Paywall that the Run then replaces. That record has no age limit and gives way to the Paywall the next Run presents, which becomes the kept copy again
14
+
3
15
  ## 0.10.66
4
16
 
5
17
  - A Paywall can prepare the Customer's membership read while it is visible, through the new `prepareSubscriptionChange(signal)` option, so a purchase click no longer waits for that read before quoting. The read is used for the Paywall state it was made in and is discarded when the Paywall's plans change or the page is hidden; a click during a running read waits for it. `resolveSubscriptionChange` receives the prepared read as its optional second argument
package/README.md CHANGED
@@ -335,7 +335,7 @@ When the merchant's targeting is off, omit `start` and set `allowNewPurchase: fa
335
335
 
336
336
  `merchant` permits merchant-provider quotes; `record_only` permits Stripe quotes executed by the merchant; `indiana` permits platform execution; `native` permits Apple/Google execution. The original and current policies are intersected. The Controller checks the original quote before confirmation, including Host automatic confirmation and log retry; a policy refusal sends no commercial command. Checkout URLs and external business destinations remain merchant policy. The existing Host owns Run observation and loading/ready/dismissal; one recovery observer handles Operation-only or post-termination work. `onDismiss` releases presentation ownership before merchant code runs, so immediate reopening does not wait on a merchant lock.
337
337
 
338
- The matching Customer-session recovery protocol ([Indianapolis API reference](https://github.com/tinkerlandai/Indianapolis/blob/dev/docs/sdk-api-reference.md), FRC-001/002) uses the current original Customer's access token, including a new login session, without issuing another Run Token. For an unknown Start, `refresh()` only performs `recover_start` with `intent: "lookup"`; a missing result remains blocked. Initial `start()` and explicit `retry()` use `intent: "start"` with the retained original ID and full input: Longplay accepts a Start it never saw and drives it to its first position in the same request, so the first screen arrives without a separate resume. An API that predates `start` refuses it with 400, and the SDK repeats the request with `intent: "resume"`. Known Runs use `recover_run`; exact retained commands use `settle_command`, and the same Controller continues through `run_command`. Operation-only recovery retains original references and unresolved commands, and reads `recover_purchase` for the existing SQL reselection decision. A false decision is preserved even when the Operation reports failure or cancellation; commercial completion does not mark recovery complete while an original command remains unsettled. A missing receipt never authorizes replacement. Managed recovery requires matching Indianapolis runtime and SQL functions. Offline simulated results do not establish deployment, native RLS, concurrent SQL locking or Sandbox acceptance.
338
+ The matching Customer-session recovery protocol ([Indianapolis API reference](https://github.com/tinkerlandai/Indianapolis/blob/dev/docs/sdk-api-reference.md), FRC-001/002) uses the current original Customer's access token, including a new login session, without issuing another Run Token. For an unknown Start, `refresh()` only performs `recover_start` with `intent: "lookup"`. A missing result for a Start that holds no Run, purchase or command forgets that Start: nothing of it can be recovered or charged, so the state returns to `idle` and the next `start()` begins with its own Start (a consumer still awaiting the forgotten Start's reply finds it superseded). A missing result for anything else remains blocked. Initial `start()` and explicit `retry()` use `intent: "start"` with the retained original ID and full input: Longplay accepts a Start it never saw and drives it to its first position in the same request, so the first screen arrives without a separate resume. An API that predates `start` refuses it with 400, and the SDK repeats the request with `intent: "resume"`. Known Runs use `recover_run`; exact retained commands use `settle_command`, and the same Controller continues through `run_command`. Operation-only recovery retains original references and unresolved commands, and reads `recover_purchase` for the existing SQL reselection decision. A false decision is preserved even when the Operation reports failure or cancellation; commercial completion does not mark recovery complete while an original command remains unsettled. A missing receipt never authorizes replacement. Managed recovery requires matching Indianapolis runtime and SQL functions. Offline simulated results do not establish deployment, native RLS, concurrent SQL locking or Sandbox acceptance.
339
339
 
340
340
  #### Pre-render the first Paywall
341
341
 
@@ -375,7 +375,7 @@ button.onclick = () => {
375
375
  - Or pass `configuration` (the page's `createConfigurationSync`) and name no Paywall: the SDK predicts this Customer's first screen from the Funnel's published route (see below) once the Start is final, and renders that Paywall. `prepared.prediction` holds the prediction. A first screen that is not a Paywall leaves the copy `unavailable` with reason `first_screen_popup`, `first_screen_page`, `first_screen_external_page`, `route_end_<outcome>` (for example `route_end_ineligible`) or `route_unknown_<reason>`; a route that is not published reads `route_unavailable`. Until a click takes it, a ready copy becomes `unavailable` (`route_changed`) when a configuration refresh routes the Start to another first screen.
376
376
  - Name a Paywall and pass `configuration` too, and the SDK checks the named Paywall against the same route once the Start is final: a Start the route sends to another Paywall, a screen or an end makes the copy `unavailable` with the same reasons (`route_changed` for another Paywall) and forgets the kept copy, so that Customer is never shown it first. A step only the server decides, a route the Funnel does not publish, or a configuration read that failed for now, leaves the decision to the click's Run; a paused Funnel withdraws it. The preview and the click then follow one rule: the Funnel's route for the click's Start.
377
377
  - `start` can be a promise while the merchant's own checks run: rendering starts at once and the copy becomes ready only with the Start. Pass provisional `commerce` and `locale` then. If admission changes only `commerce.intent`, the SDK rereads the same Paywall's server availability for the final intent before revealing it; an unavailable provisional purchase screen cannot decide upgrade eligibility. A provider, currency or locale change, `null` or a rejection leaves it `unavailable`.
378
- - The SDK keeps on the device the Paywall a pre-render last read for this Customer, Paywall, commerce and locale (up to 24 hours; nothing commercial). The next pre-render of that entry paints it without any request and is ready once painted, before your checks, Longplay's original-purchase lookup or a fresh read answer, so the click needs no request to show the complete Paywall. Until the Start is final a click matches it by Funnel and locale; the Run's takeover still compares the final Start exactly. The checks and the fresh read still run: until a click takes the copy they withdraw it as usual; a revealed copy is left to the click, whose own checks and Run replace it (for example with an original purchase's recovery). A fresh read updates changed plans in place; one that names another Paywall withdraws an unclaimed copy. A refused Start or an original purchase forgets the kept copy. The kept copy follows the Run: when a click's Run presents another Paywall or Version (for example a Version the Funnel pins, or another Paywall its route chooses for this Customer), that one becomes the entry's kept copy and the next opening paints it; fresh reads refresh the Version shown rather than the Paywall's current one. `prepared.local` resolves true when the copy renders from that kept Paywall: show no loading state then, and show one at once when it resolves false or `ready` resolves false.
378
+ - The SDK keeps on the device the Paywall a pre-render last read for this Customer, Paywall, commerce and locale (up to 24 hours; nothing commercial). The next pre-render of that entry paints it without any request and is ready once painted, before your checks, Longplay's original-purchase lookup or a fresh read answer, so the click needs no request to show the complete Paywall. Until the Start is final a click matches it by Funnel and locale; the Run's takeover still compares the final Start exactly. The checks and the fresh read still run: until a click takes the copy they withdraw it as usual; a revealed copy is left to the click, whose own checks and Run replace it (for example with an original purchase's recovery). A fresh read updates changed plans in place; one that names another Paywall withdraws an unclaimed copy. A refused Start or an original purchase forgets the kept copy. The kept copy follows the Run: when a click's Run presents another Paywall or Version (for example a Version the Funnel pins, or another Paywall its route chooses for this Customer), that one becomes the entry's kept copy and the next opening paints it; fresh reads refresh the Version shown rather than the Paywall's current one. When a click's Run ends without presenting anything (an ineligible or completed end before any screen or Paywall, such as a Funnel that sends this Customer to your own flow), the entry keeps that instead: the next pre-render paints nothing first, stays `preparing` with `local` false, and the click shows its loading state until its Run decides. This record has no age limit; the Paywall a later Run presents replaces it. `prepared.local` resolves true when the copy renders from that kept Paywall: show no loading state then, and show one at once when it resolves false or `ready` resolves false.
379
379
  - For `commerce.intent: "subscription_change"`, a purchase screen can be prepared when at least one plan is available; the current membership and other unavailable choices keep their server availability. With no available upgrade choice the copy remains unavailable. Ordinary purchase screens still require every plan to be available, and commercial actions always wait for the Run's own session.
380
380
 
381
381
  - `state` is `preparing`, `ready`, `unavailable` (see `reason`), `shown`, `adopted`, `released` or `closed`; `ready` resolves `true` once it can be revealed and `false` when it never will be; `onState` reports each change.
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-SGOVJD5P.js";import"./chunk-26QYDE7V.js";import"./chunk-DZYMD4MJ.js";import"./chunk-ZRU7WONE.js";import"./chunk-TFPLIX5E.js";import"./chunk-S7NHVERO.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -1 +1 @@
1
- import{a as s,b as c,c as u}from"./chunk-OKPWZZZW.js";import{j as m,m as p}from"./chunk-XIBJF5E6.js";import{b as e}from"./chunk-YLH3AYCK.js";var y=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],i=e.enum(y);function x(t){let n=i.parse(t.toUpperCase());return["JPY","KRW","VND"].includes(n)?0:2}function I(t,n,r="en",f={}){let a=i.parse(n.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...f}).format(t/10**x(a))}var l=e.enum(["stripe","apple","google","merchant"]),w=e.enum(["membership","credit_pack","lifetime"]),v=e.enum(["active","grace","suspended","inactive","revoked"]),z=e.strictObject({currency:e.string().regex(/^[A-Z]{3}$/),micros:e.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var d=e.object({provider:l,currency:i,intent:e.literal("subscription_change").optional()}).strict();var o=e.strictObject({internal_feature_id:e.uuid(),quantity:m.refine(t=>/[1-9]/.test(t)),properties:p,entityId:e.uuid().optional()}),B=e.strictObject({requirement:o,commerce:d.optional(),paywallId:e.uuid().optional()}),g=e.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),b=e.strictObject({productId:e.string().min(1),productVersionId:e.string().min(1),name:e.string().min(1).max(120),action:e.enum(["purchase","upgrade","addon","topup"]),membershipId:e.string().min(1).nullable(),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),currency:i,amountMinor:e.string().regex(/^(0|[1-9]\d{0,8})$/),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(156)}),h=e.strictObject({subject:c,authority:e.enum(["longplay","merchant"]),observedAt:e.iso.datetime({offset:!0}),sourceRevision:e.string().min(1).max(128),requirementDigest:s});function S(t,n){return u({subject:c.parse(t),requirement:o.parse(n)})}var C=e.strictObject({internal_feature_id:e.string().min(1),name:e.string().min(1).max(120),kind:e.enum(["access","metered","credit"]),quantity:m,allowed:e.boolean(),observation:h.optional(),reason:g.nullable(),preview:e.strictObject({scenario:e.enum(["feature_flag","usage_limit"]),candidates:e.array(b).max(20)}).nullable()}).superRefine((t,n)=>{(t.allowed!==(t.reason===null)||t.allowed&&t.preview!==null||new Set(t.preview?.candidates.map(r=>r.productVersionId)).size!==(t.preview?.candidates.length??0)||t.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&n.addIssue({code:"custom",message:"Invalid access recommendation"})}),T=e.strictObject({paywallId:e.uuid(),requirement:o}),U=e.strictObject({subject:c,requirement:o}),$=C.safeExtend({observation:h.extend({authority:e.literal("merchant")})});function F(t,n){let r=o.parse(t);return n.internal_feature_id===r.internal_feature_id&&n.quantity===r.quantity&&(!n.observation||n.observation.requirementDigest===S(n.observation.subject,r))}export{i as a,x as b,I as c,w as d,d as e,o as f,B as g,b as h,S as i,C as j,U as k,$ as l,F as m};
1
+ import{a as s,b as c,c as u}from"./chunk-DZYMD4MJ.js";import{j as m,m as p}from"./chunk-TFPLIX5E.js";import{b as e}from"./chunk-S7NHVERO.js";var y=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],i=e.enum(y);function x(t){let n=i.parse(t.toUpperCase());return["JPY","KRW","VND"].includes(n)?0:2}function I(t,n,r="en",f={}){let a=i.parse(n.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...f}).format(t/10**x(a))}var l=e.enum(["stripe","apple","google","merchant"]),w=e.enum(["membership","credit_pack","lifetime"]),v=e.enum(["active","grace","suspended","inactive","revoked"]),z=e.strictObject({currency:e.string().regex(/^[A-Z]{3}$/),micros:e.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var d=e.object({provider:l,currency:i,intent:e.literal("subscription_change").optional()}).strict();var o=e.strictObject({internal_feature_id:e.uuid(),quantity:m.refine(t=>/[1-9]/.test(t)),properties:p,entityId:e.uuid().optional()}),B=e.strictObject({requirement:o,commerce:d.optional(),paywallId:e.uuid().optional()}),g=e.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),b=e.strictObject({productId:e.string().min(1),productVersionId:e.string().min(1),name:e.string().min(1).max(120),action:e.enum(["purchase","upgrade","addon","topup"]),membershipId:e.string().min(1).nullable(),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),currency:i,amountMinor:e.string().regex(/^(0|[1-9]\d{0,8})$/),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(156)}),h=e.strictObject({subject:c,authority:e.enum(["longplay","merchant"]),observedAt:e.iso.datetime({offset:!0}),sourceRevision:e.string().min(1).max(128),requirementDigest:s});function S(t,n){return u({subject:c.parse(t),requirement:o.parse(n)})}var C=e.strictObject({internal_feature_id:e.string().min(1),name:e.string().min(1).max(120),kind:e.enum(["access","metered","credit"]),quantity:m,allowed:e.boolean(),observation:h.optional(),reason:g.nullable(),preview:e.strictObject({scenario:e.enum(["feature_flag","usage_limit"]),candidates:e.array(b).max(20)}).nullable()}).superRefine((t,n)=>{(t.allowed!==(t.reason===null)||t.allowed&&t.preview!==null||new Set(t.preview?.candidates.map(r=>r.productVersionId)).size!==(t.preview?.candidates.length??0)||t.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&n.addIssue({code:"custom",message:"Invalid access recommendation"})}),T=e.strictObject({paywallId:e.uuid(),requirement:o}),U=e.strictObject({subject:c,requirement:o}),$=C.safeExtend({observation:h.extend({authority:e.literal("merchant")})});function F(t,n){let r=o.parse(t);return n.internal_feature_id===r.internal_feature_id&&n.quantity===r.quantity&&(!n.observation||n.observation.requirementDigest===S(n.observation.subject,r))}export{i as a,x as b,I as c,w as d,d as e,o as f,B as g,b as h,S as i,C as j,U as k,$ as l,F as m};
@@ -0,0 +1 @@
1
+ import{o as n,r as t}from"./chunk-UIR5CBCC.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +1 @@
1
- import{b as e}from"./chunk-YLH3AYCK.js";var r=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),m=e.enum(["unknown","denied","provisional","granted"]),d=e.enum(["ios","android"]),i=e.strictObject({installationId:e.uuid(),publicKey:e.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:e.iso.datetime({offset:!0}),signature:e.string().regex(/^[A-Za-z0-9_-]{86}$/)}),a=e.string().regex(/^[a-f0-9]{64}$/),p=i.extend({sequence:r,platform:d,credentialDigest:a}),f=i.extend({credentialDigest:a}),x=i.extend({sequence:r,platform:d}),l=i.extend({sequence:r,credentialDigest:a,connectionId:e.uuid().nullable(),kind:e.enum(["fcm_token","apns_token"]).nullable(),token:e.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:m}),g=l,b=l.extend({challenge:e.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),S=e.strictObject({requested:e.literal(!0),expiresAt:e.iso.datetime({offset:!0})}),A=e.strictObject({installationId:e.uuid(),bound:e.boolean(),identitySeq:r,bindingGeneration:r,addressSeq:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:e.uuid().nullable(),addressStatus:e.enum(["active","invalid"]).nullable(),permission:m}),I=e.strictObject({channel:e.enum(["email","sms","voice","push"]),state:e.enum(["unknown","allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}),P=e.strictObject({state:e.enum(["allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function y(s,c,t){let n=["indiana_push_v1",s,c.projectId,c.environment,t.installationId,t.publicKey,t.issuedAt];s==="bind"?n.push(t.sequence,t.platform,t.credentialDigest):s==="detach"?n.push(t.sequence,t.platform):s==="read"?n.push(t.credentialDigest):n.push(t.sequence,t.credentialDigest,t.connectionId,t.kind,t.token,t.permission),s==="recovery_confirm"&&n.push(t.challenge);let u=JSON.stringify(n);if([...u].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(u,o=>o.charCodeAt(0))}export{p as a,f as b,x as c,l as d,g as e,b as f,S as g,A as h,I as i,y as j};
1
+ import{b as e}from"./chunk-S7NHVERO.js";var r=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),m=e.enum(["unknown","denied","provisional","granted"]),d=e.enum(["ios","android"]),i=e.strictObject({installationId:e.uuid(),publicKey:e.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:e.iso.datetime({offset:!0}),signature:e.string().regex(/^[A-Za-z0-9_-]{86}$/)}),a=e.string().regex(/^[a-f0-9]{64}$/),p=i.extend({sequence:r,platform:d,credentialDigest:a}),f=i.extend({credentialDigest:a}),x=i.extend({sequence:r,platform:d}),l=i.extend({sequence:r,credentialDigest:a,connectionId:e.uuid().nullable(),kind:e.enum(["fcm_token","apns_token"]).nullable(),token:e.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:m}),g=l,b=l.extend({challenge:e.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),S=e.strictObject({requested:e.literal(!0),expiresAt:e.iso.datetime({offset:!0})}),A=e.strictObject({installationId:e.uuid(),bound:e.boolean(),identitySeq:r,bindingGeneration:r,addressSeq:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:e.uuid().nullable(),addressStatus:e.enum(["active","invalid"]).nullable(),permission:m}),I=e.strictObject({channel:e.enum(["email","sms","voice","push"]),state:e.enum(["unknown","allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}),P=e.strictObject({state:e.enum(["allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function y(s,c,t){let n=["indiana_push_v1",s,c.projectId,c.environment,t.installationId,t.publicKey,t.issuedAt];s==="bind"?n.push(t.sequence,t.platform,t.credentialDigest):s==="detach"?n.push(t.sequence,t.platform):s==="read"?n.push(t.credentialDigest):n.push(t.sequence,t.credentialDigest,t.connectionId,t.kind,t.token,t.permission),s==="recovery_confirm"&&n.push(t.challenge);let u=JSON.stringify(n);if([...u].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(u,o=>o.charCodeAt(0))}export{p as a,f as b,x as c,l as d,g as e,b as f,S as g,A as h,I as i,y as j};
@@ -1 +1 @@
1
- import{d as t}from"./chunk-DCMA7W7N.js";async function u(e,n){try{let{route:r}=await e.funnelRoute(n.funnelId),a=t(r,{customerId:n.customerId,parameters:n.parameters??{}});return{funnelId:n.funnelId,...a}}catch(r){return{funnelId:n.funnelId,type:"unavailable",reason:r?.code?.toLowerCase()??"error",path:[]}}}function l(e){switch(e.type){case"paywall":return null;case"screen":return`first_screen_${e.surface}`;case"external_page":return"first_screen_external_page";case"end":return`route_end_${e.outcome}`;case"unknown":return`route_unknown_${e.reason}`;case"unavailable":return e.reason.startsWith("route_")?e.reason:`route_${e.reason}`}}async function s(e,n){if(n.type!=="paywall")return null;try{let{document:r}=await e.paywall(n.paywallId,n.paywallVersionId);return{presentation:r.presentation,screen:r.screen,buttons:r.buttons}}catch{return null}}export{u as a,l as b,s as c};
1
+ import{d as t}from"./chunk-RMR64P6V.js";async function u(e,n){try{let{route:r}=await e.funnelRoute(n.funnelId),a=t(r,{customerId:n.customerId,parameters:n.parameters??{}});return{funnelId:n.funnelId,...a}}catch(r){return{funnelId:n.funnelId,type:"unavailable",reason:r?.code?.toLowerCase()??"error",path:[]}}}function l(e){switch(e.type){case"paywall":return null;case"screen":return`first_screen_${e.surface}`;case"external_page":return"first_screen_external_page";case"end":return`route_end_${e.outcome}`;case"unknown":return`route_unknown_${e.reason}`;case"unavailable":return e.reason.startsWith("route_")?e.reason:`route_${e.reason}`}}async function s(e,n){if(n.type!=="paywall")return null;try{let{document:r}=await e.paywall(n.paywallId,n.paywallVersionId);return{presentation:r.presentation,screen:r.screen,buttons:r.buttons}}catch{return null}}export{u as a,l as b,s as c};
@@ -1 +1 @@
1
- import{a as He,i as Ze,y as We}from"./chunk-3Q3DZEP3.js";import{w as Pe}from"./chunk-5WFI36LF.js";import{a as K,b as fe,c as ge,d as ye,e as T,f as $e,g as Le,j as be,m as Q}from"./chunk-MNICOIQ6.js";import{a as q}from"./chunk-VILB5M4X.js";import{a as Fe}from"./chunk-7EENIOSJ.js";import{m as Je,n as J,o as B}from"./chunk-Q523TPZM.js";import{C as me,f as Ve,g as Ue,h as Be,p as pe,v as L,w as H,x as Z,y as de,z as Te}from"./chunk-56YCOGQZ.js";import{b as Me,d as S,e as U,f as qe,g as Ge,h as W}from"./chunk-7OJIW75D.js";import{h as V}from"./chunk-XIBJF5E6.js";import{b as e}from"./chunk-YLH3AYCK.js";var E=e.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(t=>t.split(".").every(o=>!["__proto__","constructor","prototype"].includes(o)),"Reserved value path"),C=e.discriminatedUnion("source",[e.strictObject({source:e.literal("literal"),value:S}),e.strictObject({source:e.literal("variable"),key:e.string().min(1).max(255),path:E.optional()})]);function Qe(t,o){if(!o)return t;for(let n of E.parse(o).split(".")){if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=t.length)return;t=t[Number(n)];continue}if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=Reflect.get(t,n)}return t}function _t(t,o){if(t.source==="literal")return structuredClone(t.value);let n=Le(o.declarations,o);if(!Object.hasOwn(n,t.key))throw new Error("Capability input is missing");return structuredClone(S.parse(Qe(n[t.key],t.path)))}function he(t,o){let n=[...o].sort((i,a)=>a.length-i.length).find(i=>t===i||t.startsWith(i+"."));if(!n)return null;let s=t===n?void 0:t.slice(n.length+1);return s&&!E.safeParse(s).success?null:{key:n,path:s}}function xe(t){let o=Object.values(t.strings.locales).flatMap(n=>Object.values(n));return L(t,n=>{n.type==="custom_html"&&o.push(...Object.values(n.html))}),[...new Set(o.flatMap(Be))]}function Xe(t){return xe(t).filter(o=>o.startsWith("variables.")).map(o=>o.slice(10))}function F(t){let o=JSON.stringify(t);if(o===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(o).length,s=!1;for(let i=0;i<o.length;i++){let a=o.charAt(i);if(s)a==="\\"?i++:a==='"'&&(s=!1);else if(a==='"')s=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let f=i;for(;i+1<o.length&&/[0-9.eE+-]/.test(o.charAt(i+1));)i++;let m=o.slice(f,i+1);if(!/[eE]/.test(m))continue;let[x="",_]=m.split(/[eE]/),p=x.replace(/^-/,""),v=p.replace(".","").length,N=(p.includes(".")?p.indexOf("."):v)+Number(_),d=N<=0?2-N+v:N>=v?N:v+1;n+=d+(x.startsWith("-")?1:0)-m.length}}return n}var Kt=e.string().regex(/^[a-f0-9]{64}$/),Et=Ve.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Ye=e.strictObject({couponDigests:e.record(e.uuid(),Kt),variables:e.record(pe,e.record(e.uuid(),e.partialRecord(e.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),e.string()))),locales:e.record(pe,Ue.extend({nodes:e.record(e.string(),e.strictObject({base:Et})),plans:e.object({}).strict(),pickers:e.object({}).strict()}).omit({paywall:!0}))});var et=e.enum(["funnel-run/1","funnel-process/1"]),Kn="funnel-process/1";var Se=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),tt=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),nt=B.refine(t=>new TextEncoder().encode(JSON.stringify(t)).byteLength<=8192,"Task data exceeds 8 KiB"),ve=e.record(Se,e.enum(["string","number","boolean","strings"])).refine(t=>Object.keys(t).length<=20,"Too many output fields"),Dt=C,rt=e.strictObject({type:e.literal("external_task"),endpointId:e.uuid(),taskKey:Se,inputs:e.record(Se,Dt).refine(t=>Object.keys(t).length<=20),outputs:ve}),it=e.strictObject({maxAttempts:e.number().int().min(1).max(5),retryDelaySeconds:e.number().int().min(1).max(30),backoff:e.enum(["fixed","exponential"]),requestTimeoutSeconds:e.number().int().min(1).max(10),timeoutSeconds:e.number().int().min(1).max(300)}).refine(t=>t.requestTimeoutSeconds<=t.timeoutSeconds,"Request timeout exceeds action deadline");var Pn=e.strictObject({outcome:e.enum(["success","failure"]),data:nt});var Vn=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("signal"),runId:e.uuid(),nodeId:tt,eventName:Q,eventId:e.uuid(),data:nt}),e.strictObject({operation:e.literal("read_results"),runId:e.uuid()})]),Un=e.strictObject({scope:V,runId:e.uuid(),eventId:e.uuid(),accepted:e.boolean()}),At=e.record(tt,be),Bn=e.strictObject({scope:V,runId:e.uuid(),results:At});var Ct=["id","externalUserId","createdAt","ageDays","subscription"],we=e.array(e.string().trim().min(1).max(40).refine(t=>!t.includes(","),"标签不能包含逗号")).max(20).refine(t=>new Set(t).size===t.length,"标签不能重复"),X=e.intersection(U,e.looseObject({tags:we.optional()})).refine(t=>![...Ct,"parameters","answers","results"].some(o=>Object.hasOwn(t,o)),"Reserved customer attribute"),Y=e.string().trim().max(80),ee=e.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),te=e.union([e.email().max(254),e.literal("")]),Nt=e.string().trim().min(1).max(255).refine(t=>!/\p{Cc}/u.test(t),"Fingerprint must not contain control characters"),ot=e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_"),"Reserved guest identity namespace"),Gn=e.object({externalUserId:ot.optional(),name:Y.default(""),email:te.default(""),phone:ee.optional(),attributes:X.default({})}).strict().refine(t=>t.externalUserId!==void 0||t.email!=="","请提供业务用户 ID 或邮箱"),ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("id"),value:e.uuid()}),e.strictObject({type:e.literal("externalUserId"),value:ot})]),re=e.strictObject({name:Y.optional(),email:te.optional(),phone:ee.optional(),attributes:X.optional(),fingerprint:Nt.optional()}),ie=t=>!t.customerData||t.customer?.type==="externalUserId",oe="customerData requires an externalUserId customer",at=e.object({id:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),name:Y,email:te,phone:ee.optional(),attributes:X,createdAt:e.iso.datetime()}).strict(),$n=e.object({customer:at,changed:e.boolean(),replayed:e.boolean()}).strict(),zt=e.discriminatedUnion("type",[e.object({type:e.literal("id"),value:e.uuid()}).strict(),e.object({type:e.literal("externalUserId"),value:e.string().trim().min(1).max(255)}).strict()]),Ft=e.object({name:Y.optional(),email:te.optional(),phone:ee.optional(),attributes:X.refine(t=>!Object.hasOwn(t,"tags"),"Use incremental tagChanges").optional(),removeAttributes:e.array(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(t=>!t.includes("tags")).optional(),tagChanges:e.strictObject({add:we,remove:we}).optional()}).strict().refine(t=>Object.keys(t).length>0,"请提供需要修改的字段"),Pt=e.object({lookup:zt}).strict(),Ln=Pt.extend({requestId:e.uuid(),patch:Ft}).strict(),Hn=e.object({search:e.string().trim().max(200).default(""),tag:e.string().trim().max(40).default(""),planId:e.string().max(200).default(""),versionId:e.string().max(200).default(""),holdingStatus:e.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:e.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:e.union([e.iso.datetime(),e.literal("")]).default(""),createdUntil:e.union([e.iso.datetime(),e.literal("")]).default(""),offset:e.coerce.number().int().min(0).max(1e5).default(0),limit:e.coerce.number().int().min(1).max(100).default(50)}).strict(),Zn=e.object({customers:at.array(),hasMore:e.boolean(),total:e.number().int().nonnegative().nullable(),evaluatedAt:e.iso.datetime()}).strict();var Yn=e.enum(["local","remote"]),Ie=e.strictObject({port:e.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:S.optional(),sticky:e.array(e.strictObject({expected:W.nullable(),next:W})).max(100),exposures:e.array(S).max(100),features:e.array(S).max(100)}),st=e.strictObject({type:e.literal("evaluate"),receiptId:e.uuid(),environmentId:e.uuid(),policyRevision:e.number().int().nonnegative(),attributes:U,sticky:e.record(e.string(),W)}),ct=st.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative()}),Vt=st.omit({type:!0,receiptId:!0}).extend({type:e.literal("evaluate_segment")}),ut=e.strictObject({nodeId:e.string().min(1).max(64),result:Ie}),lt=Vt.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),parameters:B,answers:J,variables:e.record(e.string(),S)});var Oe=e.discriminatedUnion("type",[e.strictObject({type:e.literal("literal"),value:S}),e.strictObject({type:e.literal("variable"),key:K,path:E.optional()}),e.strictObject({type:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),Ut=e.strictObject({requestId:e.uuid(),decisionId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),versionId:e.uuid(),receiptId:e.uuid(),value:S}),Bt={funnelId:e.uuid(),requestId:e.uuid(),customer:ne,customerData:re.optional(),attributes:U.refine(t=>!["parameters","answers","results","variables"].some(o=>Object.hasOwn(t,o)),"parameters, answers, results and variables are reserved flow namespaces")},cr=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("decide"),...Bt}).refine(ie,oe),e.strictObject({operation:e.literal("read_decision"),decisionId:e.uuid()}),e.strictObject({operation:e.literal("evaluate_decision"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),receiptId:e.uuid(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),result:Ie}),e.strictObject({operation:e.literal("feature_config"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("commit_decision_segment"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),steps:e.array(ut).max(32),boundary:e.strictObject({nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()}).optional()}),e.strictObject({operation:e.literal("segment_configuration"),funnelId:e.uuid(),versionId:e.uuid()}),e.strictObject({operation:e.literal("configuration"),funnelId:e.uuid(),versionId:e.uuid().optional()}),e.strictObject({operation:e.literal("local_configuration"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("report_used"),decisionId:e.uuid(),eventId:e.uuid(),occurredAt:e.iso.datetime({offset:!0}),reference:e.string().min(1).max(128).optional()})]),ur=e.strictObject({scope:V,decisionId:e.uuid(),requestId:e.uuid(),status:e.enum(["pending","completed","failed"]),decision:Ut.nullable(),evaluation:e.discriminatedUnion("type",[ct,lt]).optional()}).refine(t=>t.status==="completed"==(t.decision!==null)&&(!t.decision||t.decision.decisionId===t.decisionId&&t.decision.requestId===t.requestId),"Completed decisions carry their committed result"),lr=e.strictObject({scope:V,decisionId:e.uuid(),eventId:e.uuid(),source:e.literal("caller_reported")});function Mt(t,o=[]){let n=[];L(t,i=>{i.hidden&&n.push("Hidden components must not be delivered"),o.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let s=new Set(de(t).map(i=>i.key));for(let[i,a]of Object.entries(t.strings.locales))for(let f of Object.keys(a))s.has(f)||n.push(`Unused string ${f} must not be delivered (${i})`);return n}function pt(t){return t.hidden?null:t.type!=="stack"?t:{...t,children:t.children.flatMap(o=>pt(o)??[])}}function Tt(t){let o=t.pages.map(i=>{let a=pt(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(de({pages:o}).map(i=>i.key)),s=Object.fromEntries(Object.entries(t.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([f])=>n.has(f)))]));return{...t,pages:o,strings:{...t.strings,locales:s}}}function dt(t,o=[]){let n=H.parse(structuredClone(Tt(t))),s=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(s);for(let a of n.pages)if(!s(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Mt(n,o);if(i.length)throw new Error(i.join("; "));return n}var gr=e.strictObject({schemaVersion:e.literal(1),renderKey:e.string().min(1).max(256),routeTemplate:e.string().startsWith("/").max(2048),selectors:e.array(e.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:e.array(e.number().int().min(0)).min(1),absent:e.array(e.number().int().min(0))}).superRefine((t,o)=>{let n=[...t.present,...t.absent];(new Set(t.selectors).size!==t.selectors.length||new Set(n).size!==n.length||n.length!==t.selectors.length||n.some(s=>s>=t.selectors.length))&&o.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),mt=e.strictObject({renderKey:e.string().min(1).max(256),routeKey:e.string().min(1).max(256),stateKey:e.string().min(1).max(256),documentKey:e.string().min(1).max(256),documentHash:e.string().regex(/^[a-f0-9]{64}$/),compositionKey:e.string().min(1).max(256),entryMode:e.enum(["hard","soft"]),match:e.strictObject({present:e.array(e.number().int().min(0)),absent:e.array(e.number().int().min(0))})});var qt=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],je="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Gt=e.string().regex(new RegExp(`^${je}/${je}/${je}/manifest\\.json$`)),ft=e.strictObject({kind:e.literal("gcs-resumable"),url:e.url(),bucket:e.enum(qt),objectKey:Gt,byteLength:e.number().int().positive(),expiresAt:e.iso.datetime()}).superRefine((t,o)=>{let n=new URL(t.url),s=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${t.bucket}/o`||[...s.keys()].some(a=>!i.includes(a)||s.getAll(a).length!==1)||s.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(s.get("upload_id")??"")||s.has("name")&&s.get("name")!==`app-manifests/${t.objectKey}`||s.has("upload_protocol")&&s.get("upload_protocol")!=="resumable"||s.has("ifGenerationMatch")&&s.get("ifGenerationMatch")!=="0")&&o.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var h=e.string().min(1).max(256),j=e.string().regex(/^[a-f0-9]{64}$/),ae=e.strictObject({versionId:e.uuid(),manifestDigest:j,sourceGraphDigest:j,pageKey:h,stateKey:h,documentKey:h,documentHash:j,elementKey:h.optional(),nodeId:h.optional(),contentHash:j.optional(),renderKey:h.optional()}),gt=e.strictObject({pageKey:h,documentKey:h,expectedDocumentHash:j,renderKey:h.optional(),nodeId:h,elementKey:h,expectedContentHash:j,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),wr=e.strictObject({versionId:e.uuid(),manifestDigest:j,sourceGraphDigest:j,pageKey:h,stateKey:h,documentKey:h,documentHash:j,renderKey:h.optional(),patches:e.array(gt.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),$t=/^[a-z][a-z0-9-]{0,39}$/,G=e.string().regex($t),Re=e.enum(["web","ios","android"]),yt={requestId:e.uuid(),client:G,platform:Re,label:e.string().trim().min(1).max(100),sha256:j,bytes:e.number().int().min(1),transferBytes:e.number().int().min(1)},Lt=e.strictObject({action:e.literal("upload"),...yt,transferBytes:e.number().int().min(1).max(2e6),base64:e.string().min(4).max(2666668).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}),Ir=e.discriminatedUnion("action",[Lt,e.strictObject({action:e.literal("register"),...yt}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),variationId:h,changesetId:e.uuid().nullable(),expectedRevision:j.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(gt).max(200)})]),_e=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),clientKey:G,platform:Re,label:e.string(),sha256:j,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),Ht=e.strictObject({key:G,platform:Re,currentId:e.uuid().nullable()}),Or=e.strictObject({rows:e.array(_e).max(100),nextCursor:e.uuid().nullable(),clients:e.array(Ht).max(20)}),ke=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),jr=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:ke,runtime:ke,previews:ke})}),kr=e.strictObject({version:_e,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),Rr=e.strictObject({version:_e,upload:ft.nullable()}),_r=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:h,path:e.string(),documentKey:h,documentHash:j,initialStateKey:h,initialRenderKey:h})),renders:e.array(mt)}).loose().superRefine((t,o)=>{(!t.renders||t.routes.some(n=>!t.renders?.some(s=>s.renderKey===n.initialRenderKey&&s.routeKey===n.routeKey&&s.documentKey===n.documentKey&&s.stateKey===n.initialStateKey&&s.documentHash===n.documentHash&&s.entryMode==="hard")))&&o.addIssue({code:"custom",message:"Incomplete render catalog"})}),Kr=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:h,key:h,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),Er=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var Zt=e.strictObject({delaySeconds:e.number().int().min(0).max(86400).optional(),maxPerDay:e.number().int().min(1).max(100).optional(),maxPerSession:e.number().int().min(1).max(100).optional()}),bt=e.strictObject({id:e.uuid(),name:e.string().trim().min(1).max(80),client:G,source:ae,event:e.enum(["screen_enter","button_click"]),cooldownSeconds:e.number().int().min(0).max(2592e3),behavior:e.literal("observe"),delivery:Zt.optional()}).superRefine((t,o)=>{t.event==="button_click"&&(!t.source.nodeId||!t.source.elementKey)&&o.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var D={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},ht="00000000-0000-0000-0000-000000000000";var xt=e.strictObject({type:e.literal("bundle"),paywall:C.optional(),offering:C.optional(),coupons:C,data:C}),Wt=t=>e.strictObject({type:e.literal(t),id:e.uuid()}),Br=e.strictObject({type:e.literal("bundle"),paywallVersionId:e.uuid().optional(),offeringVersionId:e.uuid().optional(),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),data:S});var Mr=e.strictObject({type:e.literal("bundle"),offering:Wt("offering_version").nullable(),paywall:e.strictObject({versionId:e.uuid(),paywallId:e.uuid(),offeringVersionId:e.uuid()}).nullable(),coupons:e.array(Ze).max(20),data:S});var St=e.union([e.string(),e.number().finite(),e.boolean(),e.null()]),Jt=e.union([St,e.array(St).min(1).max(20)]),Qt=e.record(E,Jt).refine(t=>Object.keys(t).length<=10),vt=e.strictObject({path:E,type:e.enum(["string","number","boolean","strings"]),nullable:e.boolean().optional(),aggregation:e.enum(["count","exists"]).optional(),where:Qt.optional()}).superRefine((t,o)=>{(t.aggregation==="count"&&t.type!=="number"||t.aggregation==="exists"&&t.type!=="boolean"||!t.aggregation&&t.where)&&o.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var Xt=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],wt=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Yt=C,It=e.discriminatedUnion("type",[rt,e.strictObject({type:e.literal("claim_offer"),coupon:C}),e.strictObject({type:e.literal("event"),event:wt}),e.strictObject({type:e.literal("api"),operation:e.enum(Xt),inputs:e.record(E,Yt).refine(t=>Object.keys(t).length<=40),outputs:e.record(wt,vt).refine(t=>Object.keys(t).length<=20)})]);var y=Q,en=e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),k={id:y,name:e.string().trim().min(1).max(80),position:e.strictObject({x:e.number().finite(),y:e.number().finite()}).optional()},tn={success:y,cancel:y,unavailable:y,failure:y},nn=e.url().max(2048).refine(t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),rn=e.enum(["same_window","new_window"]),on=e.discriminatedUnion("type",[e.strictObject({...k,type:e.literal("entry"),next:y,triggers:e.array(bt).max(20).refine(t=>new Set(t.map(o=>o.id)).size===t.length,"Entry trigger IDs must be unique").optional()}),e.strictObject({...k,type:e.literal("screen"),screenId:y,presentation:Me,outputs:e.record(y,y),offering:e.discriminatedUnion("source",[e.strictObject({source:e.literal("variable"),key:K}),e.strictObject({source:e.literal("fixed"),versionId:e.uuid()})]).optional()}),e.strictObject({...k,type:e.literal("offering"),configuration:e.discriminatedUnion("source",[e.strictObject({source:e.literal("fixed"),versionId:e.uuid()}),e.strictObject({source:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("coupon"),couponId:e.uuid(),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("coupons"),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("output"),value:e.discriminatedUnion("type",[...Oe.options,xt,e.strictObject({type:e.literal("selection"),screenId:y,offeringKey:K})])}),e.strictObject({...k,type:e.literal("condition"),cases:e.array(e.strictObject({condition:qe,target:y})).min(1).max(50),default:y}),e.strictObject({...k,type:e.literal("feature"),featureKey:e.string().min(1).max(128),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("split"),experimentId:e.uuid(),applyPageExperiment:e.literal(!0).optional(),routes:e.record(en,y).refine(t=>Object.keys(t).length>=2&&Object.keys(t).length<=20),notParticipating:y}),e.strictObject({...k,type:e.literal("action"),...tn,execution:it,action:It,writes:ye.optional()}),e.strictObject({...k,type:e.literal("external_page"),appManifest:ae.optional(),url:nn,openIn:rn,opened:y,failed:y}),e.strictObject({...k,type:e.literal("end"),outcome:e.enum(["completed","closed","ineligible","failed"]),output:Oe.optional()}),e.strictObject({...k,type:e.literal("wait"),writes:ye.optional(),wait:e.discriminatedUnion("type",[e.strictObject({type:e.literal("duration"),delaySeconds:e.number().int().min(1).max(2592e3),elapsed:y}),e.strictObject({type:e.literal("event"),eventName:y,outputs:ve,timeoutSeconds:e.number().int().min(1).max(2592e3),received:y,timeout:y})])})]),Ke=e.strictObject({version:e.literal(5),entry:y,nodes:e.array(on).min(1).max(D.flowNodes)}),Ee=Ke.superRefine((t,o)=>{an(t,n=>o.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function se(t){switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[t.next];case"screen":return Object.values(t.outputs);case"condition":return[...t.cases.map(o=>o.target),t.default];case"split":return[...Object.values(t.routes),t.notParticipating];case"action":return[t.success,t.cancel,t.unavailable,t.failure];case"external_page":return[t.opened,t.failed];case"end":case"output":return[];case"wait":return t.wait.type==="duration"?[t.wait.elapsed]:[t.wait.received,t.wait.timeout]}}function an(t,o){let n=[],s=new Map(t.nodes.map(p=>[p.id,p])),i=(p,v,N)=>{n.push(p),o?.({message:p,reason:v,path:N?["nodes",t.nodes.indexOf(N)]:[]})};s.size!==t.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(s.get(t.entry)?.type!=="entry"||t.nodes.filter(p=>p.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(t.nodes.filter(p=>p.type==="screen").length>D.pages||t.nodes.filter(p=>!["screen","entry","end","output"].includes(p.type)).length>D.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let p of t.nodes){for(let v of se(p))v===t.entry&&i("An entry cannot be a transition target","entryTarget",p),s.has(v)||i(`Missing target ${v}`,"missingTarget",p);p.type==="screen"&&(a.has(p.screenId)&&i("Every screen has exactly one node owner","screenOwner",p),a.add(p.screenId))}let f=new Set,m=new Set,x=new Set;function _(p){if(f.has(p)){i("Flow edges must not form a cycle","cycle",s.get(p));return}if(!(m.has(p)||!s.has(p))){f.add(p),x.add(p);for(let v of se(s.get(p)))_(v);f.delete(p),m.add(p)}}_(t.entry);for(let p of t.nodes)x.has(p.id)||i("Every node must be reachable from Entry","unreachable",p);return[...new Set(n)]}var De={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Ot(t,o,n){let s=[...o].sort((m,x)=>x.length-m.length),i=new Set,a=(m,x=!1)=>{let _=s.find(p=>m===p||x&&m.startsWith(p+"."));i.add(_??m)};if(t.type==="condition"){let m=n?.startsWith("case_")?Number(n.slice(5)):t.cases.length-1;for(let x of t.cases.slice(0,m+1))for(let _ of q(x.condition))_.startsWith("variables.")&&a(_.slice(10),!0)}if(t.type==="screen"&&t.offering?.source==="variable"&&a(t.offering.key),t.type==="action"&&(t.action.type==="api"||t.action.type==="external_task"))for(let m of Object.values(t.action.inputs))m.source==="variable"&&a(m.key);t.type==="action"&&t.action.type==="claim_offer"&&t.action.coupon.source==="variable"&&a(t.action.coupon.key);let f=t.type==="output"?t.value:t.type==="end"?t.output:null;if(f?.type==="variable"&&a(f.key),f?.type==="bundle")for(let m of[f.paywall,f.offering,f.coupons,f.data])m?.source==="variable"&&a(m.key);return f?.type==="selection"&&a(f.offeringKey),[...i]}var M=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ce=t=>e.record(e.string(),S).refine(o=>F(o)<=t,"Funnel evidence exceeds its byte budget"),xi=e.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Ce=e.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("flag"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("experiment"),id:e.uuid()}),e.strictObject({type:e.literal("saved_group"),id:e.uuid()}),e.strictObject({type:e.literal("config"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("constant"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("paywall_version"),id:e.uuid()}),e.strictObject({type:e.literal("offering_version"),id:e.uuid()}),e.strictObject({type:e.literal("reward"),id:e.uuid()})]),Si=e.strictObject({schemaVersion:e.literal(1),kind:Ce,selector:Ne.nullable(),context:ce(131072),contract:e.strictObject({version:e.number().int().positive(),evaluator:e.string().min(1).max(128),policyRevision:e.number().int().nonnegative()})}).refine(t=>F(t)<=131072,"Node input exceeds its byte budget"),vi=e.strictObject({schemaVersion:e.literal(1),kind:Ce,outcome:e.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ce(131072),route:e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ce(131072)}).refine(t=>F(t)<=131072,"Node result exceeds its byte budget"),wi=e.strictObject({schemaVersion:e.literal(1),operations:e.record(M,e.strictObject({attempts:e.number().int().nonnegative(),maxAttempts:e.number().int().min(1).max(5),deadlineAt:e.iso.datetime({offset:!0}),retryAt:e.iso.datetime({offset:!0}).nullable(),error:e.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:e.strictObject({type:M,id:e.uuid()}).nullable()}))}).refine(t=>F(t)<=65536,"Execution state exceeds its byte budget"),P={receiptId:e.uuid()},Ae=e.iso.datetime({offset:!0}),Ii=e.discriminatedUnion("type",[e.strictObject({type:e.literal("node_entered"),details:e.strictObject({kind:Ce})}),e.strictObject({type:e.literal("presentation_shown"),details:e.strictObject({...P,source:e.literal("client"),occurredAt:Ae.optional()})}),e.strictObject({type:e.literal("decision_accepted"),details:e.strictObject(P)}),e.strictObject({type:e.literal("signal_received"),details:e.strictObject({signalId:e.uuid(),nodeId:M,eventName:M,data:ce(8192),source:e.literal("server"),occurredAt:Ae})}),e.strictObject({type:e.literal("signal_consumed"),details:e.strictObject({...P,signalId:e.uuid()})}),e.strictObject({type:e.literal("wait_elapsed"),details:e.strictObject(P)}),e.strictObject({type:e.literal("wait_timeout"),details:e.strictObject(P)}),e.strictObject({type:e.literal("operation_completed"),details:e.strictObject({...P,operation:M,reference:e.strictObject({type:M,id:e.uuid()}).nullable()})}),e.strictObject({type:e.literal("execution_recovered"),details:e.strictObject({generation:e.number().int().positive(),reason:e.enum(["interrupted","expired_lease","delivery_failed"])})}),e.strictObject({type:e.literal("execution_failed"),details:e.strictObject({generation:e.number().int().positive(),code:e.string().regex(/^[a-z_]{1,64}$/)})}),e.strictObject({type:e.literal("run_completed"),details:e.strictObject({outcome:e.enum(["completed","ineligible","failed"])})}),e.strictObject({type:e.literal("run_closed"),details:e.strictObject({source:e.enum(["client","server","expiry"])})}),e.strictObject({type:e.literal("treatment_used"),details:e.strictObject({...P,source:e.enum(["client","server"]),occurredAt:Ae,reference:e.string().min(1).max(128).optional()})})]);var R=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sn=e.discriminatedUnion("type",[e.strictObject({id:R,type:e.literal("owned"),publicData:Ye.optional(),document:H.refine(t=>["page","popup","onboarding"].includes(t.surface)&&t.pages.length===1&&t.actions.every(o=>o.type==="event"&&!o.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),e.strictObject({id:R,type:e.literal("paywall"),paywallVersionId:e.uuid()})]),ze={executionContract:et.optional(),kind:e.literal("funnel"),schemaVersion:e.literal(4),screens:e.array(sn).max(D.pages),references:e.record(R,Ne).refine(t=>Object.keys(t).length<=500),inputs:e.array(e.strictObject({variable:R,screenId:R,componentId:R,required:e.boolean()})).max(D.questions),variables:e.record(K,ge).refine(t=>Object.keys(t).length<=D.logicNodes),outputSchema:fe,execution:e.strictObject({runTimeoutSeconds:e.number().int().min(1).max(De.runTimeoutSeconds),maxTransitions:e.number().int().min(1).max(De.maxTransitions)})},$i=e.strictObject({...ze,graph:Ke});function cn(t,o){let n=!1,s=(i,a)=>{let f=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(t.strings.locales).some(m=>m[i.text]?.includes("{{offer."))&&!(f&&o(f))&&(n=!0),i.type==="stack"&&i.children.forEach(m=>s(m,f))};for(let i of t.pages)s(i.root);return n}function le(t){return Array.isArray(t)?t.some(le):!t||typeof t!="object"?!1:Object.entries(t).some(([o,n])=>o==="productVersionId"?n===ht:le(n))}function un(t){let o=[],n=new Set(Object.values(t.references).flatMap(s=>s.type==="reward"?[s.id]:[]));for(let[s,i]of t.screens.entries()){if(i.type!=="owned")continue;let a;try{a=dt(i.document)}catch(f){o.push({message:f instanceof Error?f.message:"Screen cannot be delivered",reason:"screen",path:["screens",s,"document"]});continue}for(let[f,m]of t.inputs.entries())m.screenId===i.id&&!me(a,m.componentId)&&o.push({message:`Local Funnel input ${m.variable} targets hidden component ${m.componentId} on screen ${m.screenId}`,reason:"inputBinding",path:["inputs",f]})}for(let[s,i]of t.graph.nodes.entries()){let a=["graph","nodes",s],f=i.type==="screen"?t.screens.find(m=>m.id===i.screenId):void 0;f?.type==="owned"&&(f.document.actions.some(m=>typeof m.properties.templateKey=="string"&&m.properties.templateKey.startsWith("popup-coupon-"))&&o.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),cn(f.document,m=>n.has(m))&&o.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&le(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&le(i.output.value))&&o.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return o}function jt(t,o){for(let{message:n,reason:s,path:i}of un(t))o.addIssue({code:"custom",message:n,path:i,params:{reason:s}})}function kt(t,o){let n=(d,r,c=[])=>o.addIssue({code:"custom",message:d,path:c,params:{reason:r}}),s=Object.values(t.references),i=new Map(t.screens.map(d=>[d.id,d])),a=(d,r)=>s.some(c=>c.type===d&&("id"in c?c.id:c.key)===r);i.size!==t.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let f=t.graph.nodes.filter(d=>d.type==="screen");(f.length!==i.size||f.some(d=>!i.has(d.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let m=new Map,x=Object.keys(t.variables);x.some(d=>x.some(r=>d!==r&&r.startsWith(d+".")))&&n("Variable paths must not overlap","variable");function _(d,r){Object.hasOwn(t.variables,d)||n("Every produced variable needs a declaration","variable",["graph","nodes",t.graph.nodes.indexOf(r)]);let c=m.get(d)??new Set;c.add(r.id),m.set(d,c)}for(let[d,r]of t.graph.nodes.entries()){let c=["graph","nodes",d],w=r.type==="feature"?r.featureKey:r.type==="offering"&&r.configuration.source==="feature"?r.configuration.featureKey:r.type==="output"&&r.value.type==="feature"?r.value.featureKey:r.type==="end"&&r.output?.type==="feature"?r.output.featureKey:null;w&&!a("flag",w)&&n("Flag selectors require an explicit GB resource reference","feature",c);let I=r.type==="feature"||r.type==="offering"||r.type==="coupon"||r.type==="coupons"||r.type==="action"&&r.action.type==="api"?["value"]:r.type==="action"&&r.action.type==="external_task"?Object.keys(r.action.outputs):r.type==="wait"&&r.wait.type==="event"?Object.keys(r.wait.outputs):[],O="writes"in r?r.writes??{}:{};(I.length!==Object.keys(O).length||I.some(u=>!Object.hasOwn(O,u))||new Set(Object.values(O)).size!==Object.values(O).length)&&n("Node writes must map every named output exactly once","variable",c);for(let[u,b]of Object.entries(O)){_(b,r);let g=t.variables[b],l=r.type==="offering"?"offering_version":r.type==="coupon"?"reward":r.type==="action"&&r.action.type==="api"?"json":r.type==="action"&&r.action.type==="external_task"?r.action.outputs[u]:r.type==="wait"&&r.wait.type==="event"?r.wait.outputs[u]:void 0;(g?.source.type!=="node"||l&&g.type!==l)&&n("Node writer source or output type does not match declaration","variable",c)}if(r.type==="coupons"){let u=t.variables[r.writes.value];(u?.type!=="array"||u.items?.type!=="reward"||u.items.nullable||u.nullable)&&n("Coupons output requires a non-null Reward array","variable",c);for(let b of r.couponIds)a("reward",b)||n("Coupons require Reward references","coupon",c)}if(r.type==="split"&&!a("experiment",r.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",c),r.type==="coupon"&&!a("reward",r.couponId)&&n("Coupon selectors require a Reward reference","coupon",c),r.type==="action"&&r.action.type==="claim_offer"&&r.action.coupon.source==="literal"){let u=r.action.coupon.value;(!u||typeof u!="object"||Array.isArray(u)||u.type!=="reward"||typeof u.id!="string"||Object.keys(u).length!==2||!a("reward",u.id))&&n("Coupon claims require a Reward reference","coupon",c)}if(r.type==="offering"&&r.configuration.source==="fixed"&&!a("offering_version",r.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",c),r.type==="screen"&&r.offering?.source==="variable"&&t.variables[r.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",c),r.type==="action"&&r.action.type==="claim_offer"&&r.action.coupon.source==="variable"&&(t.variables[r.action.coupon.key]?.type!=="reward"||r.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",c),r.type==="screen"){let u=i.get(r.screenId);if(r.offering?.source==="fixed"&&!a("offering_version",r.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",c),u?.type==="paywall"&&r.offering&&n("Paywall owns its fixed Offering Version","offering",c),u?.type==="paywall"&&!a("paywall_version",u.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",c),u?.type==="owned"){let b=u.document.pages[0];if(!b){n("Owned screen requires a page","screen",c);continue}Te(u.document).some(l=>!l.complete)&&n("Owned screens require complete local content","translations",c);let g=new Set(u.document.actions.map(l=>l.id));(g.size!==Object.keys(r.outputs).length||Object.keys(r.outputs).some(l=>!g.has(l)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",c),Z(b.root,l=>{!r.offering&&(l.type==="plan_picker"||(l.type==="stack"||l.type==="button")&&l.bind?.plan||l.type==="customer_data"&&["customer_plans","credit_packs"].includes(l.data.source))&&n("Product presentation requires an Offering Version","offering",c),l.type==="customer_data"&&Object.values(l.data.outputs??{}).some(z=>z!==void 0&&!g.has(z))&&n("Customer components require declared screen outcomes","componentOutput",c)})}}r.type==="end"&&["completed","ineligible"].includes(r.outcome)&&!r.output&&n("Completed and ineligible ends require a declared output","output",c),r.type==="end"&&r.output?.type==="literal"&&!T(t.outputSchema,r.output.value)&&n("Terminal output does not match outputSchema","output",c),r.type==="output"&&r.value.type==="literal"&&!T(t.outputSchema,r.value.value)&&n("Terminal output does not match outputSchema","output",c);let A=r.type==="output"?r.value:r.type==="end"?r.output:void 0;if(A?.type==="variable"&&!A.path){let u=t.variables[A.key];u&&!$e(u,t.outputSchema)&&n("Variable output does not match outputSchema","output",c)}if(r.type==="screen"){let u=i.get(r.screenId);if(u?.type==="owned")for(let b of xe(u.document))(/^(input|params)\./.test(b)||b.startsWith("variables.")&&!he(b.slice(10),x))&&n("Screen values must reference registered variables","variable",c)}if(r.type==="condition")for(let u of r.cases){for(let b of Ge(u.condition))a("saved_group",b)||n("Conditions require explicit Saved Group references","savedGroup",c);for(let b of q(u.condition))b.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",c)}if(r.type==="output"&&r.value.type==="bundle"){t.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",c);for(let[u,b]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let g=r.value[u];if(g)if(g.source==="literal"){let l=u==="coupons"?g.value:[g.value];(!Array.isArray(l)||l.length>20||l.some(z=>!T({type:b,nullable:!1},z)||!a(b,z.id))||u==="coupons"&&new Set(l.map(z=>z.id)).size!==l.length)&&n("Bundle requires distinct scoped resource references",u==="coupons"?"coupon":u==="paywall"?"paywall":"offering",[...c,"value",u])}else{let l=t.variables[g.key];(g.path||!l||l.nullable||(u==="coupons"?l.type!=="array"||l.items?.type!=="reward"||l.items.nullable:l.type!==b))&&n("Bundle binding type does not match its slot","output",c)}}}}for(let[d,r]of t.graph.nodes.entries()){let c=r.type==="screen"?i.get(r.screenId):void 0,w=[...Ot(r,x),...c?.type==="owned"?Xe(c.document).map(I=>he(I,x)?.key??I):[]];for(let I of new Set(w)){let b=function(g){if(g===r.id)return!0;if(u.has(g))return!1;u.add(g);let l=t.graph.nodes.find(Rt=>Rt.id===g);return l?(A.has(g)?l.type==="action"?[l.cancel,l.unavailable,l.failure]:l.type==="wait"&&l.wait.type==="event"?[l.wait.timeout]:[]:se(l)).some(b):!1};var N=b;if(!Object.hasOwn(t.variables,I)){n("Consumed variable is undeclared","variable",["graph","nodes",d]);continue}let O=t.variables[I];if(r.type==="screen"&&O.source.type==="input"&&t.inputs.some(g=>g.screenId===r.screenId&&g.variable===I)||O.source.type==="parameter"||O.source.type==="attribute")continue;let A=O.source.type==="input"?new Set(t.inputs.filter(g=>g.variable===I&&g.required).flatMap(g=>f.filter(l=>l.screenId===g.screenId).map(l=>l.id))):m.get(I)??new Set,u=new Set;(!A.size||b(t.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",d])}}(new Set(t.inputs.map(d=>d.variable)).size!==t.inputs.length||new Set(t.inputs.map(d=>`${d.screenId}:${d.componentId}`)).size!==t.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[d,r]of t.inputs.entries()){t.variables[r.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",d]);let c=i.get(r.screenId),w=c?.type==="owned"?me(c.document,r.componentId):null;if((w?.type!=="stack"||!w.interaction||!["input","toggle","select","multiselect","tabs"].includes(w.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",d]),w?.type==="stack"&&w.interaction){let I=w.interaction.type==="toggle"?"boolean":w.interaction.type==="multiselect"?"strings":"string";t.variables[r.variable]?.type!==I&&n("Input variable type does not match component","inputBinding",["inputs",d]);let O=t.variables[r.variable]?.enum;O&&!w.children.filter(A=>!A.hidden).every(A=>O.includes(A.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",d])}}for(let[d,r]of Object.entries(t.variables))r.enum&&r.type!=="string"&&n("Only string variables support enum","variable",["variables",d]),r.source.type==="input"&&!t.inputs.some(c=>c.variable===d)&&n("Input variable requires a component binding","inputBinding",["variables",d]);let p=0,v=0;for(let d of t.screens)if(d.type==="owned"){for(let r of d.document.pages)Z(r.root,()=>{p++});v+=d.document.actions.length}(p>D.components||v>D.actions||F(t)>D.documentBytes)&&n("Funnel document exceeds its budget","budget")}var ln=e.strictObject({...ze,graph:Ee}).superRefine(kt),pn=e.strictObject({...ze,graph:Ee,displayName:e.string().trim().min(1).max(80)}).superRefine(kt),Li=pn.superRefine(jt),Hi=ln.superRefine(jt),ue=e.string().regex(Fe),$={requestId:e.uuid(),nodeId:R,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),customerToken:ue.optional()},dn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("screen"),output:R,answers:J,selection:e.record(R,e.union([e.string().max(200),e.boolean(),e.number().int().min(0).max(1e4)])).optional()}),e.strictObject({type:e.literal("paywall_quote"),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),actionId:R,productVersionId:e.uuid(),offerId:e.uuid().optional(),nativeOffer:He.optional(),subscriptionChange:We.optional(),predecessor:e.strictObject({operationId:e.uuid().nullable(),generation:e.number().int().positive()}).optional()}),e.strictObject({type:e.literal("paywall_confirm"),operationId:e.uuid(),merchantConfirmation:Pe.optional()}),e.strictObject({type:e.literal("paywall_cancel"),operationId:e.uuid()}),e.strictObject({type:e.literal("client_action"),receiptId:e.uuid(),outcome:e.enum(["success","cancel","failure","opened","failed"])})]),mn=e.object({nodeId:R,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),components:e.record(R,e.object({resourceKey:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:e.number().int().min(1).max(1e5),after:Je.nullable(),filter:e.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(t=>Object.keys(t).length<=150)}).strict(),Zi=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("start"),funnelId:e.uuid(),requestId:e.uuid(),customer:ne.optional(),customerData:re.optional(),locale:e.string().min(1).max(35),parameters:B}).refine(ie,oe),e.strictObject({operation:e.literal("get"),settlementRequestId:e.uuid().optional(),data:mn.optional(),purchase:e.strictObject({receiptId:e.uuid(),operationId:e.uuid()}).optional(),customerToken:ue.optional()}),e.strictObject({operation:e.literal("resume"),requestId:e.uuid(),customerToken:ue.optional()}),e.strictObject({operation:e.literal("submit"),...$,input:dn}),e.strictObject({operation:e.literal("back"),...$}),e.strictObject({operation:e.literal("shown"),...$}),e.strictObject({operation:e.literal("close"),...$}),e.strictObject({operation:e.literal("commit_segment"),...$,policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256)}),e.strictObject({operation:e.literal("review"),receiptId:e.uuid().optional(),customerToken:ue.optional()})]);export{_t as a,Xe as b,F as c,Kt as d,Kn as e,Mt as f,gr as g,wr as h,Zt as i,Vn as j,Un as k,Bn as l,Vt as m,Ct as n,Nt as o,Gn as p,ne as q,re as r,ie as s,oe as t,at as u,$n as v,Pt as w,Ln as x,Hn as y,Zn as z,Oe as A,Bt as B,cr as C,ur as D,lr as E,nn as F,rn as G,Si as H,vi as I,pn as J,Zi as K};
1
+ import{a as He,i as Ze,y as We}from"./chunk-WVTKVQLZ.js";import{w as Pe}from"./chunk-QTXHF27F.js";import{a as K,b as fe,c as ge,d as ye,e as T,f as $e,g as Le,j as be,m as Q}from"./chunk-44ZJPQM6.js";import{a as q}from"./chunk-VILB5M4X.js";import{a as Fe}from"./chunk-KJTHMRSH.js";import{m as Je,n as J,o as B}from"./chunk-JW4MSBYN.js";import{C as me,f as Ve,g as Ue,h as Be,p as pe,v as L,w as H,x as Z,y as de,z as Te}from"./chunk-EJSTRCBQ.js";import{b as Me,d as S,e as U,f as qe,g as Ge,h as W}from"./chunk-LUVTP4VU.js";import{h as V}from"./chunk-TFPLIX5E.js";import{b as e}from"./chunk-S7NHVERO.js";var E=e.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(t=>t.split(".").every(o=>!["__proto__","constructor","prototype"].includes(o)),"Reserved value path"),C=e.discriminatedUnion("source",[e.strictObject({source:e.literal("literal"),value:S}),e.strictObject({source:e.literal("variable"),key:e.string().min(1).max(255),path:E.optional()})]);function Qe(t,o){if(!o)return t;for(let n of E.parse(o).split(".")){if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=t.length)return;t=t[Number(n)];continue}if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=Reflect.get(t,n)}return t}function _t(t,o){if(t.source==="literal")return structuredClone(t.value);let n=Le(o.declarations,o);if(!Object.hasOwn(n,t.key))throw new Error("Capability input is missing");return structuredClone(S.parse(Qe(n[t.key],t.path)))}function he(t,o){let n=[...o].sort((i,a)=>a.length-i.length).find(i=>t===i||t.startsWith(i+"."));if(!n)return null;let s=t===n?void 0:t.slice(n.length+1);return s&&!E.safeParse(s).success?null:{key:n,path:s}}function xe(t){let o=Object.values(t.strings.locales).flatMap(n=>Object.values(n));return L(t,n=>{n.type==="custom_html"&&o.push(...Object.values(n.html))}),[...new Set(o.flatMap(Be))]}function Xe(t){return xe(t).filter(o=>o.startsWith("variables.")).map(o=>o.slice(10))}function F(t){let o=JSON.stringify(t);if(o===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(o).length,s=!1;for(let i=0;i<o.length;i++){let a=o.charAt(i);if(s)a==="\\"?i++:a==='"'&&(s=!1);else if(a==='"')s=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let f=i;for(;i+1<o.length&&/[0-9.eE+-]/.test(o.charAt(i+1));)i++;let m=o.slice(f,i+1);if(!/[eE]/.test(m))continue;let[x="",_]=m.split(/[eE]/),p=x.replace(/^-/,""),v=p.replace(".","").length,N=(p.includes(".")?p.indexOf("."):v)+Number(_),d=N<=0?2-N+v:N>=v?N:v+1;n+=d+(x.startsWith("-")?1:0)-m.length}}return n}var Kt=e.string().regex(/^[a-f0-9]{64}$/),Et=Ve.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Ye=e.strictObject({couponDigests:e.record(e.uuid(),Kt),variables:e.record(pe,e.record(e.uuid(),e.partialRecord(e.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),e.string()))),locales:e.record(pe,Ue.extend({nodes:e.record(e.string(),e.strictObject({base:Et})),plans:e.object({}).strict(),pickers:e.object({}).strict()}).omit({paywall:!0}))});var et=e.enum(["funnel-run/1","funnel-process/1"]),Kn="funnel-process/1";var Se=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),tt=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),nt=B.refine(t=>new TextEncoder().encode(JSON.stringify(t)).byteLength<=8192,"Task data exceeds 8 KiB"),ve=e.record(Se,e.enum(["string","number","boolean","strings"])).refine(t=>Object.keys(t).length<=20,"Too many output fields"),Dt=C,rt=e.strictObject({type:e.literal("external_task"),endpointId:e.uuid(),taskKey:Se,inputs:e.record(Se,Dt).refine(t=>Object.keys(t).length<=20),outputs:ve}),it=e.strictObject({maxAttempts:e.number().int().min(1).max(5),retryDelaySeconds:e.number().int().min(1).max(30),backoff:e.enum(["fixed","exponential"]),requestTimeoutSeconds:e.number().int().min(1).max(10),timeoutSeconds:e.number().int().min(1).max(300)}).refine(t=>t.requestTimeoutSeconds<=t.timeoutSeconds,"Request timeout exceeds action deadline");var Pn=e.strictObject({outcome:e.enum(["success","failure"]),data:nt});var Vn=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("signal"),runId:e.uuid(),nodeId:tt,eventName:Q,eventId:e.uuid(),data:nt}),e.strictObject({operation:e.literal("read_results"),runId:e.uuid()})]),Un=e.strictObject({scope:V,runId:e.uuid(),eventId:e.uuid(),accepted:e.boolean()}),At=e.record(tt,be),Bn=e.strictObject({scope:V,runId:e.uuid(),results:At});var Ct=["id","externalUserId","createdAt","ageDays","subscription"],we=e.array(e.string().trim().min(1).max(40).refine(t=>!t.includes(","),"标签不能包含逗号")).max(20).refine(t=>new Set(t).size===t.length,"标签不能重复"),X=e.intersection(U,e.looseObject({tags:we.optional()})).refine(t=>![...Ct,"parameters","answers","results"].some(o=>Object.hasOwn(t,o)),"Reserved customer attribute"),Y=e.string().trim().max(80),ee=e.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),te=e.union([e.email().max(254),e.literal("")]),Nt=e.string().trim().min(1).max(255).refine(t=>!/\p{Cc}/u.test(t),"Fingerprint must not contain control characters"),ot=e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_"),"Reserved guest identity namespace"),Gn=e.object({externalUserId:ot.optional(),name:Y.default(""),email:te.default(""),phone:ee.optional(),attributes:X.default({})}).strict().refine(t=>t.externalUserId!==void 0||t.email!=="","请提供业务用户 ID 或邮箱"),ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("id"),value:e.uuid()}),e.strictObject({type:e.literal("externalUserId"),value:ot})]),re=e.strictObject({name:Y.optional(),email:te.optional(),phone:ee.optional(),attributes:X.optional(),fingerprint:Nt.optional()}),ie=t=>!t.customerData||t.customer?.type==="externalUserId",oe="customerData requires an externalUserId customer",at=e.object({id:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),name:Y,email:te,phone:ee.optional(),attributes:X,createdAt:e.iso.datetime()}).strict(),$n=e.object({customer:at,changed:e.boolean(),replayed:e.boolean()}).strict(),zt=e.discriminatedUnion("type",[e.object({type:e.literal("id"),value:e.uuid()}).strict(),e.object({type:e.literal("externalUserId"),value:e.string().trim().min(1).max(255)}).strict()]),Ft=e.object({name:Y.optional(),email:te.optional(),phone:ee.optional(),attributes:X.refine(t=>!Object.hasOwn(t,"tags"),"Use incremental tagChanges").optional(),removeAttributes:e.array(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(t=>!t.includes("tags")).optional(),tagChanges:e.strictObject({add:we,remove:we}).optional()}).strict().refine(t=>Object.keys(t).length>0,"请提供需要修改的字段"),Pt=e.object({lookup:zt}).strict(),Ln=Pt.extend({requestId:e.uuid(),patch:Ft}).strict(),Hn=e.object({search:e.string().trim().max(200).default(""),tag:e.string().trim().max(40).default(""),planId:e.string().max(200).default(""),versionId:e.string().max(200).default(""),holdingStatus:e.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:e.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:e.union([e.iso.datetime(),e.literal("")]).default(""),createdUntil:e.union([e.iso.datetime(),e.literal("")]).default(""),offset:e.coerce.number().int().min(0).max(1e5).default(0),limit:e.coerce.number().int().min(1).max(100).default(50)}).strict(),Zn=e.object({customers:at.array(),hasMore:e.boolean(),total:e.number().int().nonnegative().nullable(),evaluatedAt:e.iso.datetime()}).strict();var Yn=e.enum(["local","remote"]),Ie=e.strictObject({port:e.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:S.optional(),sticky:e.array(e.strictObject({expected:W.nullable(),next:W})).max(100),exposures:e.array(S).max(100),features:e.array(S).max(100)}),st=e.strictObject({type:e.literal("evaluate"),receiptId:e.uuid(),environmentId:e.uuid(),policyRevision:e.number().int().nonnegative(),attributes:U,sticky:e.record(e.string(),W)}),ct=st.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative()}),Vt=st.omit({type:!0,receiptId:!0}).extend({type:e.literal("evaluate_segment")}),ut=e.strictObject({nodeId:e.string().min(1).max(64),result:Ie}),lt=Vt.extend({runId:e.uuid(),versionId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),parameters:B,answers:J,variables:e.record(e.string(),S)});var Oe=e.discriminatedUnion("type",[e.strictObject({type:e.literal("literal"),value:S}),e.strictObject({type:e.literal("variable"),key:K,path:E.optional()}),e.strictObject({type:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),Ut=e.strictObject({requestId:e.uuid(),decisionId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(255).nullable(),versionId:e.uuid(),receiptId:e.uuid(),value:S}),Bt={funnelId:e.uuid(),requestId:e.uuid(),customer:ne,customerData:re.optional(),attributes:U.refine(t=>!["parameters","answers","results","variables"].some(o=>Object.hasOwn(t,o)),"parameters, answers, results and variables are reserved flow namespaces")},cr=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("decide"),...Bt}).refine(ie,oe),e.strictObject({operation:e.literal("read_decision"),decisionId:e.uuid()}),e.strictObject({operation:e.literal("evaluate_decision"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),receiptId:e.uuid(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),result:Ie}),e.strictObject({operation:e.literal("feature_config"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("commit_decision_segment"),decisionId:e.uuid(),requestId:e.uuid(),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256),steps:e.array(ut).max(32),boundary:e.strictObject({nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()}).optional()}),e.strictObject({operation:e.literal("segment_configuration"),funnelId:e.uuid(),versionId:e.uuid()}),e.strictObject({operation:e.literal("configuration"),funnelId:e.uuid(),versionId:e.uuid().optional()}),e.strictObject({operation:e.literal("local_configuration"),funnelId:e.uuid()}),e.strictObject({operation:e.literal("report_used"),decisionId:e.uuid(),eventId:e.uuid(),occurredAt:e.iso.datetime({offset:!0}),reference:e.string().min(1).max(128).optional()})]),ur=e.strictObject({scope:V,decisionId:e.uuid(),requestId:e.uuid(),status:e.enum(["pending","completed","failed"]),decision:Ut.nullable(),evaluation:e.discriminatedUnion("type",[ct,lt]).optional()}).refine(t=>t.status==="completed"==(t.decision!==null)&&(!t.decision||t.decision.decisionId===t.decisionId&&t.decision.requestId===t.requestId),"Completed decisions carry their committed result"),lr=e.strictObject({scope:V,decisionId:e.uuid(),eventId:e.uuid(),source:e.literal("caller_reported")});function Mt(t,o=[]){let n=[];L(t,i=>{i.hidden&&n.push("Hidden components must not be delivered"),o.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let s=new Set(de(t).map(i=>i.key));for(let[i,a]of Object.entries(t.strings.locales))for(let f of Object.keys(a))s.has(f)||n.push(`Unused string ${f} must not be delivered (${i})`);return n}function pt(t){return t.hidden?null:t.type!=="stack"?t:{...t,children:t.children.flatMap(o=>pt(o)??[])}}function Tt(t){let o=t.pages.map(i=>{let a=pt(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(de({pages:o}).map(i=>i.key)),s=Object.fromEntries(Object.entries(t.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([f])=>n.has(f)))]));return{...t,pages:o,strings:{...t.strings,locales:s}}}function dt(t,o=[]){let n=H.parse(structuredClone(Tt(t))),s=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(s);for(let a of n.pages)if(!s(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Mt(n,o);if(i.length)throw new Error(i.join("; "));return n}var gr=e.strictObject({schemaVersion:e.literal(1),renderKey:e.string().min(1).max(256),routeTemplate:e.string().startsWith("/").max(2048),selectors:e.array(e.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:e.array(e.number().int().min(0)).min(1),absent:e.array(e.number().int().min(0))}).superRefine((t,o)=>{let n=[...t.present,...t.absent];(new Set(t.selectors).size!==t.selectors.length||new Set(n).size!==n.length||n.length!==t.selectors.length||n.some(s=>s>=t.selectors.length))&&o.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),mt=e.strictObject({renderKey:e.string().min(1).max(256),routeKey:e.string().min(1).max(256),stateKey:e.string().min(1).max(256),documentKey:e.string().min(1).max(256),documentHash:e.string().regex(/^[a-f0-9]{64}$/),compositionKey:e.string().min(1).max(256),entryMode:e.enum(["hard","soft"]),match:e.strictObject({present:e.array(e.number().int().min(0)),absent:e.array(e.number().int().min(0))})});var qt=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],je="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Gt=e.string().regex(new RegExp(`^${je}/${je}/${je}/manifest\\.json$`)),ft=e.strictObject({kind:e.literal("gcs-resumable"),url:e.url(),bucket:e.enum(qt),objectKey:Gt,byteLength:e.number().int().positive(),expiresAt:e.iso.datetime()}).superRefine((t,o)=>{let n=new URL(t.url),s=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${t.bucket}/o`||[...s.keys()].some(a=>!i.includes(a)||s.getAll(a).length!==1)||s.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(s.get("upload_id")??"")||s.has("name")&&s.get("name")!==`app-manifests/${t.objectKey}`||s.has("upload_protocol")&&s.get("upload_protocol")!=="resumable"||s.has("ifGenerationMatch")&&s.get("ifGenerationMatch")!=="0")&&o.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var h=e.string().min(1).max(256),j=e.string().regex(/^[a-f0-9]{64}$/),ae=e.strictObject({versionId:e.uuid(),manifestDigest:j,sourceGraphDigest:j,pageKey:h,stateKey:h,documentKey:h,documentHash:j,elementKey:h.optional(),nodeId:h.optional(),contentHash:j.optional(),renderKey:h.optional()}),gt=e.strictObject({pageKey:h,documentKey:h,expectedDocumentHash:j,renderKey:h.optional(),nodeId:h,elementKey:h,expectedContentHash:j,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),wr=e.strictObject({versionId:e.uuid(),manifestDigest:j,sourceGraphDigest:j,pageKey:h,stateKey:h,documentKey:h,documentHash:j,renderKey:h.optional(),patches:e.array(gt.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),$t=/^[a-z][a-z0-9-]{0,39}$/,G=e.string().regex($t),Re=e.enum(["web","ios","android"]),yt={requestId:e.uuid(),client:G,platform:Re,label:e.string().trim().min(1).max(100),sha256:j,bytes:e.number().int().min(1),transferBytes:e.number().int().min(1)},Lt=e.strictObject({action:e.literal("upload"),...yt,transferBytes:e.number().int().min(1).max(2e6),base64:e.string().min(4).max(2666668).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}),Ir=e.discriminatedUnion("action",[Lt,e.strictObject({action:e.literal("register"),...yt}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),variationId:h,changesetId:e.uuid().nullable(),expectedRevision:j.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(gt).max(200)})]),_e=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),clientKey:G,platform:Re,label:e.string(),sha256:j,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),Ht=e.strictObject({key:G,platform:Re,currentId:e.uuid().nullable()}),Or=e.strictObject({rows:e.array(_e).max(100),nextCursor:e.uuid().nullable(),clients:e.array(Ht).max(20)}),ke=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),jr=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:ke,runtime:ke,previews:ke})}),kr=e.strictObject({version:_e,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),Rr=e.strictObject({version:_e,upload:ft.nullable()}),_r=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:h,path:e.string(),documentKey:h,documentHash:j,initialStateKey:h,initialRenderKey:h})),renders:e.array(mt)}).loose().superRefine((t,o)=>{(!t.renders||t.routes.some(n=>!t.renders?.some(s=>s.renderKey===n.initialRenderKey&&s.routeKey===n.routeKey&&s.documentKey===n.documentKey&&s.stateKey===n.initialStateKey&&s.documentHash===n.documentHash&&s.entryMode==="hard")))&&o.addIssue({code:"custom",message:"Incomplete render catalog"})}),Kr=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:h,key:h,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),Er=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var Zt=e.strictObject({delaySeconds:e.number().int().min(0).max(86400).optional(),maxPerDay:e.number().int().min(1).max(100).optional(),maxPerSession:e.number().int().min(1).max(100).optional()}),bt=e.strictObject({id:e.uuid(),name:e.string().trim().min(1).max(80),client:G,source:ae,event:e.enum(["screen_enter","button_click"]),cooldownSeconds:e.number().int().min(0).max(2592e3),behavior:e.literal("observe"),delivery:Zt.optional()}).superRefine((t,o)=>{t.event==="button_click"&&(!t.source.nodeId||!t.source.elementKey)&&o.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var D={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},ht="00000000-0000-0000-0000-000000000000";var xt=e.strictObject({type:e.literal("bundle"),paywall:C.optional(),offering:C.optional(),coupons:C,data:C}),Wt=t=>e.strictObject({type:e.literal(t),id:e.uuid()}),Br=e.strictObject({type:e.literal("bundle"),paywallVersionId:e.uuid().optional(),offeringVersionId:e.uuid().optional(),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),data:S});var Mr=e.strictObject({type:e.literal("bundle"),offering:Wt("offering_version").nullable(),paywall:e.strictObject({versionId:e.uuid(),paywallId:e.uuid(),offeringVersionId:e.uuid()}).nullable(),coupons:e.array(Ze).max(20),data:S});var St=e.union([e.string(),e.number().finite(),e.boolean(),e.null()]),Jt=e.union([St,e.array(St).min(1).max(20)]),Qt=e.record(E,Jt).refine(t=>Object.keys(t).length<=10),vt=e.strictObject({path:E,type:e.enum(["string","number","boolean","strings"]),nullable:e.boolean().optional(),aggregation:e.enum(["count","exists"]).optional(),where:Qt.optional()}).superRefine((t,o)=>{(t.aggregation==="count"&&t.type!=="number"||t.aggregation==="exists"&&t.type!=="boolean"||!t.aggregation&&t.where)&&o.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var Xt=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],wt=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Yt=C,It=e.discriminatedUnion("type",[rt,e.strictObject({type:e.literal("claim_offer"),coupon:C}),e.strictObject({type:e.literal("event"),event:wt}),e.strictObject({type:e.literal("api"),operation:e.enum(Xt),inputs:e.record(E,Yt).refine(t=>Object.keys(t).length<=40),outputs:e.record(wt,vt).refine(t=>Object.keys(t).length<=20)})]);var y=Q,en=e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),k={id:y,name:e.string().trim().min(1).max(80),position:e.strictObject({x:e.number().finite(),y:e.number().finite()}).optional()},tn={success:y,cancel:y,unavailable:y,failure:y},nn=e.url().max(2048).refine(t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),rn=e.enum(["same_window","new_window"]),on=e.discriminatedUnion("type",[e.strictObject({...k,type:e.literal("entry"),next:y,triggers:e.array(bt).max(20).refine(t=>new Set(t.map(o=>o.id)).size===t.length,"Entry trigger IDs must be unique").optional()}),e.strictObject({...k,type:e.literal("screen"),screenId:y,presentation:Me,outputs:e.record(y,y),offering:e.discriminatedUnion("source",[e.strictObject({source:e.literal("variable"),key:K}),e.strictObject({source:e.literal("fixed"),versionId:e.uuid()})]).optional()}),e.strictObject({...k,type:e.literal("offering"),configuration:e.discriminatedUnion("source",[e.strictObject({source:e.literal("fixed"),versionId:e.uuid()}),e.strictObject({source:e.literal("feature"),featureKey:e.string().min(1).max(128)})]),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("coupon"),couponId:e.uuid(),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("coupons"),couponIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("output"),value:e.discriminatedUnion("type",[...Oe.options,xt,e.strictObject({type:e.literal("selection"),screenId:y,offeringKey:K})])}),e.strictObject({...k,type:e.literal("condition"),cases:e.array(e.strictObject({condition:qe,target:y})).min(1).max(50),default:y}),e.strictObject({...k,type:e.literal("feature"),featureKey:e.string().min(1).max(128),writes:e.strictObject({value:K}),next:y}),e.strictObject({...k,type:e.literal("split"),experimentId:e.uuid(),applyPageExperiment:e.literal(!0).optional(),routes:e.record(en,y).refine(t=>Object.keys(t).length>=2&&Object.keys(t).length<=20),notParticipating:y}),e.strictObject({...k,type:e.literal("action"),...tn,execution:it,action:It,writes:ye.optional()}),e.strictObject({...k,type:e.literal("external_page"),appManifest:ae.optional(),url:nn,openIn:rn,opened:y,failed:y}),e.strictObject({...k,type:e.literal("end"),outcome:e.enum(["completed","closed","ineligible","failed"]),output:Oe.optional()}),e.strictObject({...k,type:e.literal("wait"),writes:ye.optional(),wait:e.discriminatedUnion("type",[e.strictObject({type:e.literal("duration"),delaySeconds:e.number().int().min(1).max(2592e3),elapsed:y}),e.strictObject({type:e.literal("event"),eventName:y,outputs:ve,timeoutSeconds:e.number().int().min(1).max(2592e3),received:y,timeout:y})])})]),Ke=e.strictObject({version:e.literal(5),entry:y,nodes:e.array(on).min(1).max(D.flowNodes)}),Ee=Ke.superRefine((t,o)=>{an(t,n=>o.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function se(t){switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[t.next];case"screen":return Object.values(t.outputs);case"condition":return[...t.cases.map(o=>o.target),t.default];case"split":return[...Object.values(t.routes),t.notParticipating];case"action":return[t.success,t.cancel,t.unavailable,t.failure];case"external_page":return[t.opened,t.failed];case"end":case"output":return[];case"wait":return t.wait.type==="duration"?[t.wait.elapsed]:[t.wait.received,t.wait.timeout]}}function an(t,o){let n=[],s=new Map(t.nodes.map(p=>[p.id,p])),i=(p,v,N)=>{n.push(p),o?.({message:p,reason:v,path:N?["nodes",t.nodes.indexOf(N)]:[]})};s.size!==t.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(s.get(t.entry)?.type!=="entry"||t.nodes.filter(p=>p.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(t.nodes.filter(p=>p.type==="screen").length>D.pages||t.nodes.filter(p=>!["screen","entry","end","output"].includes(p.type)).length>D.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let p of t.nodes){for(let v of se(p))v===t.entry&&i("An entry cannot be a transition target","entryTarget",p),s.has(v)||i(`Missing target ${v}`,"missingTarget",p);p.type==="screen"&&(a.has(p.screenId)&&i("Every screen has exactly one node owner","screenOwner",p),a.add(p.screenId))}let f=new Set,m=new Set,x=new Set;function _(p){if(f.has(p)){i("Flow edges must not form a cycle","cycle",s.get(p));return}if(!(m.has(p)||!s.has(p))){f.add(p),x.add(p);for(let v of se(s.get(p)))_(v);f.delete(p),m.add(p)}}_(t.entry);for(let p of t.nodes)x.has(p.id)||i("Every node must be reachable from Entry","unreachable",p);return[...new Set(n)]}var De={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Ot(t,o,n){let s=[...o].sort((m,x)=>x.length-m.length),i=new Set,a=(m,x=!1)=>{let _=s.find(p=>m===p||x&&m.startsWith(p+"."));i.add(_??m)};if(t.type==="condition"){let m=n?.startsWith("case_")?Number(n.slice(5)):t.cases.length-1;for(let x of t.cases.slice(0,m+1))for(let _ of q(x.condition))_.startsWith("variables.")&&a(_.slice(10),!0)}if(t.type==="screen"&&t.offering?.source==="variable"&&a(t.offering.key),t.type==="action"&&(t.action.type==="api"||t.action.type==="external_task"))for(let m of Object.values(t.action.inputs))m.source==="variable"&&a(m.key);t.type==="action"&&t.action.type==="claim_offer"&&t.action.coupon.source==="variable"&&a(t.action.coupon.key);let f=t.type==="output"?t.value:t.type==="end"?t.output:null;if(f?.type==="variable"&&a(f.key),f?.type==="bundle")for(let m of[f.paywall,f.offering,f.coupons,f.data])m?.source==="variable"&&a(m.key);return f?.type==="selection"&&a(f.offeringKey),[...i]}var M=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ce=t=>e.record(e.string(),S).refine(o=>F(o)<=t,"Funnel evidence exceeds its byte budget"),xi=e.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Ce=e.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("flag"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("experiment"),id:e.uuid()}),e.strictObject({type:e.literal("saved_group"),id:e.uuid()}),e.strictObject({type:e.literal("config"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("constant"),key:e.string().min(1).max(128)}),e.strictObject({type:e.literal("paywall_version"),id:e.uuid()}),e.strictObject({type:e.literal("offering_version"),id:e.uuid()}),e.strictObject({type:e.literal("reward"),id:e.uuid()})]),Si=e.strictObject({schemaVersion:e.literal(1),kind:Ce,selector:Ne.nullable(),context:ce(131072),contract:e.strictObject({version:e.number().int().positive(),evaluator:e.string().min(1).max(128),policyRevision:e.number().int().nonnegative()})}).refine(t=>F(t)<=131072,"Node input exceeds its byte budget"),vi=e.strictObject({schemaVersion:e.literal(1),kind:Ce,outcome:e.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ce(131072),route:e.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ce(131072)}).refine(t=>F(t)<=131072,"Node result exceeds its byte budget"),wi=e.strictObject({schemaVersion:e.literal(1),operations:e.record(M,e.strictObject({attempts:e.number().int().nonnegative(),maxAttempts:e.number().int().min(1).max(5),deadlineAt:e.iso.datetime({offset:!0}),retryAt:e.iso.datetime({offset:!0}).nullable(),error:e.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:e.strictObject({type:M,id:e.uuid()}).nullable()}))}).refine(t=>F(t)<=65536,"Execution state exceeds its byte budget"),P={receiptId:e.uuid()},Ae=e.iso.datetime({offset:!0}),Ii=e.discriminatedUnion("type",[e.strictObject({type:e.literal("node_entered"),details:e.strictObject({kind:Ce})}),e.strictObject({type:e.literal("presentation_shown"),details:e.strictObject({...P,source:e.literal("client"),occurredAt:Ae.optional()})}),e.strictObject({type:e.literal("decision_accepted"),details:e.strictObject(P)}),e.strictObject({type:e.literal("signal_received"),details:e.strictObject({signalId:e.uuid(),nodeId:M,eventName:M,data:ce(8192),source:e.literal("server"),occurredAt:Ae})}),e.strictObject({type:e.literal("signal_consumed"),details:e.strictObject({...P,signalId:e.uuid()})}),e.strictObject({type:e.literal("wait_elapsed"),details:e.strictObject(P)}),e.strictObject({type:e.literal("wait_timeout"),details:e.strictObject(P)}),e.strictObject({type:e.literal("operation_completed"),details:e.strictObject({...P,operation:M,reference:e.strictObject({type:M,id:e.uuid()}).nullable()})}),e.strictObject({type:e.literal("execution_recovered"),details:e.strictObject({generation:e.number().int().positive(),reason:e.enum(["interrupted","expired_lease","delivery_failed"])})}),e.strictObject({type:e.literal("execution_failed"),details:e.strictObject({generation:e.number().int().positive(),code:e.string().regex(/^[a-z_]{1,64}$/)})}),e.strictObject({type:e.literal("run_completed"),details:e.strictObject({outcome:e.enum(["completed","ineligible","failed"])})}),e.strictObject({type:e.literal("run_closed"),details:e.strictObject({source:e.enum(["client","server","expiry"])})}),e.strictObject({type:e.literal("treatment_used"),details:e.strictObject({...P,source:e.enum(["client","server"]),occurredAt:Ae,reference:e.string().min(1).max(128).optional()})})]);var R=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sn=e.discriminatedUnion("type",[e.strictObject({id:R,type:e.literal("owned"),publicData:Ye.optional(),document:H.refine(t=>["page","popup","onboarding"].includes(t.surface)&&t.pages.length===1&&t.actions.every(o=>o.type==="event"&&!o.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),e.strictObject({id:R,type:e.literal("paywall"),paywallVersionId:e.uuid()})]),ze={executionContract:et.optional(),kind:e.literal("funnel"),schemaVersion:e.literal(4),screens:e.array(sn).max(D.pages),references:e.record(R,Ne).refine(t=>Object.keys(t).length<=500),inputs:e.array(e.strictObject({variable:R,screenId:R,componentId:R,required:e.boolean()})).max(D.questions),variables:e.record(K,ge).refine(t=>Object.keys(t).length<=D.logicNodes),outputSchema:fe,execution:e.strictObject({runTimeoutSeconds:e.number().int().min(1).max(De.runTimeoutSeconds),maxTransitions:e.number().int().min(1).max(De.maxTransitions)})},$i=e.strictObject({...ze,graph:Ke});function cn(t,o){let n=!1,s=(i,a)=>{let f=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(t.strings.locales).some(m=>m[i.text]?.includes("{{offer."))&&!(f&&o(f))&&(n=!0),i.type==="stack"&&i.children.forEach(m=>s(m,f))};for(let i of t.pages)s(i.root);return n}function le(t){return Array.isArray(t)?t.some(le):!t||typeof t!="object"?!1:Object.entries(t).some(([o,n])=>o==="productVersionId"?n===ht:le(n))}function un(t){let o=[],n=new Set(Object.values(t.references).flatMap(s=>s.type==="reward"?[s.id]:[]));for(let[s,i]of t.screens.entries()){if(i.type!=="owned")continue;let a;try{a=dt(i.document)}catch(f){o.push({message:f instanceof Error?f.message:"Screen cannot be delivered",reason:"screen",path:["screens",s,"document"]});continue}for(let[f,m]of t.inputs.entries())m.screenId===i.id&&!me(a,m.componentId)&&o.push({message:`Local Funnel input ${m.variable} targets hidden component ${m.componentId} on screen ${m.screenId}`,reason:"inputBinding",path:["inputs",f]})}for(let[s,i]of t.graph.nodes.entries()){let a=["graph","nodes",s],f=i.type==="screen"?t.screens.find(m=>m.id===i.screenId):void 0;f?.type==="owned"&&(f.document.actions.some(m=>typeof m.properties.templateKey=="string"&&m.properties.templateKey.startsWith("popup-coupon-"))&&o.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),cn(f.document,m=>n.has(m))&&o.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&le(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&le(i.output.value))&&o.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return o}function jt(t,o){for(let{message:n,reason:s,path:i}of un(t))o.addIssue({code:"custom",message:n,path:i,params:{reason:s}})}function kt(t,o){let n=(d,r,c=[])=>o.addIssue({code:"custom",message:d,path:c,params:{reason:r}}),s=Object.values(t.references),i=new Map(t.screens.map(d=>[d.id,d])),a=(d,r)=>s.some(c=>c.type===d&&("id"in c?c.id:c.key)===r);i.size!==t.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let f=t.graph.nodes.filter(d=>d.type==="screen");(f.length!==i.size||f.some(d=>!i.has(d.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let m=new Map,x=Object.keys(t.variables);x.some(d=>x.some(r=>d!==r&&r.startsWith(d+".")))&&n("Variable paths must not overlap","variable");function _(d,r){Object.hasOwn(t.variables,d)||n("Every produced variable needs a declaration","variable",["graph","nodes",t.graph.nodes.indexOf(r)]);let c=m.get(d)??new Set;c.add(r.id),m.set(d,c)}for(let[d,r]of t.graph.nodes.entries()){let c=["graph","nodes",d],w=r.type==="feature"?r.featureKey:r.type==="offering"&&r.configuration.source==="feature"?r.configuration.featureKey:r.type==="output"&&r.value.type==="feature"?r.value.featureKey:r.type==="end"&&r.output?.type==="feature"?r.output.featureKey:null;w&&!a("flag",w)&&n("Flag selectors require an explicit GB resource reference","feature",c);let I=r.type==="feature"||r.type==="offering"||r.type==="coupon"||r.type==="coupons"||r.type==="action"&&r.action.type==="api"?["value"]:r.type==="action"&&r.action.type==="external_task"?Object.keys(r.action.outputs):r.type==="wait"&&r.wait.type==="event"?Object.keys(r.wait.outputs):[],O="writes"in r?r.writes??{}:{};(I.length!==Object.keys(O).length||I.some(u=>!Object.hasOwn(O,u))||new Set(Object.values(O)).size!==Object.values(O).length)&&n("Node writes must map every named output exactly once","variable",c);for(let[u,b]of Object.entries(O)){_(b,r);let g=t.variables[b],l=r.type==="offering"?"offering_version":r.type==="coupon"?"reward":r.type==="action"&&r.action.type==="api"?"json":r.type==="action"&&r.action.type==="external_task"?r.action.outputs[u]:r.type==="wait"&&r.wait.type==="event"?r.wait.outputs[u]:void 0;(g?.source.type!=="node"||l&&g.type!==l)&&n("Node writer source or output type does not match declaration","variable",c)}if(r.type==="coupons"){let u=t.variables[r.writes.value];(u?.type!=="array"||u.items?.type!=="reward"||u.items.nullable||u.nullable)&&n("Coupons output requires a non-null Reward array","variable",c);for(let b of r.couponIds)a("reward",b)||n("Coupons require Reward references","coupon",c)}if(r.type==="split"&&!a("experiment",r.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",c),r.type==="coupon"&&!a("reward",r.couponId)&&n("Coupon selectors require a Reward reference","coupon",c),r.type==="action"&&r.action.type==="claim_offer"&&r.action.coupon.source==="literal"){let u=r.action.coupon.value;(!u||typeof u!="object"||Array.isArray(u)||u.type!=="reward"||typeof u.id!="string"||Object.keys(u).length!==2||!a("reward",u.id))&&n("Coupon claims require a Reward reference","coupon",c)}if(r.type==="offering"&&r.configuration.source==="fixed"&&!a("offering_version",r.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",c),r.type==="screen"&&r.offering?.source==="variable"&&t.variables[r.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",c),r.type==="action"&&r.action.type==="claim_offer"&&r.action.coupon.source==="variable"&&(t.variables[r.action.coupon.key]?.type!=="reward"||r.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",c),r.type==="screen"){let u=i.get(r.screenId);if(r.offering?.source==="fixed"&&!a("offering_version",r.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",c),u?.type==="paywall"&&r.offering&&n("Paywall owns its fixed Offering Version","offering",c),u?.type==="paywall"&&!a("paywall_version",u.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",c),u?.type==="owned"){let b=u.document.pages[0];if(!b){n("Owned screen requires a page","screen",c);continue}Te(u.document).some(l=>!l.complete)&&n("Owned screens require complete local content","translations",c);let g=new Set(u.document.actions.map(l=>l.id));(g.size!==Object.keys(r.outputs).length||Object.keys(r.outputs).some(l=>!g.has(l)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",c),Z(b.root,l=>{!r.offering&&(l.type==="plan_picker"||(l.type==="stack"||l.type==="button")&&l.bind?.plan||l.type==="customer_data"&&["customer_plans","credit_packs"].includes(l.data.source))&&n("Product presentation requires an Offering Version","offering",c),l.type==="customer_data"&&Object.values(l.data.outputs??{}).some(z=>z!==void 0&&!g.has(z))&&n("Customer components require declared screen outcomes","componentOutput",c)})}}r.type==="end"&&["completed","ineligible"].includes(r.outcome)&&!r.output&&n("Completed and ineligible ends require a declared output","output",c),r.type==="end"&&r.output?.type==="literal"&&!T(t.outputSchema,r.output.value)&&n("Terminal output does not match outputSchema","output",c),r.type==="output"&&r.value.type==="literal"&&!T(t.outputSchema,r.value.value)&&n("Terminal output does not match outputSchema","output",c);let A=r.type==="output"?r.value:r.type==="end"?r.output:void 0;if(A?.type==="variable"&&!A.path){let u=t.variables[A.key];u&&!$e(u,t.outputSchema)&&n("Variable output does not match outputSchema","output",c)}if(r.type==="screen"){let u=i.get(r.screenId);if(u?.type==="owned")for(let b of xe(u.document))(/^(input|params)\./.test(b)||b.startsWith("variables.")&&!he(b.slice(10),x))&&n("Screen values must reference registered variables","variable",c)}if(r.type==="condition")for(let u of r.cases){for(let b of Ge(u.condition))a("saved_group",b)||n("Conditions require explicit Saved Group references","savedGroup",c);for(let b of q(u.condition))b.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",c)}if(r.type==="output"&&r.value.type==="bundle"){t.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",c);for(let[u,b]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let g=r.value[u];if(g)if(g.source==="literal"){let l=u==="coupons"?g.value:[g.value];(!Array.isArray(l)||l.length>20||l.some(z=>!T({type:b,nullable:!1},z)||!a(b,z.id))||u==="coupons"&&new Set(l.map(z=>z.id)).size!==l.length)&&n("Bundle requires distinct scoped resource references",u==="coupons"?"coupon":u==="paywall"?"paywall":"offering",[...c,"value",u])}else{let l=t.variables[g.key];(g.path||!l||l.nullable||(u==="coupons"?l.type!=="array"||l.items?.type!=="reward"||l.items.nullable:l.type!==b))&&n("Bundle binding type does not match its slot","output",c)}}}}for(let[d,r]of t.graph.nodes.entries()){let c=r.type==="screen"?i.get(r.screenId):void 0,w=[...Ot(r,x),...c?.type==="owned"?Xe(c.document).map(I=>he(I,x)?.key??I):[]];for(let I of new Set(w)){let b=function(g){if(g===r.id)return!0;if(u.has(g))return!1;u.add(g);let l=t.graph.nodes.find(Rt=>Rt.id===g);return l?(A.has(g)?l.type==="action"?[l.cancel,l.unavailable,l.failure]:l.type==="wait"&&l.wait.type==="event"?[l.wait.timeout]:[]:se(l)).some(b):!1};var N=b;if(!Object.hasOwn(t.variables,I)){n("Consumed variable is undeclared","variable",["graph","nodes",d]);continue}let O=t.variables[I];if(r.type==="screen"&&O.source.type==="input"&&t.inputs.some(g=>g.screenId===r.screenId&&g.variable===I)||O.source.type==="parameter"||O.source.type==="attribute")continue;let A=O.source.type==="input"?new Set(t.inputs.filter(g=>g.variable===I&&g.required).flatMap(g=>f.filter(l=>l.screenId===g.screenId).map(l=>l.id))):m.get(I)??new Set,u=new Set;(!A.size||b(t.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",d])}}(new Set(t.inputs.map(d=>d.variable)).size!==t.inputs.length||new Set(t.inputs.map(d=>`${d.screenId}:${d.componentId}`)).size!==t.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[d,r]of t.inputs.entries()){t.variables[r.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",d]);let c=i.get(r.screenId),w=c?.type==="owned"?me(c.document,r.componentId):null;if((w?.type!=="stack"||!w.interaction||!["input","toggle","select","multiselect","tabs"].includes(w.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",d]),w?.type==="stack"&&w.interaction){let I=w.interaction.type==="toggle"?"boolean":w.interaction.type==="multiselect"?"strings":"string";t.variables[r.variable]?.type!==I&&n("Input variable type does not match component","inputBinding",["inputs",d]);let O=t.variables[r.variable]?.enum;O&&!w.children.filter(A=>!A.hidden).every(A=>O.includes(A.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",d])}}for(let[d,r]of Object.entries(t.variables))r.enum&&r.type!=="string"&&n("Only string variables support enum","variable",["variables",d]),r.source.type==="input"&&!t.inputs.some(c=>c.variable===d)&&n("Input variable requires a component binding","inputBinding",["variables",d]);let p=0,v=0;for(let d of t.screens)if(d.type==="owned"){for(let r of d.document.pages)Z(r.root,()=>{p++});v+=d.document.actions.length}(p>D.components||v>D.actions||F(t)>D.documentBytes)&&n("Funnel document exceeds its budget","budget")}var ln=e.strictObject({...ze,graph:Ee}).superRefine(kt),pn=e.strictObject({...ze,graph:Ee,displayName:e.string().trim().min(1).max(80)}).superRefine(kt),Li=pn.superRefine(jt),Hi=ln.superRefine(jt),ue=e.string().regex(Fe),$={requestId:e.uuid(),nodeId:R,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),customerToken:ue.optional()},dn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("screen"),output:R,answers:J,selection:e.record(R,e.union([e.string().max(200),e.boolean(),e.number().int().min(0).max(1e4)])).optional()}),e.strictObject({type:e.literal("paywall_quote"),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),actionId:R,productVersionId:e.uuid(),offerId:e.uuid().optional(),nativeOffer:He.optional(),subscriptionChange:We.optional(),predecessor:e.strictObject({operationId:e.uuid().nullable(),generation:e.number().int().positive()}).optional()}),e.strictObject({type:e.literal("paywall_confirm"),operationId:e.uuid(),merchantConfirmation:Pe.optional()}),e.strictObject({type:e.literal("paywall_cancel"),operationId:e.uuid()}),e.strictObject({type:e.literal("client_action"),receiptId:e.uuid(),outcome:e.enum(["success","cancel","failure","opened","failed"])})]),mn=e.object({nodeId:R,visit:e.number().int().nonnegative(),revision:e.number().int().nonnegative(),components:e.record(R,e.object({resourceKey:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:e.number().int().min(1).max(1e5),after:Je.nullable(),filter:e.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(t=>Object.keys(t).length<=150)}).strict(),Zi=e.discriminatedUnion("operation",[e.strictObject({operation:e.literal("start"),funnelId:e.uuid(),requestId:e.uuid(),customer:ne.optional(),customerData:re.optional(),locale:e.string().min(1).max(35),parameters:B}).refine(ie,oe),e.strictObject({operation:e.literal("get"),settlementRequestId:e.uuid().optional(),data:mn.optional(),purchase:e.strictObject({receiptId:e.uuid(),operationId:e.uuid()}).optional(),customerToken:ue.optional()}),e.strictObject({operation:e.literal("resume"),requestId:e.uuid(),customerToken:ue.optional()}),e.strictObject({operation:e.literal("submit"),...$,input:dn}),e.strictObject({operation:e.literal("back"),...$}),e.strictObject({operation:e.literal("shown"),...$}),e.strictObject({operation:e.literal("close"),...$}),e.strictObject({operation:e.literal("commit_segment"),...$,policyRevision:e.number().int().nonnegative(),generation:e.string().min(1).max(256)}),e.strictObject({operation:e.literal("review"),receiptId:e.uuid().optional(),customerToken:ue.optional()})]);export{_t as a,Xe as b,F as c,Kt as d,Kn as e,Mt as f,gr as g,wr as h,Zt as i,Vn as j,Un as k,Bn as l,Vt as m,Ct as n,Nt as o,Gn as p,ne as q,re as r,ie as s,oe as t,at as u,$n as v,Pt as w,Ln as x,Hn as y,Zn as z,Oe as A,Bt as B,cr as C,ur as D,lr as E,nn as F,rn as G,Si as H,vi as I,pn as J,Zi as K};
@@ -1 +1 @@
1
- import{d as b}from"./chunk-7OJIW75D.js";import{b as r}from"./chunk-YLH3AYCK.js";var f=r.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),y=r.strictObject({type:r.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:r.boolean(),enum:r.array(r.string().max(255)).min(1).max(100).optional()}),g=y.extend({type:r.enum([...y.shape.type.options,"array"]),items:y.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),h=g.safeExtend({source:r.discriminatedUnion("type",[r.strictObject({type:r.literal("input")}),r.strictObject({type:r.literal("node")}),r.strictObject({type:r.enum(["parameter","attribute"]),key:f})])}),O=r.record(f,h),R=r.record(f,f).refine(e=>Object.keys(e).length<=20);function m(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>m(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&r.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function w(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&w(e.items,t.items)}function d(e,t){let n={};for(let[s,a]of Object.entries(e)){let i=a.source,l=i.type==="input"?t.answers:i.type==="node"?t.results??{}:i.type==="parameter"?t.parameters:t.attributes,c=i.type==="parameter"||i.type==="attribute"?i.key:s,u=Object.hasOwn(l,c),o=l[c];if(i.type==="attribute"&&c.includes(".")&&(!u||c.startsWith("merchandise."))){o=l,u=!0;for(let p of c.split(".")){if(!o||typeof o!="object"||!Object.hasOwn(o,p)||Array.isArray(o)&&(!/^(0|[1-9]\d*)$/.test(p)||Number(p)>=o.length)){u=!1;break}o=o[p]}}if(!(!u||o===void 0)){if(!m(a,o))throw new Error(`Invalid variable value: ${s}`);n[s]=o}}return n}function J(e,t){let n={};for(let[s,a]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,s))throw new Error(`Node output is missing: ${s}`);if(Object.hasOwn(n,a))throw new Error("Node outputs cannot overwrite one another");n[a]=t[s]}return n}function A(e,t,n){let s=new Set(Object.values(t.writes??{}));for(let[a,i]of Object.entries(n))if(!s.has(a)||e[a]?.source.type!=="node"||!m(e[a],i))throw new Error(`Invalid node variable write: ${a}`);if(s.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var k=b,V=["parameters","answers","results","variables"];function j(e){return V.some(t=>e===t||e.startsWith(t+"."))}function z(e){let t={};for(let[s,a]of Object.entries(d(e.declarations,e))){let i=s.split(".");if(i.some(u=>["__proto__","constructor","prototype"].includes(u)))throw new Error("Reserved result path");let l=t;for(let u of i.slice(0,-1)){Object.hasOwn(l,u)||(l[u]={});let o=l[u];if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Ambiguous result path");l=o}let c=i.at(-1);if(c===void 0)throw new Error("Empty result path");l[c]=a}return{...Object.fromEntries(Object.entries(e.attributes).filter(([s])=>!j(s))),variables:t}}var N=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);export{f as a,g as b,h as c,R as d,m as e,w as f,d as g,J as h,A as i,k as j,j as k,z as l,N as m};
1
+ import{d as b}from"./chunk-LUVTP4VU.js";import{b as r}from"./chunk-S7NHVERO.js";var f=r.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),y=r.strictObject({type:r.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:r.boolean(),enum:r.array(r.string().max(255)).min(1).max(100).optional()}),g=y.extend({type:r.enum([...y.shape.type.options,"array"]),items:y.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),h=g.safeExtend({source:r.discriminatedUnion("type",[r.strictObject({type:r.literal("input")}),r.strictObject({type:r.literal("node")}),r.strictObject({type:r.enum(["parameter","attribute"]),key:f})])}),O=r.record(f,h),R=r.record(f,f).refine(e=>Object.keys(e).length<=20);function m(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>m(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&r.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function w(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&w(e.items,t.items)}function d(e,t){let n={};for(let[s,a]of Object.entries(e)){let i=a.source,l=i.type==="input"?t.answers:i.type==="node"?t.results??{}:i.type==="parameter"?t.parameters:t.attributes,c=i.type==="parameter"||i.type==="attribute"?i.key:s,u=Object.hasOwn(l,c),o=l[c];if(i.type==="attribute"&&c.includes(".")&&(!u||c.startsWith("merchandise."))){o=l,u=!0;for(let p of c.split(".")){if(!o||typeof o!="object"||!Object.hasOwn(o,p)||Array.isArray(o)&&(!/^(0|[1-9]\d*)$/.test(p)||Number(p)>=o.length)){u=!1;break}o=o[p]}}if(!(!u||o===void 0)){if(!m(a,o))throw new Error(`Invalid variable value: ${s}`);n[s]=o}}return n}function J(e,t){let n={};for(let[s,a]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,s))throw new Error(`Node output is missing: ${s}`);if(Object.hasOwn(n,a))throw new Error("Node outputs cannot overwrite one another");n[a]=t[s]}return n}function A(e,t,n){let s=new Set(Object.values(t.writes??{}));for(let[a,i]of Object.entries(n))if(!s.has(a)||e[a]?.source.type!=="node"||!m(e[a],i))throw new Error(`Invalid node variable write: ${a}`);if(s.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var k=b,V=["parameters","answers","results","variables"];function j(e){return V.some(t=>e===t||e.startsWith(t+"."))}function z(e){let t={};for(let[s,a]of Object.entries(d(e.declarations,e))){let i=s.split(".");if(i.some(u=>["__proto__","constructor","prototype"].includes(u)))throw new Error("Reserved result path");let l=t;for(let u of i.slice(0,-1)){Object.hasOwn(l,u)||(l[u]={});let o=l[u];if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Ambiguous result path");l=o}let c=i.at(-1);if(c===void 0)throw new Error("Empty result path");l[c]=a}return{...Object.fromEntries(Object.entries(e.attributes).filter(([s])=>!j(s))),variables:t}}var N=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);export{f as a,g as b,h as c,R as d,m as e,w as f,d as g,J as h,A as i,k as j,j as k,z as l,N as m};
@@ -1 +1 @@
1
- import{c as $}from"./chunk-7OJIW75D.js";import{a as z}from"./chunk-DSPLGTQI.js";var G={sm:420,md:640,lg:900},F=767;function Pe(e,t,r=()=>!0,a="Close"){let n=e.ownerDocument.defaultView,o=e.ownerDocument.createElement("button");o.type="button",o.setAttribute("aria-label",a),o.style.cssText="position:absolute;inset:0 48px auto;z-index:2;height:24px;border:0;padding:0;background:transparent;touch-action:none;cursor:grab";let d=e.ownerDocument.createElement("span");d.style.cssText="display:block;width:36px;height:4px;border-radius:4px;margin:8px auto 12px;background:currentColor;opacity:.22;pointer-events:none",o.append(d),e.prepend(o);let l,c=0,s=!1,p=()=>{o.hidden=e.dataset.presentation!=="sheet",o.setAttribute("aria-disabled",String(!r()))},b=i=>{p(),!(o.hidden||!r()||i.button!==0)&&(l={y:i.clientY,time:Date.now(),id:i.pointerId},c=0,s=!1,o.setPointerCapture?.(i.pointerId))},x=i=>{!l||i.pointerId!==l.id||(c=Math.max(0,i.clientY-l.y),e.style.transform=`translateY(${c}px)`)},v=i=>{if(!l||i.pointerId!==l.id)return;let g=Math.max(1,Date.now()-l.time),P=i.type!=="pointercancel"&&r()&&(c>120||c>40&&c/g>.5);s=c>6,l=void 0,o.releasePointerCapture?.(i.pointerId),e.style.transform="",P?t():c&&typeof e.animate=="function"&&!n?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&e.animate([{transform:`translateY(${c}px)`},{transform:"none"}],{duration:200,easing:"cubic-bezier(.2,.8,.2,1)"}),c=0},m=()=>{if(s){s=!1;return}!l&&c===0&&r()&&t()};o.addEventListener("pointerdown",b),o.addEventListener("pointermove",x),o.addEventListener("pointerup",v),o.addEventListener("pointercancel",v),o.addEventListener("click",m);let L=typeof MutationObserver=="function"?new MutationObserver(p):void 0;return L?.observe(e,{attributes:!0,attributeFilter:["data-presentation"]}),n?.addEventListener("resize",p),p(),()=>{L?.disconnect(),n?.removeEventListener("resize",p),o.remove(),e.style.transform=""}}function q(e,t,r=!1){return(e.type==="modal"||e.type==="sheet")&&e.mobile&&r&&t<=F?e.mobile:e.type}function j(e,t,r){let a=e.ownerDocument.defaultView,n=t.presentation,o;if((n.type==="modal"||n.type==="sheet")&&n.backdrop){let i=`lp-backdrop-${crypto.randomUUID()}`,g={none:"transparent",scrim:"#f2f2f2cc",dim:"#0006","strong-dim":"#000000bf",blur:"#0006"};e.dataset.indianaBackdrop=i,o=e.ownerDocument.createElement("style"),o.textContent=`dialog[data-indiana-backdrop="${i}"]::backdrop{background:${g[n.backdrop]};backdrop-filter:${n.backdrop==="blur"?"blur(16px)":"none"}}`,e.append(o)}let d=t.pages?.[0]?.root.style?.shape,l=d?.type==="pill"?"9999px":d?.type==="rect"?typeof d.radius=="number"?`${d.radius}px`:[d.radius.topLeft,d.radius.topRight,d.radius.bottomRight,d.radius.bottomLeft].map(i=>`${i}px`).join(" "):void 0,c=(n.type==="modal"||n.type==="sheet")&&(n.desktopWidth!==void 0||n.mobile!==void 0||n.type==="modal"&&n.position!==void 0),s=n.type,p,b,x=!1,v=i=>{x||!Number.isFinite(i)||i<0||(b=i,s!=="fullscreen"&&s!=="inline"&&(e.style.height=`min(${Math.max(i,40)}px, calc(100dvh - ${s==="sheet"?0:32}px))`))},m=()=>{if(!x&&(s=p??q(n,a?.innerWidth??1024,a?.matchMedia?.("(pointer: coarse)").matches===!0),e.dataset.presentation=s,!(!c||n.type!=="modal"&&n.type!=="sheet"))){if(e.style.boxSizing="border-box",e.style.padding="0",e.style.border="0",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=-1,e.style.background=t.theme.background,e.style.color=t.theme.text,s==="fullscreen")e.style.width="100vw",e.style.height="100dvh",e.style.maxWidth="100vw",e.style.maxHeight="100dvh",e.style.margin="0",e.style.borderRadius="0";else{let i=n.mobile==="sheet"&&s==="sheet",g=n.desktopWidth,P=a?.innerWidth??1024;e.style.width=i?`${P}px`:g?`${Math.min(g.max,Math.max(P*g.viewport/100,g.min))}px`:`${$[n.size]}px`,e.style.maxWidth=`${Math.max(0,P-(s==="sheet"?0:32))}px`,e.style.maxHeight=s==="sheet"?"100dvh":"calc(100dvh - 32px)",e.style.margin=s==="sheet"?"auto auto 0":n.type==="modal"&&n.position==="top"?"16px auto auto":n.type==="modal"&&n.position==="bottom"?"auto auto 16px":"auto",e.style.borderRadius=l??(s==="sheet"?"16px 16px 0 0":"24px"),e.style.height="",b!==void 0&&v(b)}r?.(s)}},L=c?[a?.matchMedia?.(`(max-width: ${F}px)`),a?.matchMedia?.("(pointer: coarse)")].filter(i=>i!==void 0):[];if(c){a?.addEventListener("resize",m);for(let i of L)i.addEventListener?i.addEventListener("change",m):i.addListener?.(m)}return m(),{responsive:c,get type(){return s},latch(){x||p!==void 0||(m(),p=s)},setContentHeight:v,destroy(){if(!x){x=!0,o?.remove(),delete e.dataset.indianaBackdrop,a?.removeEventListener("resize",m);for(let i of L)i.removeEventListener?i.removeEventListener("change",m):i.removeListener?.(m)}}}}function Se(e,t,r){let{presentation:a}=t,n="size"in a?`${G[a.size]}px`:"100vw";return e.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${n}`,j(e,t,r)}function Le(e,t,r=!1){let a=e.ownerDocument.defaultView;if(typeof e.animate!="function"||a?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let n=r?{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}:{duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};e.animate(t==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:t==="modal"?[{opacity:0,transform:r?"translateY(12px) scale(0.96)":"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],n);try{e.animate([{opacity:0},{opacity:1}],{...n,pseudoElement:"::backdrop"})}catch{}}function V(e,t){e.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0","border-radius:50%","font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";"),e.style.background=`radial-gradient(circle, ${t.background} 0 15px, color-mix(in srgb, ${t.text} 22%, ${t.background}) 15px 16px, transparent 16.5px)`,e.style.color=t.text}function De(e){let t=e.closest("dialog");if(!t?.open||!t.isConnected)return;let r=["style","tabindex","aria-label","data-presentation","data-indiana-backdrop"].map(a=>[a,t.getAttribute(a)]);return{dialog:t,content:e,release(){for(let[a,n]of r)n===null?t.removeAttribute(a):t.setAttribute(a,n)}}}var O=new WeakMap;function ke(e,t){return O.set(e,t),()=>O.delete(e)}function B(e){let t=e.defaultView?.HTMLElement,r=e.activeElement;for(let n=0;n<16&&r?.shadowRoot?.activeElement;n++)r=r.shadowRoot.activeElement;let a=r?O.get(r)?.():void 0;return()=>{!r?.isConnected||!t||!(r instanceof t)||(r.focus({preventScroll:!0}),a?.())}}var Ie=15e3;function Ae(e,t,r,a,n){let o=e.ownerDocument,d=new AbortController,l=!1,c=!1,s,p,b,x,v,m;function L(){clearTimeout(m),m=void 0,b?.(),b=void 0,s?.tagName==="DIALOG"&&s.close?.(),s?.remove(),s=void 0,p=void 0,v=void 0}function i(u,w){c||(c=!0,L(),(u==="dismissed"||u==="error")&&d.abort(w??new DOMException("Presentation cancelled","AbortError")),!(!l&&u!=="ready")&&z(t.onPresentationState,u==="error"?{surface:r,state:u,error:w}:{surface:r,state:u}))}let g=a,P=()=>{c||g()};return{setDismissHandler(u){g=u},get active(){return l&&!c},get cancelled(){return d.signal.aborted},retainPurchaseDialog(){return p?.()},setPurchaseRecovery(u,w){x={message:u,retry:w},v?.()},start(u,w,y){if(l||c)return;l=!0;let C=()=>{if(!c&&t.loading!=="host"){let k=(w??o.documentElement.lang)||"en",M=u&&y?.presentation?.type!=="inline",D=y!==void 0,h=o.createElement(M?"dialog":"div");s=h,h.dataset.longplayLoading=r;let R=k.startsWith("zh"),W=D?R?"正在加载套餐":"Loading plans":R?"正在加载":"Loading",N=y?.screen.theme??{background:"Canvas",text:"CanvasText"};h.setAttribute("aria-label",W);let S=o.createElement("div");S.setAttribute("role","status");let H=o.createElement("div");H.setAttribute("aria-hidden","true"),D?(S.style.cssText="padding:calc(24px + env(safe-area-inset-top, 0px)) 24px 16px;padding-inline-end:68px;font:650 20px/1.3 system-ui,sans-serif;letter-spacing:-.015em",y||(S.style.paddingBlockEnd="24px")):S.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)",S.textContent=W;let T=o.createElement("button");T.type="button",T.textContent=R?"重试":"Retry",T.style.cssText="margin:0 24px 20px;padding:8px 16px",T.onclick=()=>x?.retry?.(),v=()=>{x&&(S.textContent=x.message,x.retry?S.after(T):T.remove())};let E=o.createElement("button");E.type="button",E.textContent="×",E.setAttribute("aria-label",R?"取消加载":"Cancel loading"),V(E,N),D&&(E.style.borderRadius="50%",E.style.top="calc(15px + env(safe-area-inset-top, 0px))",E.style.insetInlineEnd="calc(15px + env(safe-area-inset-right, 0px))"),E.addEventListener("click",P);let _=f=>{f.preventDefault(),P()};h.addEventListener("cancel",_);let I=o.createElement("style");I.textContent="[data-longplay-loading] > button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}",h.append(S,H,E,I),v(),e.append(h);let A=()=>{if(!c&&M){let f=h,Y=B(o);f.showModal?f.showModal():f.open=!0,E.focus({preventScroll:!0}),p=()=>{if(!f.open||!f.isConnected)return;let U=b;return b=void 0,s=void 0,p=void 0,delete f.dataset.longplayLoading,f.removeAttribute("aria-label"),f.style.padding="0",f.removeEventListener("cancel",_),S.remove(),H.remove(),E.remove(),I.remove(),T.remove(),v=void 0,{dialog:f,release(){U?.(),f.close?.(),f.remove(),Y()}}}}};y&&n?(b=n(h,H,y),A()):D?(h.style.cssText=M?"padding:0;border:0;border-radius:24px;background:Canvas;color:CanvasText;width:min(420px,calc(100vw - 32px))":"position:relative;background:Canvas;color:CanvasText;width:100%",A()):(X(h,H,M,r),A())}};y!==void 0&&t.loading!=="host"?m=setTimeout(C,120):C(),z(t.onPresentationState,{surface:r,state:"loading",dismiss:P})},present(u){if(c)return;let w=!!s;L(),u(w),i("ready")},dismiss:P,finish:i,async wait(u,w){let y=d.signal,C,k,M=new Promise((D,h)=>{k=()=>h(y.reason),y.aborted?k():y.addEventListener("abort",k,{once:!0}),w!==void 0&&(C=setTimeout(()=>h(new Error("Presentation data timed out")),w))});try{let D=await Promise.race([M,u]);return y.throwIfAborted(),D}finally{y.removeEventListener("abort",k),clearTimeout(C)}}}}function X(e,t,r,a){e.style.cssText="position:relative;box-sizing:border-box;background:Canvas;color:CanvasText;padding:24px 48px 24px 24px;"+(r?"position:fixed;width:min(480px,calc(100% - 32px));border:0;border-radius:16px;max-height:calc(100dvh - 32px)":"width:100%"),t.style.cssText="display:grid;gap:12px";let n=a==="banner"?[["72%",12],["44%",10]]:[["46%",20],["84%",12],["65%",12],["100%",64]];for(let[o,d]of n){let l=e.ownerDocument.createElement("div");l.style.cssText=`width:${o};height:${d}px;background:currentColor;opacity:.11;border-radius:6px`,t.append(l)}}function J(e){let t={display:"block",position:"fixed",top:"0",left:"0",opacity:"0",pointerEvents:"none",zIndex:"-1"},r=Object.keys(t).map(o=>{let d=o,l=e.style[d];return e.style[d]=t[d],[d,l]}),a=e.inert??!1,n=e.getAttribute("aria-hidden");return e.inert=!0,e.setAttribute("aria-hidden","true"),()=>{for(let[o,d]of r)e.style[o]=d;e.inert=a,n===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n)}}function ze(e,t){let r=e.style.width;e.style.width=`${t.getBoundingClientRect().width||t.ownerDocument.defaultView?.innerWidth||800}px`;let a=J(e);return()=>{a(),e.style.width=r}}export{Pe as a,q as b,j as c,Se as d,Le as e,V as f,De as g,ke as h,B as i,Ie as j,Ae as k,J as l,ze as m};
1
+ import{c as $}from"./chunk-LUVTP4VU.js";import{a as z}from"./chunk-DSPLGTQI.js";var G={sm:420,md:640,lg:900},F=767;function Pe(e,t,r=()=>!0,a="Close"){let n=e.ownerDocument.defaultView,o=e.ownerDocument.createElement("button");o.type="button",o.setAttribute("aria-label",a),o.style.cssText="position:absolute;inset:0 48px auto;z-index:2;height:24px;border:0;padding:0;background:transparent;touch-action:none;cursor:grab";let d=e.ownerDocument.createElement("span");d.style.cssText="display:block;width:36px;height:4px;border-radius:4px;margin:8px auto 12px;background:currentColor;opacity:.22;pointer-events:none",o.append(d),e.prepend(o);let l,c=0,s=!1,p=()=>{o.hidden=e.dataset.presentation!=="sheet",o.setAttribute("aria-disabled",String(!r()))},b=i=>{p(),!(o.hidden||!r()||i.button!==0)&&(l={y:i.clientY,time:Date.now(),id:i.pointerId},c=0,s=!1,o.setPointerCapture?.(i.pointerId))},x=i=>{!l||i.pointerId!==l.id||(c=Math.max(0,i.clientY-l.y),e.style.transform=`translateY(${c}px)`)},v=i=>{if(!l||i.pointerId!==l.id)return;let g=Math.max(1,Date.now()-l.time),P=i.type!=="pointercancel"&&r()&&(c>120||c>40&&c/g>.5);s=c>6,l=void 0,o.releasePointerCapture?.(i.pointerId),e.style.transform="",P?t():c&&typeof e.animate=="function"&&!n?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&e.animate([{transform:`translateY(${c}px)`},{transform:"none"}],{duration:200,easing:"cubic-bezier(.2,.8,.2,1)"}),c=0},m=()=>{if(s){s=!1;return}!l&&c===0&&r()&&t()};o.addEventListener("pointerdown",b),o.addEventListener("pointermove",x),o.addEventListener("pointerup",v),o.addEventListener("pointercancel",v),o.addEventListener("click",m);let L=typeof MutationObserver=="function"?new MutationObserver(p):void 0;return L?.observe(e,{attributes:!0,attributeFilter:["data-presentation"]}),n?.addEventListener("resize",p),p(),()=>{L?.disconnect(),n?.removeEventListener("resize",p),o.remove(),e.style.transform=""}}function q(e,t,r=!1){return(e.type==="modal"||e.type==="sheet")&&e.mobile&&r&&t<=F?e.mobile:e.type}function j(e,t,r){let a=e.ownerDocument.defaultView,n=t.presentation,o;if((n.type==="modal"||n.type==="sheet")&&n.backdrop){let i=`lp-backdrop-${crypto.randomUUID()}`,g={none:"transparent",scrim:"#f2f2f2cc",dim:"#0006","strong-dim":"#000000bf",blur:"#0006"};e.dataset.indianaBackdrop=i,o=e.ownerDocument.createElement("style"),o.textContent=`dialog[data-indiana-backdrop="${i}"]::backdrop{background:${g[n.backdrop]};backdrop-filter:${n.backdrop==="blur"?"blur(16px)":"none"}}`,e.append(o)}let d=t.pages?.[0]?.root.style?.shape,l=d?.type==="pill"?"9999px":d?.type==="rect"?typeof d.radius=="number"?`${d.radius}px`:[d.radius.topLeft,d.radius.topRight,d.radius.bottomRight,d.radius.bottomLeft].map(i=>`${i}px`).join(" "):void 0,c=(n.type==="modal"||n.type==="sheet")&&(n.desktopWidth!==void 0||n.mobile!==void 0||n.type==="modal"&&n.position!==void 0),s=n.type,p,b,x=!1,v=i=>{x||!Number.isFinite(i)||i<0||(b=i,s!=="fullscreen"&&s!=="inline"&&(e.style.height=`min(${Math.max(i,40)}px, calc(100dvh - ${s==="sheet"?0:32}px))`))},m=()=>{if(!x&&(s=p??q(n,a?.innerWidth??1024,a?.matchMedia?.("(pointer: coarse)").matches===!0),e.dataset.presentation=s,!(!c||n.type!=="modal"&&n.type!=="sheet"))){if(e.style.boxSizing="border-box",e.style.padding="0",e.style.border="0",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=-1,e.style.background=t.theme.background,e.style.color=t.theme.text,s==="fullscreen")e.style.width="100vw",e.style.height="100dvh",e.style.maxWidth="100vw",e.style.maxHeight="100dvh",e.style.margin="0",e.style.borderRadius="0";else{let i=n.mobile==="sheet"&&s==="sheet",g=n.desktopWidth,P=a?.innerWidth??1024;e.style.width=i?`${P}px`:g?`${Math.min(g.max,Math.max(P*g.viewport/100,g.min))}px`:`${$[n.size]}px`,e.style.maxWidth=`${Math.max(0,P-(s==="sheet"?0:32))}px`,e.style.maxHeight=s==="sheet"?"100dvh":"calc(100dvh - 32px)",e.style.margin=s==="sheet"?"auto auto 0":n.type==="modal"&&n.position==="top"?"16px auto auto":n.type==="modal"&&n.position==="bottom"?"auto auto 16px":"auto",e.style.borderRadius=l??(s==="sheet"?"16px 16px 0 0":"24px"),e.style.height="",b!==void 0&&v(b)}r?.(s)}},L=c?[a?.matchMedia?.(`(max-width: ${F}px)`),a?.matchMedia?.("(pointer: coarse)")].filter(i=>i!==void 0):[];if(c){a?.addEventListener("resize",m);for(let i of L)i.addEventListener?i.addEventListener("change",m):i.addListener?.(m)}return m(),{responsive:c,get type(){return s},latch(){x||p!==void 0||(m(),p=s)},setContentHeight:v,destroy(){if(!x){x=!0,o?.remove(),delete e.dataset.indianaBackdrop,a?.removeEventListener("resize",m);for(let i of L)i.removeEventListener?i.removeEventListener("change",m):i.removeListener?.(m)}}}}function Se(e,t,r){let{presentation:a}=t,n="size"in a?`${G[a.size]}px`:"100vw";return e.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${n}`,j(e,t,r)}function Le(e,t,r=!1){let a=e.ownerDocument.defaultView;if(typeof e.animate!="function"||a?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let n=r?{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}:{duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};e.animate(t==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:t==="modal"?[{opacity:0,transform:r?"translateY(12px) scale(0.96)":"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],n);try{e.animate([{opacity:0},{opacity:1}],{...n,pseudoElement:"::backdrop"})}catch{}}function V(e,t){e.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0","border-radius:50%","font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";"),e.style.background=`radial-gradient(circle, ${t.background} 0 15px, color-mix(in srgb, ${t.text} 22%, ${t.background}) 15px 16px, transparent 16.5px)`,e.style.color=t.text}function De(e){let t=e.closest("dialog");if(!t?.open||!t.isConnected)return;let r=["style","tabindex","aria-label","data-presentation","data-indiana-backdrop"].map(a=>[a,t.getAttribute(a)]);return{dialog:t,content:e,release(){for(let[a,n]of r)n===null?t.removeAttribute(a):t.setAttribute(a,n)}}}var O=new WeakMap;function ke(e,t){return O.set(e,t),()=>O.delete(e)}function B(e){let t=e.defaultView?.HTMLElement,r=e.activeElement;for(let n=0;n<16&&r?.shadowRoot?.activeElement;n++)r=r.shadowRoot.activeElement;let a=r?O.get(r)?.():void 0;return()=>{!r?.isConnected||!t||!(r instanceof t)||(r.focus({preventScroll:!0}),a?.())}}var Ie=15e3;function Ae(e,t,r,a,n){let o=e.ownerDocument,d=new AbortController,l=!1,c=!1,s,p,b,x,v,m;function L(){clearTimeout(m),m=void 0,b?.(),b=void 0,s?.tagName==="DIALOG"&&s.close?.(),s?.remove(),s=void 0,p=void 0,v=void 0}function i(u,w){c||(c=!0,L(),(u==="dismissed"||u==="error")&&d.abort(w??new DOMException("Presentation cancelled","AbortError")),!(!l&&u!=="ready")&&z(t.onPresentationState,u==="error"?{surface:r,state:u,error:w}:{surface:r,state:u}))}let g=a,P=()=>{c||g()};return{setDismissHandler(u){g=u},get active(){return l&&!c},get cancelled(){return d.signal.aborted},retainPurchaseDialog(){return p?.()},setPurchaseRecovery(u,w){x={message:u,retry:w},v?.()},start(u,w,y){if(l||c)return;l=!0;let C=()=>{if(!c&&t.loading!=="host"){let k=(w??o.documentElement.lang)||"en",M=u&&y?.presentation?.type!=="inline",D=y!==void 0,h=o.createElement(M?"dialog":"div");s=h,h.dataset.longplayLoading=r;let R=k.startsWith("zh"),W=D?R?"正在加载套餐":"Loading plans":R?"正在加载":"Loading",N=y?.screen.theme??{background:"Canvas",text:"CanvasText"};h.setAttribute("aria-label",W);let S=o.createElement("div");S.setAttribute("role","status");let H=o.createElement("div");H.setAttribute("aria-hidden","true"),D?(S.style.cssText="padding:calc(24px + env(safe-area-inset-top, 0px)) 24px 16px;padding-inline-end:68px;font:650 20px/1.3 system-ui,sans-serif;letter-spacing:-.015em",y||(S.style.paddingBlockEnd="24px")):S.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)",S.textContent=W;let T=o.createElement("button");T.type="button",T.textContent=R?"重试":"Retry",T.style.cssText="margin:0 24px 20px;padding:8px 16px",T.onclick=()=>x?.retry?.(),v=()=>{x&&(S.textContent=x.message,x.retry?S.after(T):T.remove())};let E=o.createElement("button");E.type="button",E.textContent="×",E.setAttribute("aria-label",R?"取消加载":"Cancel loading"),V(E,N),D&&(E.style.borderRadius="50%",E.style.top="calc(15px + env(safe-area-inset-top, 0px))",E.style.insetInlineEnd="calc(15px + env(safe-area-inset-right, 0px))"),E.addEventListener("click",P);let _=f=>{f.preventDefault(),P()};h.addEventListener("cancel",_);let I=o.createElement("style");I.textContent="[data-longplay-loading] > button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}",h.append(S,H,E,I),v(),e.append(h);let A=()=>{if(!c&&M){let f=h,Y=B(o);f.showModal?f.showModal():f.open=!0,E.focus({preventScroll:!0}),p=()=>{if(!f.open||!f.isConnected)return;let U=b;return b=void 0,s=void 0,p=void 0,delete f.dataset.longplayLoading,f.removeAttribute("aria-label"),f.style.padding="0",f.removeEventListener("cancel",_),S.remove(),H.remove(),E.remove(),I.remove(),T.remove(),v=void 0,{dialog:f,release(){U?.(),f.close?.(),f.remove(),Y()}}}}};y&&n?(b=n(h,H,y),A()):D?(h.style.cssText=M?"padding:0;border:0;border-radius:24px;background:Canvas;color:CanvasText;width:min(420px,calc(100vw - 32px))":"position:relative;background:Canvas;color:CanvasText;width:100%",A()):(X(h,H,M,r),A())}};y!==void 0&&t.loading!=="host"?m=setTimeout(C,120):C(),z(t.onPresentationState,{surface:r,state:"loading",dismiss:P})},present(u){if(c)return;let w=!!s;L(),u(w),i("ready")},dismiss:P,finish:i,async wait(u,w){let y=d.signal,C,k,M=new Promise((D,h)=>{k=()=>h(y.reason),y.aborted?k():y.addEventListener("abort",k,{once:!0}),w!==void 0&&(C=setTimeout(()=>h(new Error("Presentation data timed out")),w))});try{let D=await Promise.race([M,u]);return y.throwIfAborted(),D}finally{y.removeEventListener("abort",k),clearTimeout(C)}}}}function X(e,t,r,a){e.style.cssText="position:relative;box-sizing:border-box;background:Canvas;color:CanvasText;padding:24px 48px 24px 24px;"+(r?"position:fixed;width:min(480px,calc(100% - 32px));border:0;border-radius:16px;max-height:calc(100dvh - 32px)":"width:100%"),t.style.cssText="display:grid;gap:12px";let n=a==="banner"?[["72%",12],["44%",10]]:[["46%",20],["84%",12],["65%",12],["100%",64]];for(let[o,d]of n){let l=e.ownerDocument.createElement("div");l.style.cssText=`width:${o};height:${d}px;background:currentColor;opacity:.11;border-radius:6px`,t.append(l)}}function J(e){let t={display:"block",position:"fixed",top:"0",left:"0",opacity:"0",pointerEvents:"none",zIndex:"-1"},r=Object.keys(t).map(o=>{let d=o,l=e.style[d];return e.style[d]=t[d],[d,l]}),a=e.inert??!1,n=e.getAttribute("aria-hidden");return e.inert=!0,e.setAttribute("aria-hidden","true"),()=>{for(let[o,d]of r)e.style[o]=d;e.inert=a,n===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n)}}function ze(e,t){let r=e.style.width;e.style.width=`${t.getBoundingClientRect().width||t.ownerDocument.defaultView?.innerWidth||800}px`;let a=J(e);return()=>{a(),e.style.width=r}}export{Pe as a,q as b,j as c,Se as d,Le as e,V as f,De as g,ke as h,B as i,Ie as j,Ae as k,J as l,ze as m};
@@ -0,0 +1 @@
1
+ import{b as He}from"./chunk-NEW77IDA.js";import{a as $}from"./chunk-YDPF2ZZW.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-UIR5CBCC.js";import{a as Ne,b as je,c as Ue}from"./chunk-T5SCW4IA.js";import{a as se}from"./chunk-LBYMDTGD.js";import{i as ue}from"./chunk-CQ5EQNQA.js";import{K as G}from"./chunk-3NV6NBQB.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-WVTKVQLZ.js";import{x as ye}from"./chunk-QTXHF27F.js";import{b as Ve}from"./chunk-MT4OQFDI.js";import{a as l}from"./chunk-ZRU7WONE.js";import{h as oe}from"./chunk-TFPLIX5E.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-S7NHVERO.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-A76T5V7B.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=O(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(A(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Fe(a))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=O(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-RAB5S6KB.js"),import("./check-response-754GDUOJ.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ue(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return be();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=O(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return v(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
@@ -1 +1 @@
1
- import{b as o}from"./chunk-YLH3AYCK.js";var s=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],n=o.string().regex(/.+\/.+/),e=o.number().min(-100),t=o.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),p=o.strictObject({input:t,output:t,cache_read:t.optional(),cache_write:t.optional(),reasoning:t.optional(),input_audio:t.optional(),output_audio:t.optional()}),i=(r,a)=>o.record(r,a).refine(c=>Object.keys(c).length<=100,"At most 100 AI overrides"),d=o.strictObject({defaultMarkup:e,providerMarkups:i(o.string().min(1),e),modelMarkups:i(n,e),customModels:i(n,p.partial())});export{s as a,n as b,e as c,p as d,d as e};
1
+ import{b as o}from"./chunk-S7NHVERO.js";var s=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],n=o.string().regex(/.+\/.+/),e=o.number().min(-100),t=o.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),p=o.strictObject({input:t,output:t,cache_read:t.optional(),cache_write:t.optional(),reasoning:t.optional(),input_audio:t.optional(),output_audio:t.optional()}),i=(r,a)=>o.record(r,a).refine(c=>Object.keys(c).length<=100,"At most 100 AI overrides"),d=o.strictObject({defaultMarkup:e,providerMarkups:i(o.string().min(1),e),modelMarkups:i(n,e),customModels:i(n,p.partial())});export{s as a,n as b,e as c,p as d,d as e};
@@ -0,0 +1 @@
1
+ import{a as fe,b as pe}from"./chunk-2ZMIM4MO.js";import{d as De,e as B}from"./chunk-CQ5EQNQA.js";import{a as Ve}from"./chunk-ZRU7WONE.js";import{a as C}from"./chunk-DSPLGTQI.js";var Te=5*6e4,je=15e3,Oe=new WeakMap;function Be(c){return Oe.get(c)}var A=c=>Array.isArray(c)?c.map(A):c&&typeof c=="object"?Object.fromEntries(Object.keys(c).sort().map(a=>[a,A(c[a])])):c,N=(c,a)=>JSON.stringify(A(c))===JSON.stringify(A(a)),X=c=>JSON.stringify(A([c.funnelId,c.locale??null,c.parameters??{}])),Je=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Xe(c,a){let we=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,x="",R=a.start instanceof Promise?void 0:we(a.start),$=e=>e?.parameters?.commerce,M=Promise.resolve(a.start).then(e=>e?we(e):void 0),z=a.maxAgeMs??Te,ye=new AbortController,w=AbortSignal.any([ye.signal,a.client.identitySignal,...a.signal?[a.signal]:[]]),Q=()=>d("released","aborted"),r="preparing",me,q,Y=()=>{},L=0,P=null,b=null,v=null,y=null,g,D,Z,ge=new Map,h=null,T=new Set,k=new Map,ee,he=new Promise(e=>ee=e),j,be=new Promise(e=>j=e),ne,He=new Promise(e=>ne=e);function J(e,n){r!==e&&(r=e,me=n,C(a.onState,e))}function Fe(){w.removeEventListener("abort",Q),U(),b?.destroy(),b=null,P?.remove(),P=null,v=null}function d(e,n){["adopted","unavailable","released","closed"].includes(r)||(J(e,n),Fe(),ee(!1),j(!1),ne(null))}function O(e){r!=="shown"&&d("unavailable",e)}let p,ae=!1,E=a.client.paywallCopies,te,Pe=new Promise(e=>te=e),re=!1;function ve(e){Pe.then(n=>{n&&E&&E.write(n,e).catch(()=>{})})}function Ie(e){Pe.then(async n=>{if(!n||!E)return;let t=await E.read(n);ae||t&&"presented"in t||await E.write(n,e)}).catch(()=>{})}let oe=e=>`error:${e?.code??e?.name??"unknown"}`,le=c.ownerDocument.defaultView,H=!0,Se=null,_=!1,Ne=e=>e.storageArea===le?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),Ce=e=>{Ne(e)&&G()},xe=a.client.subscribe(()=>G());function U(){H&&(H=!1,le?.removeEventListener("storage",Ce),xe(),Y())}let ie=()=>H&&(r==="ready"||r==="preparing");function se(e){(r==="ready"||r==="preparing")&&d("unavailable",e)}function G(){if(r==="ready"&&Date.now()-L>=z)return U();_=!0,Se??=(async()=>{for(;_&&m&&ie();){_=!1;try{await a.client.retained()==="pending"&&se("purchase_pending")}catch(e){w.aborted?d("released","aborted"):se(oe(e))}}})().finally(()=>{Se=null,_&&m&&ie()&&G()})}le?.addEventListener("storage",Ce),w.addEventListener("abort",Q,{once:!0});let Ae=a.client.findPurchase();Ae.catch(()=>{});let W;function K(e){let n=W?.paywallVersionId??a.paywallVersionId??p?.resolution.id??y?.id,t=JSON.stringify(A([n??null,e])),l=ge.get(t);return l||(l=a.client.readPaywall({paywallVersionId:n,...n?{}:{paywallId:W?.paywallId??a.paywallId},...e}),ge.set(t,l)),l}function V(e,n){let t=Object.values(e.capabilities.plans),l=Object.values(e.document.buttons).some(i=>i.type==="checkout");return l&&t.length===0?!1:n.intent==="subscription_change"&&l?t.some(i=>i.available):t.every(i=>i.available)}function ce(e,n){if(y&&!B(e,y))return d("unavailable","paywall_changed"),!1;y=e,Z=n;for(let t of k.keys())C(t,structuredClone(e));return!0}function Re(e,n){if(!(!y||!["preparing","ready","shown"].includes(r))){if(!B(e,y))return O("paywall_changed");if(!V(e,n.commerce))return O("plan_unavailable");ce(e,n)}}async function F(){let e=await He;if(!e)throw new Ve("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Me={get view(){return h?h.view:y},get signal(){return h?.signal??a.client.identitySignal},get quote(){return h?.quote??null},get operation(){return h?.operation??null},webViewUrl:"bundled",get canReselect(){return h?.canReselect},get recovery(){return h?.recovery},get pendingCancellation(){return h?.pendingCancellation},subscribe(e){return k.set(e,h?.subscribe?.(e)??(()=>{})),()=>{k.get(e)?.(),k.delete(e)}},refresh:async()=>h?h.refresh():structuredClone(y),preview:async e=>(await F()).preview(e),confirm:async()=>(await F()).confirm(),cancel:async()=>(await F()).cancel(),read:async()=>(await F()).read(),destroy(){h?.destroy()}},u={options:{},handoff:{}},ke={loading:"host",focusAtReveal:!0,signal:a.client.identitySignal,start:async()=>Me,canInteract:()=>u.options.canInteract?u.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",n=y?.capabilities,t=await F();if(e&&!N(t.view?.capabilities,n))throw new De;await u.options.beforeAction?.()}};for(let e of Je)Object.defineProperty(ke,e,{enumerable:!0,get:()=>u.options[e]});function de(){r!=="preparing"||!v||!b||!p&&(!m||!N(Z?.commerce,$(m))||Z?.locale!==m.locale)||(J("ready"),ee(!0))}let Ee={present(e){if(u.handoff.present)return u.handoff.present(e);r==="preparing"&&(v=e,L=Date.now(),de())},async dismiss(){if(u.handoff.dismiss)return u.handoff.dismiss();d("closed");for(let e of[...T])C(e)},async closeAction(e){if(u.handoff.closeAction)return u.handoff.closeAction(e);u.options.onAction?await u.options.onAction(e):await Ee.dismiss()},quoteError(e){u.handoff.quoteError?u.handoff.quoteError(e):C(u.options.onError,e)}};async function qe(){if(a.paywallVersionId||a.paywallId)return{paywallVersionId:a.paywallVersionId,paywallId:a.paywallId};let e=a.configuration;if(!e)return d("unavailable","paywall_missing"),null;let n=await Promise.resolve(a.start).catch(()=>null);if(!n||r!=="preparing")return null;let t=()=>fe(e,{funnelId:n.funnelId,customerId:a.client.customerId,parameters:n.parameters??{}});if(q=await t(),r!=="preparing")return null;let l=q;if(l.type!=="paywall")return d("unavailable",pe(l)??"route"),null;let i=!1;return Y=e.subscribe(()=>{i||!ie()||(i=!0,t().then(s=>{!(s.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(s.reason))&&(s.type!=="paywall"||s.paywallVersionId!==l.paywallVersionId)&&se("route_changed")}).finally(()=>i=!1))}),H||Y(),{paywallVersionId:l.paywallVersionId}}(async()=>{try{let[{showPaywall:e},n]=await Promise.all([import("./paywall-BSY67NQL.js"),qe()]),t=a.commerce??$(R),l=a.locale??R?.locale,i=n&&t&&l?JSON.stringify(A([n.paywallVersionId??null,n.paywallId??null,{commerce:t,locale:l}])):null;if(te(i),w.throwIfAborted(),r!=="preparing"||!n)return;if(!t)return d("unavailable","commerce_missing");if(!l)return d("unavailable","locale_missing");W=n;let s={commerce:t,locale:l},f=i?await E?.read(i).catch(()=>null):null;if(re=!!f&&"presented"in f&&(!R||f.funnelId===R.funnelId),w.throwIfAborted(),r!=="preparing"||re)return;f&&!("presented"in f)&&(!R||f.funnelId===R.funnelId)&&V(f.resolution,f.context.commerce)&&(p=f),j(!!p);let o;if(p){let ue=p.context;s=ue,o=structuredClone(p.resolution),K(ue).then(Le=>Re(Le,ue),()=>{})}else o=await K(s);if(w.throwIfAborted(),r!=="preparing"||(!V(o,s.commerce)&&a.start instanceof Promise&&!g&&await M,!p&&g&&!N(s,g)&&(s=g,o=await K(s)),w.throwIfAborted(),r!=="preparing"))return;if(!V(o,s.commerce))return d("unavailable","plan_unavailable");if(!ce(o,s))return;P=c.ownerDocument.createElement("div"),c.append(P);let S=setTimeout(()=>r==="preparing"&&d("unavailable","timeout"),je);he.then(()=>clearTimeout(S));let I=await e(P,ke,Ee);if(!I.host||w.aborted||r!=="preparing"){I.host?.destroy(),d(w.aborted?"released":"unavailable","error");return}b=I.host,de()}catch(e){d(w.aborted?"released":"unavailable",oe(e))}finally{te(null),j(!1)}})(),M.then(async e=>{let n=s=>{Ie(null),O(s)};if(!e)return n("gated");let t=e,l=$(t),i=a.commerce??l;if(!N(l&&{...l,intent:void 0},i&&{...i,intent:void 0})||a.locale!==void 0&&t.locale!==a.locale)return n("start_mismatch");if(!l)return n("commerce_missing");g={commerce:l,locale:t.locale},D=t,p&&["preparing","ready","shown"].includes(r)&&(m=t,x=X(t));try{let s=await Ae,f=s==="pending"?"purchase_pending":s==="found"?"original_purchase":s==="blocked"?"purchase_blocked":void 0;if(f)return n(f);if(!["preparing","ready","shown"].includes(r))return;if(a.configuration&&(a.paywallId||a.paywallVersionId)){let o=await fe(a.configuration,{funnelId:t.funnelId,customerId:a.client.customerId,parameters:t.parameters??{}});w.throwIfAborted();let S=o.type==="unknown"||o.type==="unavailable"&&o.reason!=="funnel_stopped";if(o.type==="paywall"?p?o.paywallId!==p.resolution.paywallId:a.paywallVersionId?o.paywallVersionId!==a.paywallVersionId:o.paywallId!==a.paywallId:!S)return n(pe(o)??"route_changed")}if(H&&(_=!1,await a.client.retained()==="pending"))return n("purchase_pending");if(await be,re){m=t,x=X(t);return}if(W||a.paywallId||a.paywallVersionId||y){let o=await K(g);if(w.throwIfAborted(),Ie(V(o,g.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:g,resolution:o}:null),p)Re(o,g);else{if(r!=="preparing")return;if(y){if(!V(o,g.commerce))return d("unavailable","plan_unavailable");if(!ce(o,g))return}}}}catch(s){return w.aborted?d("released","aborted"):O(oe(s))}["preparing","ready","shown"].includes(r)&&(m=t,x=X(t),de(),_&&G())},()=>O("gated"));let _e={get state(){return r},get reason(){return me},ready:he,local:be,get start(){return m},get prediction(){return q?structuredClone(q):void 0},matches:e=>m?X(e)===x:!!p&&e.funnelId===p.funnelId&&e.locale===p.context.locale,open(){if(r==="preparing")return"pending";if(r!=="ready"||!v)return!1;if(Date.now()-L>=z)return d("unavailable","expired"),!1;let e=v;return v=null,U(),J("shown"),e(),"shown"},destroy(){ye.abort()}};return Oe.set(_e,{onClose(e){return r==="closed"?(C(e),()=>{}):(T.add(e),()=>{T.delete(e)})},claim(){U()},remember(e){ae=!0;let n=structuredClone(e);M.then(()=>{!D||!g||ve({savedAt:Date.now(),funnelId:D.funnelId,context:g,resolution:n})},()=>{})},withhold(){ae=!0,M.then(()=>{D&&ve({savedAt:Date.now(),funnelId:D.funnelId,presented:"nothing"})},()=>{})},async adopt(e,n){let t=e.paywall?.resolution,l=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!b||!y||!t||!l||e.source.id!==m?.funnelId||e.locale!==m?.locale||!N(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!B(t,y))return null;let i;try{i=await n.start()}catch{return null}if(r!=="shown"||!b)return i.destroy(),null;h=i,u.options=n.options,u.handoff=n.handoff;for(let[o]of k)k.set(o,i.subscribe?.(o)??(()=>{})),i.view&&C(o,structuredClone(i.view));w.removeEventListener("abort",Q),J("adopted"),ne(i),T.clear();let s=b,f=P;return b=null,P=null,v=null,new Proxy(s,{get(o,S){return S==="destroy"?()=>{o.destroy(),f?.remove()}:S==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),f?.remove()}}}:Reflect.get(o,S,o)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=b?.retainPurchaseDialog();if(!e)return;let n=P;return b=null,P=null,d("released"),{dialog:e.dialog,release(){e.release(),n?.remove()}}},get modal(){return y?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!v&&Date.now()-L<z},release(){d("released")}}),_e}export{Te as a,Be as b,Xe as c};