@riddledc/riddle-proof 0.8.85 → 0.8.87

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 (58) hide show
  1. package/dist/advanced/index.d.cts +1 -1
  2. package/dist/advanced/index.d.ts +1 -1
  3. package/dist/advanced/proof-run-engine.d.cts +1 -1
  4. package/dist/advanced/proof-run-engine.d.ts +1 -1
  5. package/dist/change-proof.cjs +2 -9
  6. package/dist/change-proof.d.cts +1 -1
  7. package/dist/change-proof.d.ts +1 -1
  8. package/dist/change-proof.js +2 -2
  9. package/dist/{chunk-AFARUBE4.js → chunk-3W4NGKZ6.js} +11 -11
  10. package/dist/chunk-6S33FQL7.js +14 -0
  11. package/dist/{chunk-FW7CKARF.js → chunk-7W6ZJPHJ.js} +1 -1
  12. package/dist/{chunk-JZKLCY5G.js → chunk-BVYM4WJ5.js} +1 -1
  13. package/dist/chunk-GQOE5Q7C.js +32 -0
  14. package/dist/chunk-H5AALGSA.js +32 -0
  15. package/dist/{chunk-2K3DIK7A.js → chunk-KF6F2RMQ.js} +301 -3979
  16. package/dist/{chunk-O2AO726C.js → chunk-NR2XQXIC.js} +3 -3
  17. package/dist/cli/index.js +5 -5
  18. package/dist/cli.cjs +285 -3999
  19. package/dist/cli.js +5 -5
  20. package/dist/evidence-trust-root.cjs +54 -0
  21. package/dist/evidence-trust-root.d.cts +2 -0
  22. package/dist/evidence-trust-root.d.ts +2 -0
  23. package/dist/evidence-trust-root.js +31 -0
  24. package/dist/index.cjs +346 -3991
  25. package/dist/index.d.cts +8 -1
  26. package/dist/index.d.ts +8 -1
  27. package/dist/index.js +80 -14
  28. package/dist/packet.cjs +54 -0
  29. package/dist/packet.d.cts +2 -0
  30. package/dist/packet.d.ts +2 -0
  31. package/dist/packet.js +31 -0
  32. package/dist/pr-comment.cjs +2 -9
  33. package/dist/pr-comment.d.cts +2 -2
  34. package/dist/pr-comment.d.ts +2 -2
  35. package/dist/pr-comment.js +3 -3
  36. package/dist/profile/index.cjs +277 -3991
  37. package/dist/profile/index.d.cts +2 -3
  38. package/dist/profile/index.d.ts +2 -3
  39. package/dist/profile/index.js +1 -1
  40. package/dist/profile-suggestions.cjs +2 -2
  41. package/dist/profile-suggestions.d.cts +1 -3
  42. package/dist/profile-suggestions.d.ts +1 -3
  43. package/dist/profile-suggestions.js +2 -2
  44. package/dist/profile.cjs +277 -3991
  45. package/dist/profile.d.cts +3 -550
  46. package/dist/profile.d.ts +3 -550
  47. package/dist/profile.js +1 -1
  48. package/dist/{proof-run-engine-DpChFR5H.d.cts → proof-run-engine-Baiv6l3A.d.cts} +3 -3
  49. package/dist/{proof-run-engine-BqRoA3Do.d.ts → proof-run-engine-MiKZt9oY.d.ts} +3 -3
  50. package/dist/proof-run-engine.d.cts +1 -1
  51. package/dist/proof-run-engine.d.ts +1 -1
  52. package/dist/receipts.d.cts +3 -0
  53. package/dist/receipts.d.ts +3 -0
  54. package/dist/rule-trust-root.cjs +36 -0
  55. package/dist/rule-trust-root.d.cts +2 -0
  56. package/dist/rule-trust-root.d.ts +2 -0
  57. package/dist/rule-trust-root.js +13 -0
  58. package/package.json +20 -5
package/dist/index.cjs CHANGED
@@ -3438,6 +3438,18 @@ __export(index_exports, {
3438
3438
  RIDDLE_PROOF_CHECKED_MEANING_RULE_ENGINE: () => import_checked_meaning.RIDDLE_PROOF_CHECKED_MEANING_RULE_ENGINE,
3439
3439
  RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION: () => RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
3440
3440
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: () => RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
3441
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_ARRAY_ITEMS: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_ARRAY_ITEMS,
3442
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_DEPTH: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_DEPTH,
3443
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_NODES: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_NODES,
3444
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_PROPERTIES: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_PROPERTIES,
3445
+ RIDDLE_PROOF_EVIDENCE_SENSOR_TARGET_BINDING: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_SENSOR_TARGET_BINDING,
3446
+ RIDDLE_PROOF_EVIDENCE_TEMPLATE_PROFILE_MODE: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_TEMPLATE_PROFILE_MODE,
3447
+ RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_DIGEST_DOMAIN: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_DIGEST_DOMAIN,
3448
+ RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_MAX_PROFILES: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_MAX_PROFILES,
3449
+ RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_VERSION: () => import_evidence_trust_root.RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_VERSION,
3450
+ RIDDLE_PROOF_EXECUTION_DIGEST_DOMAIN: () => import_packet.RIDDLE_PROOF_EXECUTION_DIGEST_DOMAIN,
3451
+ RIDDLE_PROOF_EXECUTION_POLICY_DIGEST_DOMAIN: () => import_packet.RIDDLE_PROOF_EXECUTION_POLICY_DIGEST_DOMAIN,
3452
+ RIDDLE_PROOF_EXECUTION_POLICY_VERSION: () => import_packet.RIDDLE_PROOF_EXECUTION_POLICY_VERSION,
3441
3453
  RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_ARTIFACTS: () => import_grounded_evidence.RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_ARTIFACTS,
3442
3454
  RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_ARTIFACT_BYTES: () => import_grounded_evidence.RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_ARTIFACT_BYTES,
3443
3455
  RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_OBSERVATION_BYTES: () => import_grounded_evidence.RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_OBSERVATION_BYTES,
@@ -3459,20 +3471,27 @@ __export(index_exports, {
3459
3471
  RIDDLE_PROOF_GROUNDED_SEMANTIC_CLOSURE_MAX_TOTAL_ARTIFACT_BYTES: () => import_grounded_evidence.RIDDLE_PROOF_GROUNDED_SEMANTIC_CLOSURE_MAX_TOTAL_ARTIFACT_BYTES,
3460
3472
  RIDDLE_PROOF_GROUNDED_VERIFICATION_RECEIPT_VERSION: () => import_grounded_evidence.RIDDLE_PROOF_GROUNDED_VERIFICATION_RECEIPT_VERSION,
3461
3473
  RIDDLE_PROOF_HANDOFF_RECEIPT_VERSION: () => RIDDLE_PROOF_HANDOFF_RECEIPT_VERSION,
3462
- RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS: () => RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS,
3474
+ RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS: () => import_profile2.RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS,
3463
3475
  RIDDLE_PROOF_OBSERVATION_RECEIPT_VERSION: () => import_receipts.RIDDLE_PROOF_OBSERVATION_RECEIPT_VERSION,
3464
- RIDDLE_PROOF_ORDERED_TRACE_OPERATORS: () => RIDDLE_PROOF_ORDERED_TRACE_OPERATORS,
3476
+ RIDDLE_PROOF_ORDERED_TRACE_OPERATORS: () => import_profile2.RIDDLE_PROOF_ORDERED_TRACE_OPERATORS,
3477
+ RIDDLE_PROOF_PACKET_RECEIPT_DIGEST_DOMAIN: () => import_packet.RIDDLE_PROOF_PACKET_RECEIPT_DIGEST_DOMAIN,
3478
+ RIDDLE_PROOF_PACKET_RECEIPT_VERSION: () => import_packet.RIDDLE_PROOF_PACKET_RECEIPT_VERSION,
3465
3479
  RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION: () => RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION,
3466
3480
  RIDDLE_PROOF_PLAYABILITY_VERSION: () => RIDDLE_PROOF_PLAYABILITY_VERSION,
3467
- RIDDLE_PROOF_PROFILE_CHECK_TYPES: () => RIDDLE_PROOF_PROFILE_CHECK_TYPES,
3468
- RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION: () => RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION,
3469
- RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES: () => RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES,
3470
- RIDDLE_PROOF_PROFILE_RESULT_VERSION: () => RIDDLE_PROOF_PROFILE_RESULT_VERSION,
3471
- RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES: () => RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES,
3472
- RIDDLE_PROOF_PROFILE_STATUSES: () => RIDDLE_PROOF_PROFILE_STATUSES,
3481
+ RIDDLE_PROOF_PRIVATE_PACKET_DIGEST_DOMAIN: () => import_packet.RIDDLE_PROOF_PRIVATE_PACKET_DIGEST_DOMAIN,
3482
+ RIDDLE_PROOF_PRIVATE_PACKET_MEDIA_TYPE: () => import_packet.RIDDLE_PROOF_PRIVATE_PACKET_MEDIA_TYPE,
3483
+ RIDDLE_PROOF_PRIVATE_PACKET_VERSION: () => import_packet.RIDDLE_PROOF_PRIVATE_PACKET_VERSION,
3484
+ RIDDLE_PROOF_PROFILE_CHECK_TYPES: () => import_profile2.RIDDLE_PROOF_PROFILE_CHECK_TYPES,
3485
+ RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION: () => import_profile2.RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION,
3486
+ RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES: () => import_profile2.RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES,
3487
+ RIDDLE_PROOF_PROFILE_RESULT_VERSION: () => import_profile2.RIDDLE_PROOF_PROFILE_RESULT_VERSION,
3488
+ RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES: () => import_profile2.RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES,
3489
+ RIDDLE_PROOF_PROFILE_STATUSES: () => import_profile2.RIDDLE_PROOF_PROFILE_STATUSES,
3473
3490
  RIDDLE_PROOF_PROFILE_SUGGESTIONS_VERSION: () => RIDDLE_PROOF_PROFILE_SUGGESTIONS_VERSION,
3474
- RIDDLE_PROOF_PROFILE_VERSION: () => RIDDLE_PROOF_PROFILE_VERSION,
3491
+ RIDDLE_PROOF_PROFILE_VERSION: () => import_profile2.RIDDLE_PROOF_PROFILE_VERSION,
3475
3492
  RIDDLE_PROOF_PR_COMMENT_MARKER: () => RIDDLE_PROOF_PR_COMMENT_MARKER,
3493
+ RIDDLE_PROOF_RULE_TRUST_ROOT_DIGEST_DOMAIN: () => import_rule_trust_root.RIDDLE_PROOF_RULE_TRUST_ROOT_DIGEST_DOMAIN,
3494
+ RIDDLE_PROOF_RULE_TRUST_ROOT_VERSION: () => import_rule_trust_root.RIDDLE_PROOF_RULE_TRUST_ROOT_VERSION,
3476
3495
  RIDDLE_PROOF_RUN_CARD_VERSION: () => RIDDLE_PROOF_RUN_CARD_VERSION,
3477
3496
  RIDDLE_PROOF_RUN_STATE_VERSION: () => RIDDLE_PROOF_RUN_STATE_VERSION,
3478
3497
  RIDDLE_PROOF_SEMANTIC_CERTIFICATE_CLOSURE_MAX_CERTIFICATES: () => import_semantic_certificate.RIDDLE_PROOF_SEMANTIC_CERTIFICATE_CLOSURE_MAX_CERTIFICATES,
@@ -3488,7 +3507,7 @@ __export(index_exports, {
3488
3507
  appendRunEvent: () => appendRunEvent,
3489
3508
  appendStageHeartbeat: () => appendStageHeartbeat,
3490
3509
  applyPrLifecycleState: () => applyPrLifecycleState,
3491
- applyRiddleProofProfileArtifactCompleteness: () => applyRiddleProofProfileArtifactCompleteness,
3510
+ applyRiddleProofProfileArtifactCompleteness: () => import_profile2.applyRiddleProofProfileArtifactCompleteness,
3492
3511
  applyShipControlState: () => applyShipControlState,
3493
3512
  applyTerminalMetadata: () => applyTerminalMetadata,
3494
3513
  assessBasicGameplayEvidence: () => assessBasicGameplayEvidence,
@@ -3498,10 +3517,10 @@ __export(index_exports, {
3498
3517
  assessPlayabilityEvidence: () => assessPlayabilityEvidence,
3499
3518
  assessRiddleProofChange: () => assessRiddleProofChange,
3500
3519
  assessRiddleProofCheckedMeaningClosure: () => import_checked_meaning.assessRiddleProofCheckedMeaningClosure,
3501
- assessRiddleProofOrderedTrace: () => assessRiddleProofOrderedTrace,
3502
- assessRiddleProofOrderedTraceSetupResults: () => assessRiddleProofOrderedTraceSetupResults,
3503
- assessRiddleProofProfileArtifactCompleteness: () => assessRiddleProofProfileArtifactCompleteness,
3504
- assessRiddleProofProfileEvidence: () => assessRiddleProofProfileEvidence,
3520
+ assessRiddleProofOrderedTrace: () => import_profile2.assessRiddleProofOrderedTrace,
3521
+ assessRiddleProofOrderedTraceSetupResults: () => import_profile2.assessRiddleProofOrderedTraceSetupResults,
3522
+ assessRiddleProofProfileArtifactCompleteness: () => import_profile2.assessRiddleProofProfileArtifactCompleteness,
3523
+ assessRiddleProofProfileEvidence: () => import_profile2.assessRiddleProofProfileEvidence,
3505
3524
  attachBasicGameplayArtifactScreenshotHashes: () => attachBasicGameplayArtifactScreenshotHashes,
3506
3525
  augmentBasicGameplayAssessmentWithProgressionChecks: () => augmentBasicGameplayAssessmentWithProgressionChecks,
3507
3526
  authorPacketPayloadFromCheckpointResponse: () => authorPacketPayloadFromCheckpointResponse,
@@ -3517,8 +3536,8 @@ __export(index_exports, {
3517
3536
  checkpointResponseIdentity: () => checkpointResponseIdentity,
3518
3537
  checkpointSummaryFromState: () => checkpointSummaryFromState,
3519
3538
  collectRiddlePreviewDeployWarnings: () => import_client.collectRiddlePreviewDeployWarnings,
3520
- collectRiddleProfileArtifactRefs: () => collectRiddleProfileArtifactRefs,
3521
- collectRiddleProofProfileWarnings: () => collectRiddleProofProfileWarnings,
3539
+ collectRiddleProfileArtifactRefs: () => import_profile2.collectRiddleProfileArtifactRefs,
3540
+ collectRiddleProofProfileWarnings: () => import_profile2.collectRiddleProofProfileWarnings,
3522
3541
  compactBasicGameplayText: () => compactBasicGameplayText,
3523
3542
  compactRecord: () => compactRecord,
3524
3543
  compareVisualProofSessionFingerprint: () => compareVisualProofSessionFingerprint,
@@ -3539,15 +3558,18 @@ __export(index_exports, {
3539
3558
  createRiddleProofChangeReceipt: () => createRiddleProofChangeReceipt,
3540
3559
  createRiddleProofCheckedMeaningAtomicClosure: () => import_checked_meaning.createRiddleProofCheckedMeaningAtomicClosure,
3541
3560
  createRiddleProofCheckedMeaningRule: () => import_checked_meaning.createRiddleProofCheckedMeaningRule,
3561
+ createRiddleProofEvidenceTrustRoot: () => import_evidence_trust_root.createRiddleProofEvidenceTrustRoot,
3542
3562
  createRiddleProofGroundedDeclarativeJsonContract: () => import_grounded_evidence.createRiddleProofGroundedDeclarativeJsonContract,
3543
3563
  createRiddleProofGroundedDeclarativeJsonVerifier: () => import_grounded_evidence.createRiddleProofGroundedDeclarativeJsonVerifier,
3544
3564
  createRiddleProofGroundedSemanticAtomicCertificateClosure: () => import_grounded_evidence.createRiddleProofGroundedSemanticAtomicCertificateClosure,
3545
3565
  createRiddleProofGroundedSemanticCertificate: () => import_grounded_evidence.createRiddleProofGroundedSemanticCertificate,
3546
3566
  createRiddleProofHandoffReceipt: () => createRiddleProofHandoffReceipt,
3547
3567
  createRiddleProofObservationReceipt: () => import_receipts.createRiddleProofObservationReceipt,
3548
- createRiddleProofProfileConfigurationError: () => createRiddleProofProfileConfigurationError,
3549
- createRiddleProofProfileEnvironmentBlockedResult: () => createRiddleProofProfileEnvironmentBlockedResult,
3550
- createRiddleProofProfileInsufficientResult: () => createRiddleProofProfileInsufficientResult,
3568
+ createRiddleProofPacketReceipt: () => import_packet.createRiddleProofPacketReceipt,
3569
+ createRiddleProofProfileConfigurationError: () => import_profile2.createRiddleProofProfileConfigurationError,
3570
+ createRiddleProofProfileEnvironmentBlockedResult: () => import_profile2.createRiddleProofProfileEnvironmentBlockedResult,
3571
+ createRiddleProofProfileInsufficientResult: () => import_profile2.createRiddleProofProfileInsufficientResult,
3572
+ createRiddleProofRuleTrustRoot: () => import_rule_trust_root.createRiddleProofRuleTrustRoot,
3551
3573
  createRiddleProofRunCard: () => createRiddleProofRunCard,
3552
3574
  createRiddleProofSemanticAtomicCertificateClosure: () => import_semantic_certificate.createRiddleProofSemanticAtomicCertificateClosure,
3553
3575
  createRiddleProofSemanticCertificate: () => import_semantic_certificate.createRiddleProofSemanticCertificate,
@@ -3557,11 +3579,14 @@ __export(index_exports, {
3557
3579
  createRunStatusSnapshot: () => createRunStatusSnapshot,
3558
3580
  deployRiddlePreview: () => import_client.deployRiddlePreview,
3559
3581
  deployRiddleStaticPreview: () => import_client.deployRiddleStaticPreview,
3560
- deriveRiddleProofArtifactBodyAssertions: () => deriveRiddleProofArtifactBodyAssertions,
3582
+ deriveRiddleProofArtifactBodyAssertions: () => import_profile2.deriveRiddleProofArtifactBodyAssertions,
3561
3583
  detectRiddlePreviewSource: () => import_client.detectRiddlePreviewSource,
3584
+ digestRiddleProofExecution: () => import_packet.digestRiddleProofExecution,
3585
+ digestRiddleProofExecutionPolicy: () => import_packet.digestRiddleProofExecutionPolicy,
3586
+ digestRiddleProofPrivatePacketBytes: () => import_packet.digestRiddleProofPrivatePacketBytes,
3562
3587
  extractBasicGameplayEvidence: () => extractBasicGameplayEvidence,
3563
3588
  extractPlayabilityEvidence: () => extractPlayabilityEvidence,
3564
- extractRiddleProofProfileResult: () => extractRiddleProofProfileResult,
3589
+ extractRiddleProofProfileResult: () => import_profile2.extractRiddleProofProfileResult,
3565
3590
  getRiddleBalance: () => import_client.getRiddleBalance,
3566
3591
  getRiddleJobArtifacts: () => import_client.getRiddleJobArtifacts,
3567
3592
  isDuplicateCheckpointResponse: () => isDuplicateCheckpointResponse,
@@ -3574,12 +3599,13 @@ __export(index_exports, {
3574
3599
  matchRiddleProofGroundedSemanticCertificateClosure: () => import_grounded_evidence.matchRiddleProofGroundedSemanticCertificateClosure,
3575
3600
  matchRiddleProofSemanticCertificate: () => import_semantic_certificate.matchRiddleProofSemanticCertificate,
3576
3601
  matchRiddleProofSemanticCertificateClosure: () => import_semantic_certificate.matchRiddleProofSemanticCertificateClosure,
3602
+ materializeRiddleProofEvidenceTrustProfile: () => import_evidence_trust_root.materializeRiddleProofEvidenceTrustProfile,
3577
3603
  migrateRiddleProofChangeReceipt: () => migrateRiddleProofChangeReceipt,
3578
3604
  nonEmptyString: () => nonEmptyString,
3579
3605
  normalizeCheckpointResponse: () => normalizeCheckpointResponse,
3580
3606
  normalizeIntegrationContext: () => normalizeIntegrationContext,
3581
3607
  normalizePrLifecycleState: () => normalizePrLifecycleState,
3582
- normalizeRiddleProofProfile: () => normalizeRiddleProofProfile,
3608
+ normalizeRiddleProofProfile: () => import_profile2.normalizeRiddleProofProfile,
3583
3609
  normalizeRunParams: () => normalizeRunParams,
3584
3610
  normalizeTerminalMetadata: () => normalizeTerminalMetadata,
3585
3611
  parseRiddlePreviewReceipt: () => import_receipts.parseRiddlePreviewReceipt,
@@ -3591,8 +3617,8 @@ __export(index_exports, {
3591
3617
  parseVisualProofSession: () => parseVisualProofSession,
3592
3618
  pollRiddleJob: () => import_client.pollRiddleJob,
3593
3619
  preflightRiddleProofProfileHttpStatusChecks: () => preflightRiddleProofProfileHttpStatusChecks,
3594
- preflightRiddleProofProfileRunnerArtifacts: () => preflightRiddleProofProfileRunnerArtifacts,
3595
- profileStatusExitCode: () => profileStatusExitCode,
3620
+ preflightRiddleProofProfileRunnerArtifacts: () => import_profile2.preflightRiddleProofProfileRunnerArtifacts,
3621
+ profileStatusExitCode: () => import_profile2.profileStatusExitCode,
3596
3622
  proofContractFromAuthorCheckpointResponse: () => proofContractFromAuthorCheckpointResponse,
3597
3623
  publicMergeRecommendationForRunState: () => publicMergeRecommendationForRunState,
3598
3624
  publicStateForRunState: () => publicStateForRunState,
@@ -3604,9 +3630,11 @@ __export(index_exports, {
3604
3630
  resolveBasicGameplayProgressionCheckWithArtifactScreenshots: () => resolveBasicGameplayProgressionCheckWithArtifactScreenshots,
3605
3631
  resolveRiddleApiKey: () => import_client.resolveRiddleApiKey,
3606
3632
  resolveRiddleApiKeySource: () => import_client.resolveRiddleApiKeySource,
3607
- resolveRiddleProofProfileRouteUrl: () => resolveRiddleProofProfileRouteUrl,
3608
- resolveRiddleProofProfileTargetUrl: () => resolveRiddleProofProfileTargetUrl,
3609
- resolveRiddleProofProfileTimeoutSec: () => resolveRiddleProofProfileTimeoutSec,
3633
+ resolveRiddleProofEvidenceTrustRoot: () => import_evidence_trust_root.resolveRiddleProofEvidenceTrustRoot,
3634
+ resolveRiddleProofProfileRouteUrl: () => import_profile2.resolveRiddleProofProfileRouteUrl,
3635
+ resolveRiddleProofProfileTargetUrl: () => import_profile2.resolveRiddleProofProfileTargetUrl,
3636
+ resolveRiddleProofProfileTimeoutSec: () => import_profile2.resolveRiddleProofProfileTimeoutSec,
3637
+ resolveRiddleProofRuleTrustRoot: () => import_rule_trust_root.resolveRiddleProofRuleTrustRoot,
3610
3638
  riddleProofChangeReceiptHtml: () => riddleProofChangeReceiptHtml,
3611
3639
  riddleProofChangeReceiptMarkdown: () => riddleProofChangeReceiptMarkdown,
3612
3640
  riddleProofPublicStateAllowsClaim: () => riddleProofPublicStateAllowsClaim,
@@ -3623,19 +3651,21 @@ __export(index_exports, {
3623
3651
  sanitizeBasicGameplayJsonString: () => sanitizeBasicGameplayJsonString,
3624
3652
  setRunStatus: () => setRunStatus,
3625
3653
  shipControlStateFor: () => shipControlStateFor,
3626
- slugifyRiddleProofProfileName: () => slugifyRiddleProofProfileName,
3654
+ slugifyRiddleProofProfileName: () => import_profile2.slugifyRiddleProofProfileName,
3627
3655
  statePathsForRunState: () => statePathsForRunState,
3628
3656
  suggestRiddleProofProfileChecks: () => suggestRiddleProofProfileChecks,
3629
3657
  summarizeCaptureArtifacts: () => summarizeCaptureArtifacts,
3630
3658
  summarizeRiddleProofAgentSummarySurface: () => summarizeRiddleProofAgentSummarySurface,
3631
3659
  summarizeRiddleProofHostedProofViewSurface: () => summarizeRiddleProofHostedProofViewSurface,
3632
3660
  summarizeRiddleProofPrComment: () => summarizeRiddleProofPrComment,
3633
- summarizeRiddleProofProfileResult: () => summarizeRiddleProofProfileResult,
3661
+ summarizeRiddleProofProfileResult: () => import_profile2.summarizeRiddleProofProfileResult,
3634
3662
  summarizeRiddleProofPublicConsumerSurface: () => summarizeRiddleProofPublicConsumerSurface,
3635
3663
  summarizeRiddleProofPublicState: () => summarizeRiddleProofPublicState,
3636
3664
  validateRiddleProofCheckedMeaningClosure: () => import_checked_meaning.validateRiddleProofCheckedMeaningClosure,
3665
+ validateRiddleProofEvidenceObservationSchema: () => import_evidence_trust_root.validateRiddleProofEvidenceObservationSchema,
3637
3666
  validateRiddleProofGroundedSemanticCertificateClosure: () => import_grounded_evidence.validateRiddleProofGroundedSemanticCertificateClosure,
3638
3667
  validateRiddleProofSemanticCertificateClosure: () => import_semantic_certificate.validateRiddleProofSemanticCertificateClosure,
3668
+ verifyRiddleProofPacketReceipt: () => import_packet.verifyRiddleProofPacketReceipt,
3639
3669
  verifyRiddleProofSignedCaptureBundle: () => import_grounded_evidence.verifyRiddleProofSignedCaptureBundle,
3640
3670
  visualSessionFingerprint: () => visualSessionFingerprint,
3641
3671
  visualSessionFingerprintBasis: () => visualSessionFingerprintBasis
@@ -10246,145 +10276,10 @@ function parseJson2(value) {
10246
10276
  }
10247
10277
 
10248
10278
  // src/profile.ts
10249
- var RIDDLE_PROOF_PROFILE_VERSION = "riddle-proof.profile.v1";
10250
- var RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION = "riddle-proof.profile-evidence.v1";
10251
- var RIDDLE_PROOF_PROFILE_RESULT_VERSION = "riddle-proof.profile-result.v1";
10252
- var RIDDLE_PROOF_PROFILE_STATUSES = [
10253
- "passed",
10254
- "product_regression",
10255
- "proof_insufficient",
10256
- "environment_blocked",
10257
- "configuration_error",
10258
- "needs_human_review"
10259
- ];
10260
- var RIDDLE_PROOF_PROFILE_CHECK_TYPES = [
10261
- "route_loaded",
10262
- "url_search_param_equals",
10263
- "url_search_param_absent",
10264
- "selector_visible",
10265
- "selector_absent",
10266
- "selector_count_at_least",
10267
- "selector_count_equals",
10268
- "selector_count_equal",
10269
- "selector_count_eq",
10270
- "dialog_count_equals",
10271
- "dialog_accept_count_equals",
10272
- "dialog_dismiss_count_equals",
10273
- "selector_text_visible",
10274
- "selector_text_absent",
10275
- "selector_text_order",
10276
- "ordered_trace",
10277
- "observe_within",
10278
- "frame_text_visible",
10279
- "frame_url_equals",
10280
- "frame_url_matches",
10281
- "frame_no_horizontal_overflow",
10282
- "text_visible",
10283
- "text_absent",
10284
- "http_status",
10285
- "link_status",
10286
- "artifact_link_status",
10287
- "route_inventory",
10288
- "no_horizontal_overflow",
10289
- "no_mobile_horizontal_overflow",
10290
- "no_fatal_console_errors",
10291
- "no_console_warnings"
10292
- ];
10293
- var RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES = [
10294
- "click",
10295
- "tap",
10296
- "tap_until",
10297
- "drag",
10298
- "press",
10299
- "key_down",
10300
- "key_up",
10301
- "fill",
10302
- "set_input_value",
10303
- "set_range_value",
10304
- "deterministic_runtime",
10305
- "canvas_signature",
10306
- "assert_text_visible",
10307
- "assert_text_absent",
10308
- "assert_selector_count",
10309
- "assert_window_value",
10310
- "assert_window_number",
10311
- "local_storage",
10312
- "session_storage",
10313
- "clear_storage",
10314
- "clear_console",
10315
- "dialog_response",
10316
- "screenshot",
10317
- "wait",
10318
- "wait_for_selector",
10319
- "wait_for_text",
10320
- "window_eval",
10321
- "window_call",
10322
- "window_call_until"
10323
- ];
10324
- var RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES = [
10325
- "aborted",
10326
- "accessdenied",
10327
- "addressunreachable",
10328
- "blockedbyclient",
10329
- "blockedbyresponse",
10330
- "connectionaborted",
10331
- "connectionclosed",
10332
- "connectionfailed",
10333
- "connectionrefused",
10334
- "connectionreset",
10335
- "internetdisconnected",
10336
- "namenotresolved",
10337
- "timedout",
10338
- "failed"
10339
- ];
10340
- var RIDDLE_PROOF_ORDERED_TRACE_OPERATORS = [
10341
- "exists",
10342
- "equals",
10343
- "not_equals",
10344
- "truthy",
10345
- "falsy",
10346
- "gt",
10347
- "gte",
10348
- "lt",
10349
- "lte",
10350
- "abs_gt",
10351
- "abs_gte",
10352
- "abs_lt",
10353
- "abs_lte"
10354
- ];
10355
- function uniqueNonEmptyStrings(values) {
10356
- const seen = /* @__PURE__ */ new Set();
10357
- const result = [];
10358
- for (const value of values ?? []) {
10359
- const normalized = typeof value === "string" ? value.trim() : "";
10360
- if (!normalized || seen.has(normalized)) continue;
10361
- seen.add(normalized);
10362
- result.push(normalized);
10363
- }
10364
- return result;
10365
- }
10366
- function deriveRiddleProofArtifactBodyAssertions(input) {
10367
- const artifactText = typeof input.artifact_text === "string" ? input.artifact_text : "";
10368
- const candidates = uniqueNonEmptyStrings(input.candidates);
10369
- const required = uniqueNonEmptyStrings(input.required);
10370
- const mergedCandidates = uniqueNonEmptyStrings([...required, ...candidates]);
10371
- const presentCandidates = mergedCandidates.filter((snippet) => artifactText.includes(snippet));
10372
- const missingCandidates = mergedCandidates.filter((snippet) => !artifactText.includes(snippet));
10373
- const missingRequired = required.filter((snippet) => !artifactText.includes(snippet));
10374
- const warnings = missingCandidates.map((snippet) => `candidate snippet is not present in artifact body: ${snippet}`);
10375
- return {
10376
- version: "riddle-proof.artifact-body-assertions.v1",
10377
- ok: missingRequired.length === 0,
10378
- body_contains: presentCandidates,
10379
- present_candidates: presentCandidates,
10380
- missing_candidates: missingCandidates,
10381
- missing_required: missingRequired,
10382
- warnings
10383
- };
10384
- }
10385
- var DEFAULT_VIEWPORTS = [
10386
- { name: "desktop", width: 1280, height: 800 }
10387
- ];
10279
+ var import_profile2 = require("@riddledc/riddle-proof-core/profile");
10280
+
10281
+ // src/profile-capabilities.ts
10282
+ var import_profile = require("@riddledc/riddle-proof-core/profile");
10388
10283
  function isRecord2(value) {
10389
10284
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
10390
10285
  }
@@ -10394,113 +10289,12 @@ function stringValue6(value) {
10394
10289
  function hasOwn(value, key) {
10395
10290
  return Object.prototype.hasOwnProperty.call(value, key);
10396
10291
  }
10397
- function stringFromOwn(input, ...keys) {
10398
- for (const key of keys) {
10399
- if (hasOwn(input, key)) {
10400
- const value = input[key];
10401
- if (value !== void 0 && value !== null) return String(value);
10402
- }
10403
- }
10404
- return void 0;
10405
- }
10406
- function valueFromOwn(input, ...keys) {
10407
- for (const key of keys) {
10408
- if (hasOwn(input, key)) return input[key];
10409
- }
10410
- return void 0;
10411
- }
10412
10292
  function numberValue4(value) {
10413
10293
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
10414
10294
  }
10415
10295
  function booleanValue2(value) {
10416
10296
  return typeof value === "boolean" ? value : void 0;
10417
10297
  }
10418
- function horizontalBoundsOverflowPx2(value) {
10419
- if (!isRecord2(value)) return 0;
10420
- let max = maxPositiveNumber2(
10421
- value.overflow_px,
10422
- value.overflow,
10423
- value.bounds_overflow_px,
10424
- value.horizontal_overflow_px,
10425
- value.left_overflow_px,
10426
- value.right_overflow_px
10427
- );
10428
- for (const offender of boundsOffendersForEvidence2(value)) {
10429
- max = Math.max(max, horizontalOffenderOverflowPx2(offender));
10430
- }
10431
- return roundPixels2(max);
10432
- }
10433
- function horizontalOffenderOverflowPx2(value) {
10434
- if (!isRecord2(value)) return 0;
10435
- let max = maxPositiveNumber2(
10436
- value.overflow,
10437
- value.overflow_px,
10438
- value.bounds_overflow_px,
10439
- value.horizontal_overflow_px,
10440
- value.left_overflow_px,
10441
- value.right_overflow_px,
10442
- value.leftOverflowPx,
10443
- value.rightOverflowPx
10444
- );
10445
- const clipped = isRecord2(value.clipped || value.clip || value.clipping) ? value.clipped || value.clip || value.clipping : void 0;
10446
- if (isRecord2(clipped)) {
10447
- max = Math.max(max, maxPositiveNumber2(
10448
- clipped.left,
10449
- clipped.right,
10450
- clipped.left_px,
10451
- clipped.right_px,
10452
- clipped.leftPx,
10453
- clipped.rightPx
10454
- ));
10455
- }
10456
- const rect = isRecord2(value.rect || value.bounds || value.bounding_rect || value.boundingRect) ? value.rect || value.bounds || value.bounding_rect || value.boundingRect : void 0;
10457
- const viewportWidth = numberValue4(value.viewport_width ?? value.viewportWidth);
10458
- if (isRecord2(rect) && viewportWidth !== void 0) {
10459
- const left = numberValue4(rect.left);
10460
- const right = numberValue4(rect.right);
10461
- if (left !== void 0 && left < 0) max = Math.max(max, Math.abs(left));
10462
- if (right !== void 0 && right > viewportWidth) max = Math.max(max, right - viewportWidth);
10463
- }
10464
- return roundPixels2(max);
10465
- }
10466
- function boundsOffendersForEvidence2(value) {
10467
- if (!isRecord2(value)) return [];
10468
- const offenders = [
10469
- ...Array.isArray(value.overflow_offenders) ? value.overflow_offenders : [],
10470
- ...Array.isArray(value.overflowOffenders) ? value.overflowOffenders : [],
10471
- ...Array.isArray(value.bounds_offenders) ? value.bounds_offenders : [],
10472
- ...Array.isArray(value.boundsOffenders) ? value.boundsOffenders : [],
10473
- ...Array.isArray(value.clipped_elements) ? value.clipped_elements : [],
10474
- ...Array.isArray(value.clippedElements) ? value.clippedElements : [],
10475
- ...Array.isArray(value.clipping_offenders) ? value.clipping_offenders : [],
10476
- ...Array.isArray(value.clippingOffenders) ? value.clippingOffenders : []
10477
- ];
10478
- return offenders.filter((item) => isRecord2(item)).sort((a, b) => horizontalOffenderOverflowPx2(b) - horizontalOffenderOverflowPx2(a));
10479
- }
10480
- function maxPositiveNumber2(...values) {
10481
- let max = 0;
10482
- for (const value of values) {
10483
- const number = numberValue4(value);
10484
- if (number !== void 0 && number > max) max = number;
10485
- }
10486
- return max;
10487
- }
10488
- function roundPixels2(value) {
10489
- return Math.round(value * 100) / 100;
10490
- }
10491
- function timeoutSecValue(value) {
10492
- const number = numberValue4(value);
10493
- return number && number > 0 ? Math.ceil(number) : void 0;
10494
- }
10495
- function jsonRecord(value) {
10496
- if (!isRecord2(value)) return void 0;
10497
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, toJsonValue(child)]));
10498
- }
10499
- function stringRecord(value) {
10500
- if (!isRecord2(value)) return void 0;
10501
- const entries = Object.entries(value).map(([key, child]) => [key, String(child)]).filter(([key]) => key.trim());
10502
- return entries.length ? Object.fromEntries(entries) : void 0;
10503
- }
10504
10298
  function toJsonValue(value) {
10505
10299
  if (value === null || value === void 0) return null;
10506
10300
  if (typeof value === "string" || typeof value === "boolean") return value;
@@ -10643,185 +10437,6 @@ function resolveJsonPath(root, path5) {
10643
10437
  }
10644
10438
  return { exists: true, value: current };
10645
10439
  }
10646
- function assessRiddleProofOrderedTrace(trace, events) {
10647
- const insufficient = (reason, traceLength = Array.isArray(trace) ? trace.length : 0, witnesses2 = [], missingEvent, missingPaths) => ({
10648
- version: "riddle-proof.ordered-trace-assessment.v1",
10649
- status: "proof_insufficient",
10650
- trace_length: traceLength,
10651
- witnesses: witnesses2,
10652
- missing_event: missingEvent,
10653
- missing_paths: missingPaths,
10654
- reason
10655
- });
10656
- const parsePath = (path5) => {
10657
- const segments = [];
10658
- let token = "";
10659
- const pushToken = () => {
10660
- const value = token.trim();
10661
- if (value) segments.push(value);
10662
- token = "";
10663
- };
10664
- for (let index = 0; index < path5.length; index += 1) {
10665
- const char = path5[index];
10666
- if (char === ".") {
10667
- pushToken();
10668
- continue;
10669
- }
10670
- if (char !== "[") {
10671
- token += char;
10672
- continue;
10673
- }
10674
- pushToken();
10675
- const closeIndex = path5.indexOf("]", index + 1);
10676
- if (closeIndex === -1) throw new Error(`unterminated bracket at ${index}`);
10677
- const bracket = path5.slice(index + 1, closeIndex).trim();
10678
- if (!bracket) throw new Error(`empty bracket at ${index}`);
10679
- if (/^\d+$/.test(bracket)) {
10680
- segments.push(Number(bracket));
10681
- } else {
10682
- segments.push(bracket.replace(/^['"]|['"]$/g, ""));
10683
- }
10684
- index = closeIndex;
10685
- }
10686
- pushToken();
10687
- return segments;
10688
- };
10689
- const resolve = (root, path5) => {
10690
- let segments;
10691
- try {
10692
- segments = parsePath(path5);
10693
- } catch {
10694
- return { exists: false };
10695
- }
10696
- let current = root;
10697
- for (const segment of segments) {
10698
- if (Array.isArray(current)) {
10699
- const index = typeof segment === "number" ? segment : /^\d+$/.test(segment) ? Number(segment) : -1;
10700
- if (index < 0 || index >= current.length) return { exists: false };
10701
- current = current[index];
10702
- continue;
10703
- }
10704
- if (typeof segment !== "string" || current === null || typeof current !== "object") return { exists: false };
10705
- if (!Object.hasOwn(current, segment)) return { exists: false };
10706
- current = current[segment];
10707
- }
10708
- return { exists: true, value: current };
10709
- };
10710
- const valuesEqual = (left, right) => {
10711
- if (Object.is(left, right)) return true;
10712
- if (Array.isArray(left) || Array.isArray(right)) {
10713
- return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => valuesEqual(value, right[index]));
10714
- }
10715
- if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;
10716
- const leftRecord = left;
10717
- const rightRecord = right;
10718
- const leftKeys = Object.keys(leftRecord).sort();
10719
- const rightKeys = Object.keys(rightRecord).sort();
10720
- return leftKeys.length === rightKeys.length && leftKeys.every((key, index) => key === rightKeys[index] && valuesEqual(leftRecord[key], rightRecord[key]));
10721
- };
10722
- const numericOperator = (op) => [
10723
- "gt",
10724
- "gte",
10725
- "lt",
10726
- "lte",
10727
- "abs_gt",
10728
- "abs_gte",
10729
- "abs_lt",
10730
- "abs_lte"
10731
- ].includes(op);
10732
- const matches = (value, predicate) => {
10733
- if (predicate.op === "exists") return true;
10734
- if (predicate.op === "equals") return valuesEqual(value, predicate.value);
10735
- if (predicate.op === "not_equals") return !valuesEqual(value, predicate.value);
10736
- if (predicate.op === "truthy") return Boolean(value);
10737
- if (predicate.op === "falsy") return !value;
10738
- const observed = typeof value === "number" ? value : Number.NaN;
10739
- const expected = typeof predicate.value === "number" ? predicate.value : Number.NaN;
10740
- if (!Number.isFinite(observed) || !Number.isFinite(expected)) return false;
10741
- const candidate = predicate.op.startsWith("abs_") ? Math.abs(observed) : observed;
10742
- if (predicate.op === "gt" || predicate.op === "abs_gt") return candidate > expected;
10743
- if (predicate.op === "gte" || predicate.op === "abs_gte") return candidate >= expected;
10744
- if (predicate.op === "lt" || predicate.op === "abs_lt") return candidate < expected;
10745
- return candidate <= expected;
10746
- };
10747
- if (!Array.isArray(trace) || trace.length === 0) return insufficient("trace_missing_or_empty");
10748
- if (!Array.isArray(events) || events.length === 0) return insufficient("events_missing", trace.length);
10749
- for (const event of events) {
10750
- const missingPaths = event.predicates.filter((predicate) => !trace.some((sample) => {
10751
- const resolved = resolve(sample, predicate.path);
10752
- return resolved.exists && (!numericOperator(predicate.op) || typeof resolved.value === "number" && Number.isFinite(resolved.value));
10753
- })).map((predicate) => predicate.path);
10754
- if (missingPaths.length) {
10755
- return insufficient("required_trace_field_missing", trace.length, [], event.label, Array.from(new Set(missingPaths)));
10756
- }
10757
- }
10758
- const witnesses = [];
10759
- let cursor = 0;
10760
- for (const event of events) {
10761
- let witnessIndex = -1;
10762
- for (let index = cursor; index < trace.length; index += 1) {
10763
- if (event.predicates.every((predicate) => {
10764
- const resolved = resolve(trace[index], predicate.path);
10765
- return resolved.exists && matches(resolved.value, predicate);
10766
- })) {
10767
- witnessIndex = index;
10768
- break;
10769
- }
10770
- }
10771
- if (witnessIndex < 0) {
10772
- return {
10773
- version: "riddle-proof.ordered-trace-assessment.v1",
10774
- status: "failed",
10775
- trace_length: trace.length,
10776
- witnesses,
10777
- missing_event: event.label,
10778
- reason: "ordered_event_not_observed"
10779
- };
10780
- }
10781
- witnesses.push({
10782
- label: event.label,
10783
- index: witnessIndex,
10784
- observations: event.predicates.map((predicate) => {
10785
- const observed = resolve(trace[witnessIndex], predicate.path).value;
10786
- return {
10787
- path: predicate.path,
10788
- op: predicate.op,
10789
- expected: predicate.value,
10790
- observed
10791
- };
10792
- })
10793
- });
10794
- cursor = witnessIndex + 1;
10795
- }
10796
- return {
10797
- version: "riddle-proof.ordered-trace-assessment.v1",
10798
- status: "passed",
10799
- trace_length: trace.length,
10800
- witnesses
10801
- };
10802
- }
10803
- function assessRiddleProofOrderedTraceSetupResults(results, setupActionLabel, tracePath, events) {
10804
- const insufficient = (reason) => ({
10805
- version: "riddle-proof.ordered-trace-assessment.v1",
10806
- status: "proof_insufficient",
10807
- trace_length: 0,
10808
- witnesses: [],
10809
- reason
10810
- });
10811
- if (!Array.isArray(results)) return insufficient("setup_results_missing");
10812
- const source = results.find((item) => item && typeof item === "object" && !Array.isArray(item) && item.label === setupActionLabel);
10813
- if (!source) return insufficient("setup_action_result_missing");
10814
- if (!Object.hasOwn(source, "returned")) return insufficient("setup_action_return_missing");
10815
- const segments = tracePath.split(".").map((segment) => segment.trim()).filter(Boolean);
10816
- let trace = source.returned;
10817
- for (const segment of segments) {
10818
- if (trace === null || typeof trace !== "object" || Array.isArray(trace) || !Object.hasOwn(trace, segment)) {
10819
- return insufficient("trace_path_missing");
10820
- }
10821
- trace = trace[segment];
10822
- }
10823
- return assessRiddleProofOrderedTrace(trace, events);
10824
- }
10825
10440
  function evaluateHttpStatusBodyJsonAssertion(root, assertion) {
10826
10441
  const resolved = resolveJsonPath(root, assertion.path);
10827
10442
  const errors = [];
@@ -10877,3498 +10492,290 @@ function evaluateHttpStatusBodyJsonAssertions(bodyText, assertions) {
10877
10492
  }
10878
10493
  return expected.map((assertion) => evaluateHttpStatusBodyJsonAssertion(parsed, assertion));
10879
10494
  }
10880
- function compactProfileSetupSummaryText(value, limit = 160) {
10881
- const text = typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
10882
- if (!text) return void 0;
10883
- if (text.length <= limit) return text;
10884
- return `${text.slice(0, Math.max(0, limit - 15)).trimEnd()}... (${text.length} chars)`;
10885
- }
10886
- function profileSetupResultAction(value) {
10887
- const action = value.action ?? value.type;
10888
- return typeof action === "string" && action ? action : "unknown";
10495
+ function checkLabel(check) {
10496
+ return check.label || check.type;
10889
10497
  }
10890
- function profileSetupFrameUrls(viewport) {
10891
- const urls = [];
10892
- const frames = viewport.frames || {};
10893
- for (const container of Object.values(frames)) {
10894
- if (!isRecord2(container) || !Array.isArray(container.frames)) continue;
10895
- for (const frame of container.frames) {
10896
- if (!isRecord2(frame)) continue;
10897
- const url = typeof frame.url === "string" ? frame.url : void 0;
10898
- if (url && !urls.includes(url)) urls.push(url);
10498
+ function httpStatusRequestUrl(check, baseUrl) {
10499
+ const rawUrl = check.url || "";
10500
+ if (!rawUrl) return "";
10501
+ try {
10502
+ if (baseUrl && rawUrl.startsWith("/") && !rawUrl.startsWith("//")) {
10503
+ const base = new URL(baseUrl);
10504
+ const mountPrefix = previewMountPrefix(base.pathname);
10505
+ if (mountPrefix) {
10506
+ const requested = new URL(rawUrl, base.origin);
10507
+ base.pathname = joinMountedRoutePath(mountPrefix, requested.pathname);
10508
+ base.search = requested.search;
10509
+ base.hash = requested.hash;
10510
+ return base.href;
10511
+ }
10899
10512
  }
10513
+ return baseUrl ? new URL(rawUrl, baseUrl).href : new URL(rawUrl).href;
10514
+ } catch {
10515
+ return rawUrl;
10900
10516
  }
10901
- return urls.slice(0, 10);
10902
- }
10903
- function profileSetupActionCounts(results) {
10904
- const counts = {};
10905
- for (const result of results) {
10906
- const action = profileSetupResultAction(result);
10907
- counts[action] = (counts[action] || 0) + 1;
10908
- }
10909
- return toJsonValue(counts);
10910
10517
  }
10911
- function profileSetupScreenshotLabels(results) {
10912
- return results.filter((result) => profileSetupResultAction(result) === "screenshot" && result.ok !== false && typeof result.screenshot_label === "string").map((result) => result.screenshot_label).filter(Boolean);
10518
+ function httpStatusMethod(check) {
10519
+ return (check.method || "GET").toUpperCase();
10913
10520
  }
10914
- function profileSetupWindowCallUntilReceipts(results) {
10915
- return results.filter((result) => profileSetupResultAction(result) === "window_call_until").map((result) => ({
10916
- ordinal: result.ordinal ?? null,
10917
- ok: result.ok !== false,
10918
- path: result.path ?? null,
10919
- until_path: result.until_path ?? null,
10920
- until_value: result.until_value ?? null,
10921
- until_expected_value: result.until_expected_value ?? null,
10922
- call_count: result.call_count ?? null,
10923
- max_calls: result.max_calls ?? null,
10924
- reason: result.reason ?? result.error ?? null
10925
- }));
10521
+ function httpStatusAllowedStatuses(check) {
10522
+ if (check.allowed_statuses?.length) return check.allowed_statuses;
10523
+ if (check.expected_status !== void 0) return [check.expected_status];
10524
+ return void 0;
10926
10525
  }
10927
- function profileSetupWindowCallReceipts(results) {
10928
- return results.filter((result) => profileSetupResultAction(result) === "window_call").map((result) => {
10929
- const receipt = {
10930
- ordinal: result.ordinal ?? null,
10931
- label: result.label ?? null,
10932
- ok: result.ok !== false,
10933
- path: result.path ?? null,
10934
- return_captured: result.return_captured ?? null,
10935
- return_stored_to: result.return_stored_to ?? null,
10936
- reason: result.reason ?? result.store_reason ?? null
10937
- };
10938
- if (result.error !== void 0) receipt.error = result.error;
10939
- if (result.returned !== void 0) receipt.returned = result.returned;
10940
- if (result.expected_return !== void 0) receipt.expected_return = result.expected_return;
10941
- const returnSummary = profileSetupReturnSummary(result);
10942
- if (returnSummary.length) receipt.return_summary = returnSummary;
10943
- return receipt;
10944
- });
10526
+ function httpStatusIsAllowed(status, check) {
10527
+ if (status === void 0) return false;
10528
+ const allowed = httpStatusAllowedStatuses(check);
10529
+ return allowed?.length ? allowed.includes(status) : status >= 200 && status < 400;
10945
10530
  }
10946
- function profileSetupWindowEvalReceipts(results) {
10947
- return results.filter((result) => profileSetupResultAction(result) === "window_eval").map((result) => {
10948
- const receipt = {
10949
- ordinal: result.ordinal ?? null,
10950
- label: result.label ?? null,
10951
- ok: result.ok !== false,
10952
- script_length: result.script_length ?? null,
10953
- return_captured: result.return_captured ?? null,
10954
- return_stored_to: result.return_stored_to ?? null,
10955
- reason: result.reason ?? result.store_reason ?? null
10956
- };
10957
- if (result.error !== void 0) receipt.error = result.error;
10958
- if (result.returned !== void 0) receipt.returned = result.returned;
10959
- if (result.expected_return !== void 0) receipt.expected_return = result.expected_return;
10960
- const returnSummary = profileSetupReturnSummary(result);
10961
- if (returnSummary.length) receipt.return_summary = returnSummary;
10962
- return receipt;
10963
- });
10531
+ function linkStatusObservedBytes(result) {
10532
+ const bytes = numberValue4(result.bytes);
10533
+ const contentLength = numberValue4(result.content_length);
10534
+ return Math.max(bytes ?? 0, contentLength ?? 0) || void 0;
10964
10535
  }
10965
- function profileSetupDeterministicRuntimeReceipts(results) {
10966
- return results.filter((result) => profileSetupResultAction(result) === "deterministic_runtime").map((result) => ({
10967
- ordinal: result.ordinal ?? null,
10968
- ok: result.ok !== false,
10969
- random_enabled: result.random_enabled ?? null,
10970
- random_queue_added: result.random_queue_added ?? null,
10971
- random_queue_length: result.random_queue_length ?? null,
10972
- random_queue_mode: result.random_queue_mode ?? null,
10973
- random_underflow_count: result.random_underflow_count ?? null,
10974
- clock_enabled: result.clock_enabled ?? null,
10975
- previous_now: result.previous_now ?? null,
10976
- now: result.now ?? null,
10977
- advance_ms: result.advance_ms ?? null,
10978
- restored: result.restored ?? null,
10979
- reason: result.reason ?? result.error ?? null
10980
- }));
10536
+ function normalizeLinkStatusContentType(value) {
10537
+ const normalized = value?.split(";")[0]?.trim().toLowerCase();
10538
+ return normalized || void 0;
10981
10539
  }
10982
- function profileSetupReturnSummaryFields(result) {
10983
- const input = result.return_summary_fields;
10984
- if (!Array.isArray(input)) return [];
10985
- const fields = [];
10986
- for (const item of input) {
10987
- if (typeof item === "string") {
10988
- const path6 = item.trim();
10989
- if (path6) fields.push({ path: path6 });
10990
- continue;
10991
- }
10992
- if (!isRecord2(item)) continue;
10993
- const path5 = stringValue6(item.path) ?? stringValue6(item.key) ?? stringValue6(item.json_path) ?? stringValue6(item.jsonPath);
10994
- if (!path5) continue;
10995
- const label = stringValue6(item.label) ?? stringValue6(item.name) ?? stringValue6(item.title);
10996
- fields.push(label ? { path: path5, label } : { path: path5 });
10997
- }
10998
- return fields;
10540
+ function linkStatusContentTypesMatch(actual, expected) {
10541
+ if (!actual || !expected) return false;
10542
+ if (expected.endsWith("/*")) return actual.startsWith(expected.slice(0, -1));
10543
+ if (actual === expected) return true;
10544
+ const yamlTypes = /* @__PURE__ */ new Set(["application/yaml", "application/x-yaml", "text/yaml", "text/x-yaml"]);
10545
+ return yamlTypes.has(actual) && yamlTypes.has(expected);
10999
10546
  }
11000
- function profileSetupReturnSummary(result) {
11001
- if (result.returned === void 0) return [];
11002
- return profileSetupReturnSummaryFields(result).map((field) => {
11003
- const resolved = resolveJsonPath(result.returned, field.path);
11004
- const receipt = {
11005
- label: field.label || field.path,
11006
- path: field.path,
11007
- exists: resolved.exists
11008
- };
11009
- if (resolved.exists) receipt.value = toJsonValue(resolved.value);
11010
- if (resolved.error) receipt.reason = resolved.error;
11011
- return receipt;
10547
+ function linkStatusContentTypeOk(result, check) {
10548
+ const expected = check.allowed_content_types;
10549
+ if (!expected?.length) return true;
10550
+ const actual = normalizeLinkStatusContentType(stringValue6(result.content_type));
10551
+ if (!actual) return false;
10552
+ return expected.some((contentType) => {
10553
+ const normalized = normalizeLinkStatusContentType(contentType);
10554
+ if (!normalized) return false;
10555
+ return linkStatusContentTypesMatch(actual, normalized);
11012
10556
  });
11013
10557
  }
11014
- function profileSetupRangeValueReceipts(results) {
11015
- return results.filter((result) => profileSetupResultAction(result) === "set_range_value").map((result) => ({
11016
- ordinal: result.ordinal ?? null,
11017
- ok: result.ok !== false,
11018
- selector: result.selector ?? null,
11019
- frame_selector: result.frame_selector ?? null,
11020
- requested_value: result.requested_value ?? null,
11021
- actual_value: result.actual_value ?? null,
11022
- before_value: result.before_value ?? null,
11023
- value_as_number: result.value_as_number ?? null,
11024
- min: result.min ?? null,
11025
- max: result.max ?? null,
11026
- step: result.step ?? null,
11027
- reason: result.reason ?? result.error ?? null
11028
- }));
11029
- }
11030
- function profileSetupDragReceipts(results) {
11031
- return results.filter((result) => profileSetupResultAction(result) === "drag").map((result) => ({
11032
- ordinal: result.ordinal ?? null,
11033
- ok: result.ok !== false,
11034
- selector: result.selector ?? null,
11035
- frame_selector: result.frame_selector ?? null,
11036
- pointer_type: result.pointer_type ?? null,
11037
- input_dispatch: result.input_dispatch ?? null,
11038
- coordinate_mode: result.coordinate_mode ?? null,
11039
- from_x: result.from_x ?? null,
11040
- from_y: result.from_y ?? null,
11041
- to_x: result.to_x ?? null,
11042
- to_y: result.to_y ?? null,
11043
- steps: result.steps ?? null,
11044
- duration_ms: result.duration_ms ?? null,
11045
- reason: result.reason ?? result.error ?? null
11046
- }));
11047
- }
11048
- function profileSetupTapReceipts(results) {
11049
- return results.filter((result) => profileSetupResultAction(result) === "tap").map((result) => ({
11050
- ordinal: result.ordinal ?? null,
11051
- ok: result.ok !== false,
11052
- selector: result.selector ?? null,
11053
- frame_selector: result.frame_selector ?? null,
11054
- pointer_type: result.pointer_type ?? null,
11055
- input_dispatch: result.input_dispatch ?? null,
11056
- coordinate_mode: result.coordinate_mode ?? null,
11057
- x: result.x ?? null,
11058
- y: result.y ?? null,
11059
- duration_ms: result.duration_ms ?? null,
11060
- reason: result.reason ?? result.error ?? null
11061
- }));
11062
- }
11063
- function profileSetupTapUntilReceipts(results) {
11064
- return results.filter((result) => profileSetupResultAction(result) === "tap_until").map((result) => ({
11065
- ordinal: result.ordinal ?? null,
11066
- ok: result.ok !== false,
11067
- selector: result.selector ?? null,
11068
- frame_selector: result.frame_selector ?? null,
11069
- pointer_type: result.pointer_type ?? null,
11070
- input_dispatch: result.input_dispatch ?? null,
11071
- coordinate_mode: result.coordinate_mode ?? null,
11072
- x: result.x ?? null,
11073
- y: result.y ?? null,
11074
- duration_ms: result.duration_ms ?? null,
11075
- until_path: result.until_path ?? null,
11076
- until_value: result.until_value ?? null,
11077
- until_expected_value: result.until_expected_value ?? null,
11078
- tap_count: result.tap_count ?? null,
11079
- max_taps: result.max_taps ?? result.max_calls ?? null,
11080
- tap_burst_size: result.tap_burst_size ?? null,
11081
- condition_check_count: result.condition_check_count ?? null,
11082
- settle_ms: result.settle_ms ?? null,
11083
- elapsed_ms: result.elapsed_ms ?? null,
11084
- interval_ms: result.interval_ms ?? null,
11085
- timeout_ms: result.timeout_ms ?? null,
11086
- reason: result.reason ?? result.error ?? null
11087
- }));
10558
+ function httpStatusBodyContainsFailures(result, check) {
10559
+ const expected = check.body_contains?.filter(Boolean) ?? [];
10560
+ if (!expected.length) return [];
10561
+ const observed = isRecord2(result.body_contains) ? result.body_contains : {};
10562
+ return expected.filter((text) => observed[text] !== true);
11088
10563
  }
11089
- function profileSetupKeyboardReceipts(results) {
11090
- return results.filter((result) => ["press", "key_down", "key_up"].includes(profileSetupResultAction(result))).map((result) => ({
11091
- action: profileSetupResultAction(result),
11092
- ordinal: result.ordinal ?? null,
11093
- ok: result.ok !== false,
11094
- selector: result.selector ?? null,
11095
- frame_selector: result.frame_selector ?? null,
11096
- key: result.key ?? null,
11097
- hold_ms: result.hold_ms ?? null,
11098
- reason: result.reason ?? result.error ?? null
11099
- }));
10564
+ function httpStatusBodyNotContainsFailures(result, check) {
10565
+ const forbidden = check.body_not_contains?.filter(Boolean) ?? [];
10566
+ if (!forbidden.length) return [];
10567
+ const observed = isRecord2(result.body_not_contains) ? result.body_not_contains : {};
10568
+ return forbidden.filter((text) => observed[text] !== false);
11100
10569
  }
11101
- function profileSetupCanvasSignatureReceipts(results) {
11102
- return results.filter((result) => profileSetupResultAction(result) === "canvas_signature").map((result) => ({
11103
- ordinal: result.ordinal ?? null,
11104
- ok: result.ok !== false,
11105
- selector: result.selector ?? null,
11106
- frame_selector: result.frame_selector ?? null,
11107
- label: result.label ?? null,
11108
- hash: result.hash ?? null,
11109
- data_length: result.data_length ?? null,
11110
- width: result.width ?? null,
11111
- height: result.height ?? null,
11112
- css_width: result.css_width ?? null,
11113
- css_height: result.css_height ?? null,
11114
- compare_to: result.compare_to ?? null,
11115
- previous_hash: result.previous_hash ?? null,
11116
- changed: result.changed ?? null,
11117
- return_stored_to: result.return_stored_to ?? null,
11118
- reason: result.reason ?? result.error ?? null
11119
- }));
10570
+ function httpStatusBodyNotPatternFailures(result, check) {
10571
+ const forbidden = check.body_not_patterns?.filter(Boolean) ?? [];
10572
+ if (!forbidden.length) return [];
10573
+ const observed = isRecord2(result.body_not_patterns) ? result.body_not_patterns : {};
10574
+ return forbidden.filter((pattern) => observed[pattern] !== false);
11120
10575
  }
11121
- function profileSetupCanvasSignatureStableHashGroups(results) {
11122
- const groups = /* @__PURE__ */ new Map();
11123
- for (const receipt of profileSetupCanvasSignatureReceipts(results)) {
11124
- if (receipt.ok === false) continue;
11125
- const hash = stringValue6(receipt.hash);
11126
- if (!hash) continue;
11127
- const selector = stringValue6(receipt.selector) || "canvas";
11128
- const frameSelector = stringValue6(receipt.frame_selector);
11129
- const key = String(frameSelector || "") + "\n" + selector;
11130
- const group = groups.get(key) || { selector, frame_selector: frameSelector, receipts: [] };
11131
- const ordinal = numberValue4(receipt.ordinal);
11132
- const label = stringValue6(receipt.label) || (ordinal === void 0 ? `capture-${group.receipts.length + 1}` : `#${ordinal}`);
11133
- group.receipts.push({ hash, label, ordinal });
11134
- groups.set(key, group);
11135
- }
11136
- const warnings = [];
11137
- for (const group of groups.values()) {
11138
- const receiptsByHash = /* @__PURE__ */ new Map();
11139
- for (const receipt of group.receipts) {
11140
- const hashReceipts = receiptsByHash.get(receipt.hash) || [];
11141
- hashReceipts.push(receipt);
11142
- receiptsByHash.set(receipt.hash, hashReceipts);
11143
- }
11144
- for (const [hash, receipts] of receiptsByHash.entries()) {
11145
- const labels = [...new Set(receipts.map((receipt) => receipt.label))];
11146
- if (receipts.length < 2 || labels.length < 2) continue;
11147
- const visibleLabels = labels.slice(0, 8);
11148
- warnings.push({
11149
- selector: group.selector,
11150
- frame_selector: group.frame_selector ?? null,
11151
- hash,
11152
- count: receipts.length,
11153
- label_count: labels.length,
11154
- labels: visibleLabels,
11155
- omitted_label_count: Math.max(0, labels.length - visibleLabels.length),
11156
- ordinals: receipts.map((receipt) => receipt.ordinal).filter((value) => value !== void 0).slice(0, 12),
11157
- reason: "stable_canvas_signature_hash"
11158
- });
11159
- }
11160
- }
11161
- return warnings;
11162
- }
11163
- function profileSetupClickSequenceReceipts(clickedItems) {
11164
- const nthChildPattern = /:nth-child\((\d+)\)/;
11165
- const nthChildTemplatePattern = /:nth-child\(\d+\)/g;
11166
- const groups = /* @__PURE__ */ new Map();
11167
- for (const item of clickedItems) {
11168
- const selector = stringValue6(item.selector);
11169
- if (!selector) continue;
11170
- const frameSelector = stringValue6(item.frame_selector);
11171
- const clickCountValue = numberValue4(item.click_count);
11172
- const clickCount = clickCountValue === void 0 ? 1 : Math.max(1, Math.min(100, Math.floor(clickCountValue)));
11173
- const ordinal = numberValue4(item.ordinal);
11174
- const match = nthChildPattern.exec(selector);
11175
- const selectorTemplate = match ? selector.replace(nthChildTemplatePattern, ":nth-child(*)") : selector;
11176
- const valueSource = match ? "nth-child" : "same-selector";
11177
- const key = `${valueSource}
11178
- ${frameSelector || ""}
11179
- ${selectorTemplate}`;
11180
- const group = groups.get(key) || {
11181
- selector_template: selectorTemplate,
11182
- frame_selector: frameSelector,
11183
- value_source: valueSource,
11184
- sequence: [],
11185
- ordinals: [],
11186
- result_count: 0,
11187
- click_total: 0
11188
- };
11189
- if (match) {
11190
- const value = Number(match[1]);
11191
- for (let index = 0; index < clickCount; index += 1) group.sequence.push(value);
11192
- }
11193
- if (ordinal !== void 0) group.ordinals.push(ordinal);
11194
- group.result_count += 1;
11195
- group.click_total += clickCount;
11196
- groups.set(key, group);
11197
- }
11198
- return [...groups.values()].filter((group) => group.result_count >= 4).map((group) => {
11199
- const sequence = group.sequence.slice(0, 32);
11200
- const ordinals = group.ordinals.slice(0, 16);
11201
- return {
11202
- selector_template: group.selector_template,
11203
- frame_selector: group.frame_selector ?? null,
11204
- value_source: group.value_source,
11205
- result_count: group.result_count,
11206
- click_total: group.click_total,
11207
- sequence,
11208
- omitted_sequence_count: Math.max(0, group.sequence.length - sequence.length),
11209
- ordinals,
11210
- omitted_ordinal_count: Math.max(0, group.ordinals.length - ordinals.length)
11211
- };
11212
- });
11213
- }
11214
- function sampleProfileSetupSummaryItems(items, limit) {
11215
- if (items.length <= limit) return items;
11216
- const firstCount = Math.floor(limit / 2);
11217
- const lastCount = limit - firstCount;
11218
- return [...items.slice(0, firstCount), ...items.slice(-lastCount)];
11219
- }
11220
- function profileScreenshotLabels(viewports) {
11221
- const labels = [];
11222
- for (const viewport of viewports || []) {
11223
- if (viewport.screenshot_label) labels.push(viewport.screenshot_label);
11224
- labels.push(...profileSetupScreenshotLabels(viewport.setup_action_results || []));
11225
- }
11226
- return labels;
11227
- }
11228
- function profileFinalScreenshotLabels(viewports) {
11229
- return (viewports || []).map((viewport) => viewport.screenshot_label).filter((label) => typeof label === "string" && Boolean(label.trim()));
11230
- }
11231
- function profileAllSetupScreenshotLabels(viewports) {
11232
- return (viewports || []).flatMap((viewport) => profileSetupScreenshotLabels(viewport.setup_action_results || []));
11233
- }
11234
- function profileSetupSummary(viewports, actionCount, expectedActionCountByViewport, finalScreenshotFullPage) {
11235
- const normalizedFinalScreenshotFullPage = finalScreenshotFullPage === void 0 ? void 0 : finalScreenshotFullPage !== false;
11236
- const finalScreenshotCount = viewports.filter((viewport) => typeof viewport.screenshot_label === "string" && viewport.screenshot_label.trim()).length;
11237
- return toJsonValue({
11238
- viewport_count: viewports.length,
11239
- action_count: actionCount ?? null,
11240
- final_screenshot_count: finalScreenshotCount,
11241
- final_screenshot_full_page: normalizedFinalScreenshotFullPage ?? null,
11242
- final_screenshot_mode: normalizedFinalScreenshotFullPage === void 0 ? null : normalizedFinalScreenshotFullPage ? "full_page" : "viewport",
11243
- viewports: viewports.map((viewport) => {
11244
- const expectedActionCount = expectedActionCountByViewport?.get(viewport.name) ?? actionCount;
11245
- const viewportFinalScreenshotFullPage = typeof viewport.screenshot_full_page === "boolean" ? viewport.screenshot_full_page : normalizedFinalScreenshotFullPage;
11246
- const results = viewport.setup_action_results || [];
11247
- const failed = results.filter((result) => result.ok === false && result.optional !== true);
11248
- const optionalFailed = results.filter((result) => result.ok === false && result.optional === true);
11249
- const successfulClicks = results.filter((result) => profileSetupResultAction(result) === "click" && result.ok !== false);
11250
- const clickCountValues = successfulClicks.map((result) => typeof result.click_count === "number" && Number.isFinite(result.click_count) && result.click_count > 1 ? result.click_count : void 0).filter((value) => value !== void 0);
11251
- const windowCallUntilReceipts = profileSetupWindowCallUntilReceipts(results);
11252
- const windowCallUntilCallCounts = windowCallUntilReceipts.map((result) => typeof result.call_count === "number" && Number.isFinite(result.call_count) ? result.call_count : void 0).filter((value) => value !== void 0);
11253
- const sampledWindowCallUntilReceipts = sampleProfileSetupSummaryItems(windowCallUntilReceipts, 8);
11254
- const windowCallReceipts = profileSetupWindowCallReceipts(results);
11255
- const windowCallStoredTotal = windowCallReceipts.filter((result) => typeof result.return_stored_to === "string" && result.return_stored_to.trim()).length;
11256
- const windowCallCapturedTotal = windowCallReceipts.filter((result) => result.return_captured === true).length;
11257
- const sampledWindowCallReceipts = sampleProfileSetupSummaryItems(windowCallReceipts, 8);
11258
- const windowEvalReceipts = profileSetupWindowEvalReceipts(results);
11259
- const windowEvalStoredTotal = windowEvalReceipts.filter((result) => typeof result.return_stored_to === "string" && result.return_stored_to.trim()).length;
11260
- const windowEvalCapturedTotal = windowEvalReceipts.filter((result) => result.return_captured === true).length;
11261
- const sampledWindowEvalReceipts = sampleProfileSetupSummaryItems(windowEvalReceipts, 8);
11262
- const deterministicRuntimeReceipts = profileSetupDeterministicRuntimeReceipts(results);
11263
- const sampledDeterministicRuntimeReceipts = sampleProfileSetupSummaryItems(deterministicRuntimeReceipts, 8);
11264
- const rangeValueReceipts = profileSetupRangeValueReceipts(results);
11265
- const sampledRangeValueReceipts = sampleProfileSetupSummaryItems(rangeValueReceipts, 8);
11266
- const dragReceipts = profileSetupDragReceipts(results);
11267
- const sampledDragReceipts = sampleProfileSetupSummaryItems(dragReceipts, 8);
11268
- const tapReceipts = profileSetupTapReceipts(results);
11269
- const sampledTapReceipts = sampleProfileSetupSummaryItems(tapReceipts, 8);
11270
- const tapUntilReceipts = profileSetupTapUntilReceipts(results);
11271
- const tapUntilTapCounts = tapUntilReceipts.map((result) => typeof result.tap_count === "number" && Number.isFinite(result.tap_count) ? result.tap_count : void 0).filter((value) => value !== void 0);
11272
- const sampledTapUntilReceipts = sampleProfileSetupSummaryItems(tapUntilReceipts, 8);
11273
- const keyboardReceipts = profileSetupKeyboardReceipts(results);
11274
- const sampledKeyboardReceipts = sampleProfileSetupSummaryItems(keyboardReceipts, 8);
11275
- const canvasSignatureReceipts = profileSetupCanvasSignatureReceipts(results);
11276
- const sampledCanvasSignatureReceipts = sampleProfileSetupSummaryItems(canvasSignatureReceipts, 8);
11277
- const clickedItems = results.filter((result) => profileSetupResultAction(result) === "click" && result.ok !== false).map((result) => {
11278
- const clickCount = typeof result.click_count === "number" && Number.isFinite(result.click_count) && result.click_count > 1 ? result.click_count : void 0;
11279
- return {
11280
- ordinal: result.ordinal ?? null,
11281
- selector: result.selector ?? null,
11282
- frame_selector: result.frame_selector ?? null,
11283
- text: compactProfileSetupSummaryText(result.text),
11284
- ...result.fallback_to_tap === true ? { fallback_to_tap: true } : {},
11285
- ...result.input_dispatch ? { input_dispatch: result.input_dispatch } : {},
11286
- ...result.click_error ? { click_error: compactProfileSetupSummaryText(result.click_error) } : {},
11287
- ...clickCount ? { click_count: clickCount } : {}
11288
- };
11289
- });
11290
- const clicked = sampleProfileSetupSummaryItems(clickedItems, 8);
11291
- const clickSequences = profileSetupClickSequenceReceipts(clickedItems);
11292
- const sampledClickSequences = sampleProfileSetupSummaryItems(clickSequences, 6);
11293
- const text_samples = results.filter((result) => result.ok !== false && typeof result.text === "string" && (profileSetupResultAction(result) === "assert_text_visible" || profileSetupResultAction(result) === "assert_text_absent" || profileSetupResultAction(result) === "wait_for_text")).map((result) => ({
11294
- ordinal: result.ordinal ?? null,
11295
- action: profileSetupResultAction(result),
11296
- frame_selector: result.frame_selector ?? null,
11297
- text: compactProfileSetupSummaryText(result.text)
11298
- })).filter((item) => item.text).slice(-6);
11299
- return {
11300
- name: viewport.name,
11301
- expected_action_count: expectedActionCount ?? null,
11302
- ok: (expectedActionCount === void 0 ? results.length > 0 : results.length >= expectedActionCount) && failed.length === 0,
11303
- result_count: results.length,
11304
- observed_path: viewport.route?.observed ?? null,
11305
- final_url: viewport.url ?? null,
11306
- action_counts: profileSetupActionCounts(results),
11307
- frame_action_count: results.filter((result) => result.frame_selector).length,
11308
- frame_urls: profileSetupFrameUrls(viewport),
11309
- final_screenshot: viewport.screenshot_label ?? null,
11310
- final_screenshot_full_page: viewportFinalScreenshotFullPage ?? null,
11311
- setup_screenshots: profileSetupScreenshotLabels(results),
11312
- clicked_total: clickedItems.length,
11313
- clicked_truncated: clickedItems.length > clicked.length,
11314
- click_sequence_total: clickSequences.length,
11315
- click_sequence_truncated: clickSequences.length > sampledClickSequences.length,
11316
- click_sequences: sampledClickSequences,
11317
- click_count_action_total: clickCountValues.length,
11318
- click_count_value_total: clickCountValues.reduce((sum, value) => sum + value, 0),
11319
- window_call_until_total: windowCallUntilReceipts.length,
11320
- window_call_until_call_total: windowCallUntilCallCounts.reduce((sum, value) => sum + value, 0),
11321
- window_call_until_truncated: windowCallUntilReceipts.length > sampledWindowCallUntilReceipts.length,
11322
- window_call_until: sampledWindowCallUntilReceipts,
11323
- window_call_total: windowCallReceipts.length,
11324
- window_call_stored_total: windowCallStoredTotal,
11325
- window_call_captured_total: windowCallCapturedTotal,
11326
- window_call_truncated: windowCallReceipts.length > sampledWindowCallReceipts.length,
11327
- window_call: sampledWindowCallReceipts,
11328
- window_eval_total: windowEvalReceipts.length,
11329
- window_eval_stored_total: windowEvalStoredTotal,
11330
- window_eval_captured_total: windowEvalCapturedTotal,
11331
- window_eval_truncated: windowEvalReceipts.length > sampledWindowEvalReceipts.length,
11332
- window_eval: sampledWindowEvalReceipts,
11333
- deterministic_runtime_total: deterministicRuntimeReceipts.length,
11334
- deterministic_runtime_truncated: deterministicRuntimeReceipts.length > sampledDeterministicRuntimeReceipts.length,
11335
- deterministic_runtime: sampledDeterministicRuntimeReceipts,
11336
- set_range_value_total: rangeValueReceipts.length,
11337
- set_range_value_truncated: rangeValueReceipts.length > sampledRangeValueReceipts.length,
11338
- set_range_value: sampledRangeValueReceipts,
11339
- drag_total: dragReceipts.length,
11340
- drag_truncated: dragReceipts.length > sampledDragReceipts.length,
11341
- drag: sampledDragReceipts,
11342
- tap_total: tapReceipts.length,
11343
- tap_truncated: tapReceipts.length > sampledTapReceipts.length,
11344
- tap: sampledTapReceipts,
11345
- tap_until_total: tapUntilReceipts.length,
11346
- tap_until_tap_total: tapUntilTapCounts.reduce((sum, value) => sum + value, 0),
11347
- tap_until_truncated: tapUntilReceipts.length > sampledTapUntilReceipts.length,
11348
- tap_until: sampledTapUntilReceipts,
11349
- keyboard_total: keyboardReceipts.length,
11350
- keyboard_truncated: keyboardReceipts.length > sampledKeyboardReceipts.length,
11351
- keyboard: sampledKeyboardReceipts,
11352
- canvas_signature_total: canvasSignatureReceipts.length,
11353
- canvas_signature_truncated: canvasSignatureReceipts.length > sampledCanvasSignatureReceipts.length,
11354
- canvas_signature: sampledCanvasSignatureReceipts,
11355
- canvas_signature_stable_hash_groups: profileSetupCanvasSignatureStableHashGroups(results),
11356
- clicked,
11357
- text_samples,
11358
- failed: failed.map((result) => ({
11359
- ordinal: result.ordinal ?? null,
11360
- action: profileSetupResultAction(result),
11361
- selector: result.selector ?? null,
11362
- frame_selector: result.frame_selector ?? null,
11363
- reason: result.reason ?? result.error ?? null,
11364
- error: result.error ?? null,
11365
- case_insensitive_text: compactProfileSetupSummaryText(result.case_insensitive_text)
11366
- })),
11367
- optional_failed: optionalFailed.map((result) => ({
11368
- ordinal: result.ordinal ?? null,
11369
- action: profileSetupResultAction(result),
11370
- selector: result.selector ?? null,
11371
- frame_selector: result.frame_selector ?? null,
11372
- reason: result.reason ?? result.error ?? null,
11373
- error: result.error ?? null,
11374
- case_insensitive_text: compactProfileSetupSummaryText(result.case_insensitive_text)
11375
- }))
11376
- };
11377
- })
11378
- });
11379
- }
11380
- function normalizeName(value, fallback) {
11381
- const name = stringValue6(value) || fallback;
11382
- return name.replace(/\s+/g, " ").trim();
11383
- }
11384
- function slugifyRiddleProofProfileName(value) {
11385
- return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "profile";
11386
- }
11387
- function normalizeViewport(input, index) {
11388
- if (!isRecord2(input)) throw new Error(`target.viewports[${index}] must be an object.`);
11389
- const width = numberValue4(input.width);
11390
- const height = numberValue4(input.height);
11391
- if (!width || !height || width < 100 || height < 100) {
11392
- throw new Error(`target.viewports[${index}] requires numeric width and height >= 100.`);
11393
- }
11394
- const hasTouch = booleanValue2(valueFromOwn(input, "hasTouch", "has_touch"));
11395
- const isMobile = booleanValue2(valueFromOwn(input, "isMobile", "is_mobile"));
11396
- return {
11397
- name: normalizeName(input.name || input.label, `viewport-${index + 1}`),
11398
- width: Math.round(width),
11399
- height: Math.round(height),
11400
- ...hasTouch === void 0 ? {} : { hasTouch },
11401
- ...isMobile === void 0 ? {} : { isMobile }
11402
- };
11403
- }
11404
- function normalizeViewports(value) {
11405
- if (value === void 0) return [...DEFAULT_VIEWPORTS];
11406
- if (!Array.isArray(value) || value.length === 0) throw new Error("target.viewports must be a non-empty array.");
11407
- return value.map(normalizeViewport);
11408
- }
11409
- function isSupportedCheckType(value) {
11410
- return RIDDLE_PROOF_PROFILE_CHECK_TYPES.includes(value);
11411
- }
11412
- function normalizeSetupActionType(value, index) {
11413
- const normalizedInput = String(value || "").trim().replace(/-/g, "_");
11414
- const normalized = normalizedInput === "clear_browser_storage" ? "clear_storage" : normalizedInput === "reset_console" || normalizedInput === "clear_browser_console" || normalizedInput === "reset_browser_console" ? "clear_console" : normalizedInput === "pointer_drag" || normalizedInput === "mouse_drag" || normalizedInput === "drag_to" ? "drag" : normalizedInput === "pointer_tap" || normalizedInput === "touch_tap" || normalizedInput === "canvas_tap" ? "tap" : normalizedInput === "tap_until" || normalizedInput === "pointer_tap_until" || normalizedInput === "touch_tap_until" || normalizedInput === "canvas_tap_until" || normalizedInput === "tap_repeat_until" || normalizedInput === "repeat_tap_until" ? "tap_until" : normalizedInput === "keyboard_press" || normalizedInput === "key_press" ? "press" : normalizedInput === "keyboard_down" || normalizedInput === "key_down" || normalizedInput === "keydown" || normalizedInput === "press_down" ? "key_down" : normalizedInput === "keyboard_up" || normalizedInput === "key_up" || normalizedInput === "keyup" || normalizedInput === "press_up" || normalizedInput === "release_key" || normalizedInput === "key_release" ? "key_up" : normalizedInput === "set_slider_value" || normalizedInput === "slider_value" || normalizedInput === "set_slider" || normalizedInput === "set_range" || normalizedInput === "range_value" || normalizedInput === "range_input" || normalizedInput === "set_range_input" ? "set_range_value" : normalizedInput === "deterministic_runtime" || normalizedInput === "mock_runtime" || normalizedInput === "mock_random" || normalizedInput === "mock_random_queue" || normalizedInput === "seed_random_queue" || normalizedInput === "set_random_queue" || normalizedInput === "mock_clock" || normalizedInput === "set_mock_clock" || normalizedInput === "set_runtime_determinism" || normalizedInput === "runtime_determinism" ? "deterministic_runtime" : normalizedInput === "canvas_hash" || normalizedInput === "capture_canvas_hash" || normalizedInput === "capture_canvas_signature" || normalizedInput === "canvas_state_signature" ? "canvas_signature" : normalizedInput === "capture_screenshot" || normalizedInput === "save_screenshot" || normalizedInput === "setup_screenshot" ? "screenshot" : normalizedInput === "accept_dialog" || normalizedInput === "accept_dialogs" || normalizedInput === "confirm_dialog" || normalizedInput === "set_dialog_response" ? "dialog_response" : normalizedInput === "dismiss_dialog" || normalizedInput === "dismiss_dialogs" || normalizedInput === "cancel_dialog" ? "dialog_response" : normalizedInput === "window_call_until" || normalizedInput === "call_until" || normalizedInput === "window_call_repeat_until" || normalizedInput === "repeat_window_call_until" ? "window_call_until" : normalizedInput === "window_evaluate" || normalizedInput === "browser_eval" || normalizedInput === "browser_evaluate" || normalizedInput === "evaluate_script" || normalizedInput === "profile_script" ? "window_eval" : normalizedInput;
11415
- if (RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES.includes(normalized)) {
11416
- return normalized;
11417
- }
11418
- throw new Error(`target.setup_actions[${index}].type ${value || "(missing)"} is not supported. Supported actions: ${RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES.join(", ")}`);
11419
- }
11420
- function normalizeSetupActionStorage(value, index) {
11421
- if (value === void 0 || value === null || value === "") return void 0;
11422
- const normalized = String(value).trim().replace(/-/g, "_");
11423
- if (normalized === "local" || normalized === "local_storage") return "local";
11424
- if (normalized === "session" || normalized === "session_storage") return "session";
11425
- if (normalized === "both" || normalized === "all") return "both";
11426
- throw new Error(`target.setup_actions[${index}].storage ${String(value)} is not supported. Supported storage values: local, session, both.`);
11427
- }
11428
- function normalizeSetupActionArgs(input, index) {
11429
- const argsInput = valueFromOwn(input, "args", "arguments", "args_json", "argsJson");
11430
- if (argsInput === void 0) return void 0;
11431
- if (!Array.isArray(argsInput)) {
11432
- throw new Error(`target.setup_actions[${index}] window_call/window_eval args must be an array.`);
11433
- }
11434
- return argsInput.map(toJsonValue);
11435
- }
11436
- function normalizeReturnSummaryFields(input, index) {
11437
- const fieldsInput = valueFromOwn(
11438
- input,
11439
- "return_summary_fields",
11440
- "returnSummaryFields",
11441
- "summary_fields",
11442
- "summaryFields",
11443
- "receipt_fields",
11444
- "receiptFields",
11445
- "return_receipt_fields",
11446
- "returnReceiptFields"
11447
- );
11448
- if (fieldsInput === void 0) return void 0;
11449
- if (!Array.isArray(fieldsInput)) {
11450
- throw new Error(`target.setup_actions[${index}].return_summary_fields must be an array.`);
11451
- }
11452
- return fieldsInput.map((field, fieldIndex) => {
11453
- if (typeof field === "string") {
11454
- const path6 = field.trim();
11455
- if (!path6) throw new Error(`target.setup_actions[${index}].return_summary_fields[${fieldIndex}] requires path.`);
11456
- return { path: path6 };
11457
- }
11458
- if (!isRecord2(field)) {
11459
- throw new Error(`target.setup_actions[${index}].return_summary_fields[${fieldIndex}] must be a string path or object.`);
11460
- }
11461
- const path5 = stringFromOwn(field, "path", "key", "json_path", "jsonPath");
11462
- if (!path5) throw new Error(`target.setup_actions[${index}].return_summary_fields[${fieldIndex}] requires path.`);
11463
- const label = stringFromOwn(field, "label", "name", "title");
11464
- return label ? { path: path5, label } : { path: path5 };
11465
- });
11466
- }
11467
- function normalizeSetupActionRepeat(input, index) {
11468
- const repeat = numberValue4(valueFromOwn(input, "repeat", "repeat_count", "repeatCount", "times"));
11469
- if (repeat === void 0) return void 0;
11470
- if (!Number.isInteger(repeat) || repeat < 1 || repeat > 100) {
11471
- throw new Error(`target.setup_actions[${index}].repeat must be an integer from 1 to 100.`);
11472
- }
11473
- return repeat;
11474
- }
11475
- function normalizeSetupActionClickCount(input, type, index) {
11476
- const clickCountInput = valueFromOwn(input, "click_count", "clickCount", "clicks");
11477
- if (clickCountInput === void 0) return void 0;
11478
- if (type !== "click") {
11479
- throw new Error(`target.setup_actions[${index}].click_count is only supported for click actions.`);
11480
- }
11481
- const clickCount = numberValue4(clickCountInput);
11482
- if (clickCount === void 0 || !Number.isInteger(clickCount) || clickCount < 1 || clickCount > 10) {
11483
- throw new Error(`target.setup_actions[${index}].click_count must be an integer from 1 to 10.`);
11484
- }
11485
- return clickCount;
11486
- }
11487
- function normalizeSetupActionCoordinateMode(value, index) {
11488
- if (value === void 0 || value === null || value === "") return void 0;
11489
- const normalized = String(value).trim().replace(/-/g, "_").toLowerCase();
11490
- if (normalized === "pixels" || normalized === "pixel" || normalized === "px") return "pixels";
11491
- if (normalized === "ratio" || normalized === "relative" || normalized === "fraction") return "ratio";
11492
- throw new Error(`target.setup_actions[${index}].coordinate_mode ${String(value)} is not supported. Supported coordinate modes: pixels, ratio.`);
11493
- }
11494
- function normalizeSetupActionPointerType(value, type, index) {
11495
- if (value === void 0 || value === null || value === "") return void 0;
11496
- if (type !== "drag" && type !== "tap" && type !== "tap_until") {
11497
- throw new Error(`target.setup_actions[${index}].pointer_type is only supported for drag/tap/tap_until actions.`);
11498
- }
11499
- const normalized = String(value).trim().replace(/-/g, "_").toLowerCase();
11500
- if (normalized === "mouse") return "mouse";
11501
- if (normalized === "touch" || normalized === "finger") return "touch";
11502
- if (normalized === "pen" || normalized === "stylus") return "pen";
11503
- throw new Error(`target.setup_actions[${index}].pointer_type ${String(value)} is not supported. Supported pointer types: mouse, touch, pen.`);
11504
- }
11505
- function normalizeSetupActionScreenshotFullPage(input, type, index) {
11506
- const directFullPage = booleanValue2(valueFromOwn(input, "full_page", "fullPage"));
11507
- const viewportOnly = booleanValue2(valueFromOwn(input, "viewport_only", "viewportOnly", "viewport_screenshot", "viewportScreenshot"));
11508
- if (type !== "screenshot") {
11509
- if (directFullPage !== void 0 || viewportOnly !== void 0 || valueFromOwn(input, "screenshot_mode", "screenshotMode", "capture_mode", "captureMode") !== void 0) {
11510
- throw new Error(`target.setup_actions[${index}].full_page is only supported for screenshot actions.`);
11511
- }
11512
- return void 0;
11513
- }
11514
- const modeInput = stringFromOwn(input, "mode", "screenshot_mode", "screenshotMode", "capture_mode", "captureMode");
11515
- let modeFullPage;
11516
- if (modeInput) {
11517
- const mode = modeInput.trim().toLowerCase().replace(/[-\s]+/g, "_");
11518
- if (mode === "full_page" || mode === "fullpage" || mode === "page" || mode === "document") {
11519
- modeFullPage = true;
11520
- } else if (mode === "viewport" || mode === "view") {
11521
- modeFullPage = false;
11522
- } else {
11523
- throw new Error(`target.setup_actions[${index}].mode ${modeInput} is not supported for screenshot actions. Supported modes: full_page, viewport.`);
11524
- }
11525
- }
11526
- const values = [directFullPage, viewportOnly === void 0 ? void 0 : !viewportOnly, modeFullPage].filter((value) => value !== void 0);
11527
- if (!values.length) return void 0;
11528
- if (values.some((value) => value !== values[0])) {
11529
- throw new Error(`target.setup_actions[${index}] has conflicting screenshot full_page / viewport mode options.`);
11530
- }
11531
- return values[0];
11532
- }
11533
- function normalizeSetupActionRandomQueue(input, index) {
11534
- const rawQueue = valueFromOwn(
11535
- input,
11536
- "random_queue",
11537
- "randomQueue",
11538
- "random_values",
11539
- "randomValues",
11540
- "random_sequence",
11541
- "randomSequence",
11542
- "math_random",
11543
- "mathRandom"
11544
- );
11545
- if (rawQueue === void 0) return void 0;
11546
- if (!Array.isArray(rawQueue) || rawQueue.length === 0) {
11547
- throw new Error(`target.setup_actions[${index}].random_queue must be a non-empty array of numbers from 0 inclusive to 1 exclusive.`);
11548
- }
11549
- return rawQueue.map((item, queueIndex) => {
11550
- const value = numberValue4(item);
11551
- if (value === void 0 || value < 0 || value >= 1) {
11552
- throw new Error(`target.setup_actions[${index}].random_queue[${queueIndex}] must be a finite number from 0 inclusive to 1 exclusive.`);
11553
- }
11554
- return value;
11555
- });
11556
- }
11557
- function normalizeSetupActionNonNegativeNumber(input, index, outputKey, ...keys) {
11558
- const rawValue = valueFromOwn(input, ...keys);
11559
- if (rawValue === void 0) return void 0;
11560
- const value = numberValue4(rawValue);
11561
- if (value === void 0 || value < 0) {
11562
- throw new Error(`target.setup_actions[${index}].${outputKey} must be a finite non-negative number.`);
11563
- }
11564
- return value;
11565
- }
11566
- function normalizeSetupAction(input, index) {
11567
- if (!isRecord2(input)) throw new Error(`target.setup_actions[${index}] must be an object.`);
11568
- const type = normalizeSetupActionType(stringValue6(input.type), index);
11569
- const rawType = String(input.type || "").trim().replace(/-/g, "_").toLowerCase();
11570
- const selector = stringValue6(input.selector);
11571
- const frameSelector = stringFromOwn(input, "frame_selector", "frameSelector", "iframe_selector", "iframeSelector");
11572
- const frameIndex = numberValue4(valueFromOwn(input, "frame_index", "frameIndex", "iframe_index", "iframeIndex"));
11573
- if (frameIndex !== void 0 && (!Number.isInteger(frameIndex) || frameIndex < 0)) {
11574
- throw new Error(`target.setup_actions[${index}].frame_index must be a non-negative integer.`);
11575
- }
11576
- if ((type === "click" || type === "tap" || type === "tap_until" || type === "drag" || type === "fill" || type === "set_input_value" || type === "set_range_value" || type === "canvas_signature" || type === "wait_for_selector" || type === "wait_for_text" || type === "assert_text_visible" || type === "assert_text_absent" || type === "assert_selector_count") && !selector) {
11577
- throw new Error(`target.setup_actions[${index}] ${type} requires selector.`);
11578
- }
11579
- const fromX = type === "click" || type === "tap" || type === "tap_until" ? numberValue4(valueFromOwn(input, "from_x", "fromX", "x", "click_x", "clickX", "start_x", "startX", "x1")) : numberValue4(valueFromOwn(input, "from_x", "fromX", "start_x", "startX", "x1"));
11580
- const fromY = type === "click" || type === "tap" || type === "tap_until" ? numberValue4(valueFromOwn(input, "from_y", "fromY", "y", "click_y", "clickY", "start_y", "startY", "y1")) : numberValue4(valueFromOwn(input, "from_y", "fromY", "start_y", "startY", "y1"));
11581
- const toX = numberValue4(valueFromOwn(input, "to_x", "toX", "end_x", "endX", "x2"));
11582
- const toY = numberValue4(valueFromOwn(input, "to_y", "toY", "end_y", "endY", "y2"));
11583
- const coordinateMode = normalizeSetupActionCoordinateMode(valueFromOwn(input, "coordinate_mode", "coordinateMode", "coords", "units"), index);
11584
- const pointerType = normalizeSetupActionPointerType(valueFromOwn(input, "pointer_type", "pointerType", "input_type", "inputType"), type, index);
11585
- const durationMs = numberValue4(input.duration_ms) ?? numberValue4(input.durationMs);
11586
- const holdMs = type === "press" ? normalizeSetupActionNonNegativeNumber(input, index, "hold_ms", "hold_ms", "holdMs", "key_down_ms", "keyDownMs", "down_ms", "downMs") ?? durationMs : void 0;
11587
- if (type === "press" && holdMs !== void 0 && (holdMs < 0 || holdMs > 3e4)) {
11588
- throw new Error(`target.setup_actions[${index}].hold_ms must be a finite number from 0 to 30000.`);
11589
- }
11590
- if (type === "click") {
11591
- const hasClickCoordinate = fromX !== void 0 || fromY !== void 0;
11592
- if (hasClickCoordinate && (fromX === void 0 || fromY === void 0)) {
11593
- throw new Error(`target.setup_actions[${index}] click coordinates require both x and y.`);
11594
- }
11595
- if (hasClickCoordinate && fromX !== void 0 && fromY !== void 0) {
11596
- const clickCoordinates = [fromX, fromY];
11597
- if (coordinateMode === "ratio" && clickCoordinates.some((value2) => value2 < 0 || value2 > 1)) {
11598
- throw new Error(`target.setup_actions[${index}] click ratio coordinates must be between 0 and 1.`);
11599
- }
11600
- if ((coordinateMode === void 0 || coordinateMode === "pixels") && clickCoordinates.some((value2) => value2 < 0)) {
11601
- throw new Error(`target.setup_actions[${index}] click pixel coordinates must be non-negative.`);
11602
- }
11603
- }
11604
- }
11605
- if (type === "tap" || type === "tap_until") {
11606
- const hasTapCoordinate = fromX !== void 0 || fromY !== void 0;
11607
- if (hasTapCoordinate && (fromX === void 0 || fromY === void 0)) {
11608
- throw new Error(`target.setup_actions[${index}] ${type} coordinates require both x and y.`);
11609
- }
11610
- if (hasTapCoordinate && fromX !== void 0 && fromY !== void 0) {
11611
- const tapCoordinates = [fromX, fromY];
11612
- if (coordinateMode === "ratio" && tapCoordinates.some((value2) => value2 < 0 || value2 > 1)) {
11613
- throw new Error(`target.setup_actions[${index}] ${type} ratio coordinates must be between 0 and 1.`);
11614
- }
11615
- if ((coordinateMode === void 0 || coordinateMode === "pixels") && tapCoordinates.some((value2) => value2 < 0)) {
11616
- throw new Error(`target.setup_actions[${index}] ${type} pixel coordinates must be non-negative.`);
11617
- }
11618
- }
11619
- }
11620
- if (type === "drag") {
11621
- if (fromX === void 0 || fromY === void 0 || toX === void 0 || toY === void 0) {
11622
- throw new Error(`target.setup_actions[${index}] drag requires from_x, from_y, to_x, and to_y.`);
11623
- }
11624
- if (coordinateMode === "ratio" && [fromX, fromY, toX, toY].some((value2) => value2 < 0 || value2 > 1)) {
11625
- throw new Error(`target.setup_actions[${index}] drag ratio coordinates must be between 0 and 1.`);
11626
- }
11627
- if ((coordinateMode === void 0 || coordinateMode === "pixels") && [fromX, fromY, toX, toY].some((value2) => value2 < 0)) {
11628
- throw new Error(`target.setup_actions[${index}] drag pixel coordinates must be non-negative.`);
11629
- }
11630
- }
11631
- if (type === "wait_for_text" && !stringValue6(input.text) && !stringValue6(input.pattern)) {
11632
- throw new Error(`target.setup_actions[${index}] wait_for_text requires text or pattern.`);
11633
- }
11634
- if ((type === "assert_text_visible" || type === "assert_text_absent") && !stringValue6(input.text) && !stringValue6(input.pattern)) {
11635
- throw new Error(`target.setup_actions[${index}] ${type} requires text or pattern.`);
11636
- }
11637
- const expectedCount = numberValue4(input.expected_count ?? input.expectedCount ?? input.count);
11638
- if (type === "assert_selector_count" && (expectedCount === void 0 || !Number.isInteger(expectedCount) || expectedCount < 0)) {
11639
- throw new Error(`target.setup_actions[${index}] ${type} requires non-negative integer expected_count.`);
11640
- }
11641
- const value = stringFromOwn(input, "value", "input_value", "inputValue");
11642
- const hasJsonValue = hasOwn(input, "value_json") || hasOwn(input, "valueJson") || hasOwn(input, "json");
11643
- if ((type === "fill" || type === "set_input_value" || type === "set_range_value") && value === void 0 && !hasJsonValue) {
11644
- throw new Error(`target.setup_actions[${index}] ${type} requires value.`);
11645
- }
11646
- const randomQueue = type === "deterministic_runtime" ? normalizeSetupActionRandomQueue(input, index) : void 0;
11647
- const deterministicNow = type === "deterministic_runtime" ? normalizeSetupActionNonNegativeNumber(input, index, "now", "now", "date_now", "dateNow", "mock_now", "mockNow", "clock", "timestamp", "time_ms", "timeMs") : void 0;
11648
- const deterministicAdvanceMs = type === "deterministic_runtime" ? normalizeSetupActionNonNegativeNumber(input, index, "advance_ms", "advance_ms", "advanceMs", "tick_ms", "tickMs", "add_ms", "addMs") : void 0;
11649
- const deterministicAppend = type === "deterministic_runtime" && booleanValue2(valueFromOwn(input, "append", "append_random", "appendRandom")) === true;
11650
- const deterministicRestore = type === "deterministic_runtime" && booleanValue2(valueFromOwn(input, "restore", "reset", "restore_originals", "restoreOriginals")) === true;
11651
- if (type === "deterministic_runtime" && randomQueue === void 0 && deterministicNow === void 0 && deterministicAdvanceMs === void 0 && !deterministicRestore) {
11652
- throw new Error(`target.setup_actions[${index}] deterministic_runtime requires random_queue, now, advance_ms, or restore.`);
11653
- }
11654
- const key = stringValue6(input.key);
11655
- let dialogAccept;
11656
- if (type === "dialog_response") {
11657
- const acceptInput = valueFromOwn(input, "accept", "accepted", "should_accept", "shouldAccept");
11658
- const responseInput = stringFromOwn(input, "response", "dialog_response", "dialogResponse", "mode");
11659
- const response = String(responseInput || "").trim().toLowerCase().replace(/-/g, "_");
11660
- if (acceptInput !== void 0) {
11661
- dialogAccept = acceptInput !== false && String(acceptInput).toLowerCase() !== "false";
11662
- } else if (rawType === "dismiss_dialog" || rawType === "dismiss_dialogs" || rawType === "cancel_dialog") {
11663
- dialogAccept = false;
11664
- } else if (response === "dismiss" || response === "cancel" || response === "reject" || response === "no" || response === "false") {
11665
- dialogAccept = false;
11666
- } else {
11667
- dialogAccept = true;
11668
- }
11669
- }
11670
- if ((type === "press" || type === "key_down" || type === "key_up") && !key) {
11671
- throw new Error(`target.setup_actions[${index}] ${type} requires key.`);
11672
- }
11673
- if ((type === "local_storage" || type === "session_storage") && !key) {
11674
- throw new Error(`target.setup_actions[${index}] ${type} requires key.`);
11675
- }
11676
- if ((type === "local_storage" || type === "session_storage") && value === void 0 && !hasJsonValue) {
11677
- throw new Error(`target.setup_actions[${index}] ${type} requires value.`);
11678
- }
11679
- const path5 = stringFromOwn(input, "path", "function_path", "functionPath", "window_path", "windowPath", "state_path", "statePath");
11680
- if ((type === "window_call" || type === "window_call_until" || type === "assert_window_value" || type === "assert_window_number") && !path5) {
11681
- throw new Error(`target.setup_actions[${index}] ${type} requires path.`);
11682
- }
11683
- const script = stringFromOwn(input, "script", "code", "source", "body");
11684
- if (type === "window_eval" && !script) {
11685
- throw new Error(`target.setup_actions[${index}] window_eval requires script.`);
11686
- }
11687
- const args = type === "window_call" || type === "window_call_until" || type === "window_eval" ? normalizeSetupActionArgs(input, index) : void 0;
11688
- const hasExpectedValue = hasOwn(input, "expected_value") || hasOwn(input, "expectedValue") || hasOwn(input, "expected") || hasOwn(input, "expect_value") || hasOwn(input, "expectValue") || hasOwn(input, "expect");
11689
- if (type === "assert_window_value" && !hasExpectedValue) {
11690
- throw new Error(`target.setup_actions[${index}] ${type} requires expected_value.`);
11691
- }
11692
- const rawExpectedValue = valueFromOwn(input, "expected_value", "expectedValue", "expected", "expect_value", "expectValue", "expect");
11693
- const minValue = numberValue4(valueFromOwn(input, "min_value", "minValue", "minimum", "min", "at_least", "atLeast", "gte"));
11694
- const maxValue = numberValue4(valueFromOwn(input, "max_value", "maxValue", "maximum", "max", "at_most", "atMost", "lte"));
11695
- if (type === "assert_window_number") {
11696
- if (!hasExpectedValue && minValue === void 0 && maxValue === void 0) {
11697
- throw new Error(`target.setup_actions[${index}] ${type} requires expected_value, min_value, or max_value.`);
11698
- }
11699
- if (hasExpectedValue && numberValue4(rawExpectedValue) === void 0) {
11700
- throw new Error(`target.setup_actions[${index}] ${type} expected_value must be a finite number.`);
11701
- }
11702
- }
11703
- const hasExpectedReturn = hasOwn(input, "expect_return") || hasOwn(input, "expectReturn") || hasOwn(input, "expected_return") || hasOwn(input, "expectedReturn");
11704
- const storeReturnTo = stringFromOwn(
11705
- input,
11706
- "store_return_to",
11707
- "storeReturnTo",
11708
- "save_return_to",
11709
- "saveReturnTo",
11710
- "assign_return_to",
11711
- "assignReturnTo",
11712
- "return_state_path",
11713
- "returnStatePath",
11714
- "store_signature_to",
11715
- "storeSignatureTo",
11716
- "signature_path",
11717
- "signaturePath"
11718
- );
11719
- const captureReturn = input.capture_return === false || input.captureReturn === false || input.include_return === false || input.includeReturn === false || input.omit_return === true || input.omitReturn === true ? false : void 0;
11720
- const untilPath = stringFromOwn(input, "until_path", "untilPath", "until_state_path", "untilStatePath", "until_window_path", "untilWindowPath", "until");
11721
- const hasUntilExpectedValue = hasOwn(input, "until_expected_value") || hasOwn(input, "untilExpectedValue") || hasOwn(input, "until_expected") || hasOwn(input, "untilExpected") || hasOwn(input, "until_value") || hasOwn(input, "untilValue") || hasOwn(input, "expected_value") || hasOwn(input, "expectedValue") || hasOwn(input, "expected");
11722
- if (type === "window_call_until" || type === "tap_until") {
11723
- if (!untilPath) {
11724
- throw new Error(`target.setup_actions[${index}] ${type} requires until_path.`);
11725
- }
11726
- if (!hasUntilExpectedValue) {
11727
- throw new Error(`target.setup_actions[${index}] ${type} requires until_expected_value.`);
11728
- }
11729
- }
11730
- const maxCalls = numberValue4(valueFromOwn(input, "max_calls", "maxCalls", "max_attempts", "maxAttempts", "attempts", "max_taps", "maxTaps", "tap_limit", "tapLimit"));
11731
- if ((type === "window_call_until" || type === "tap_until") && (maxCalls === void 0 || !Number.isInteger(maxCalls) || maxCalls < 1 || maxCalls > 100)) {
11732
- throw new Error(`target.setup_actions[${index}].max_calls must be an integer from 1 to 100.`);
11733
- }
11734
- const tapBurstSize = type === "tap_until" ? numberValue4(valueFromOwn(input, "tap_burst_size", "tapBurstSize", "burst_size", "burstSize", "check_every_taps", "checkEveryTaps", "predicate_interval_taps", "predicateIntervalTaps")) : void 0;
11735
- if (type === "tap_until" && tapBurstSize !== void 0 && (!Number.isInteger(tapBurstSize) || tapBurstSize < 1 || tapBurstSize > 100)) {
11736
- throw new Error(`target.setup_actions[${index}].tap_burst_size must be an integer from 1 to 100.`);
11737
- }
11738
- const settleMs = type === "tap_until" ? numberValue4(valueFromOwn(input, "settle_ms", "settleMs", "predicate_settle_ms", "predicateSettleMs", "post_burst_wait_ms", "postBurstWaitMs", "after_burst_ms", "afterBurstMs", "settle_after_tap_ms", "settleAfterTapMs")) : void 0;
11739
- if (type === "tap_until" && settleMs !== void 0 && (!Number.isInteger(settleMs) || settleMs < 0 || settleMs > 1e4)) {
11740
- throw new Error(`target.setup_actions[${index}].settle_ms must be an integer from 0 to 10000.`);
11741
- }
11742
- const intervalMs = numberValue4(valueFromOwn(input, "interval_ms", "intervalMs", "poll_ms", "pollMs", "call_interval_ms", "callIntervalMs"));
11743
- if ((type === "window_call_until" || type === "tap_until") && intervalMs !== void 0 && (!Number.isInteger(intervalMs) || intervalMs < 0 || intervalMs > 5e3)) {
11744
- throw new Error(`target.setup_actions[${index}].interval_ms must be an integer from 0 to 5000.`);
11745
- }
11746
- const steps = numberValue4(input.steps);
11747
- if (type === "drag" && steps !== void 0 && (!Number.isInteger(steps) || steps < 1 || steps > 100)) {
11748
- throw new Error(`target.setup_actions[${index}].steps must be an integer from 1 to 100.`);
11749
- }
11750
- return {
11751
- type,
11752
- selector,
11753
- frame_selector: frameSelector,
11754
- frame_index: frameIndex,
11755
- full_page: normalizeSetupActionScreenshotFullPage(input, type, index),
11756
- force: type === "click" && (input.force === true || input.force_click === true || input.forceClick === true),
11757
- fallback_to_tap: type === "click" && (input.fallback_to_tap === true || input.fallbackToTap === true || input.fallback_to_pointer_tap === true || input.fallbackToPointerTap === true || input.pointer_fallback === true || input.pointerFallback === true) || void 0,
11758
- click_count: normalizeSetupActionClickCount(input, type, index),
11759
- coordinate_mode: coordinateMode,
11760
- pointer_type: pointerType,
11761
- from_x: fromX,
11762
- from_y: fromY,
11763
- to_x: toX,
11764
- to_y: toY,
11765
- duration_ms: durationMs,
11766
- steps,
11767
- key,
11768
- hold_ms: holdMs,
11769
- value,
11770
- value_json: hasJsonValue ? toJsonValue(input.value_json ?? input.valueJson ?? input.json) : void 0,
11771
- random_queue: randomQueue,
11772
- now: deterministicNow,
11773
- advance_ms: deterministicAdvanceMs,
11774
- append: deterministicAppend || void 0,
11775
- restore: deterministicRestore || void 0,
11776
- label: stringFromOwn(input, "label", "name", "screenshot_label", "screenshotLabel"),
11777
- script,
11778
- path: path5,
11779
- args,
11780
- expect_return: hasExpectedReturn ? toJsonValue(valueFromOwn(input, "expect_return", "expectReturn", "expected_return", "expectedReturn")) : void 0,
11781
- store_return_to: storeReturnTo,
11782
- capture_return: captureReturn,
11783
- return_summary_fields: normalizeReturnSummaryFields(input, index),
11784
- compare_to: stringFromOwn(input, "compare_to", "compareTo", "previous_signature_path", "previousSignaturePath", "previous_path", "previousPath", "changed_from", "changedFrom"),
11785
- expect_changed: booleanValue2(valueFromOwn(input, "expect_changed", "expectChanged", "should_change", "shouldChange", "changed")),
11786
- until_path: untilPath,
11787
- until_expected_value: hasUntilExpectedValue ? toJsonValue(valueFromOwn(input, "until_expected_value", "untilExpectedValue", "until_expected", "untilExpected", "until_value", "untilValue", "expected_value", "expectedValue", "expected")) : void 0,
11788
- expected_path: stringFromOwn(input, "expected_path", "expectedPath", "expected_terminal_path", "expectedTerminalPath"),
11789
- expected_url: stringFromOwn(input, "expected_url", "expectedUrl", "expected_terminal_url", "expectedTerminalUrl"),
11790
- max_calls: maxCalls,
11791
- tap_burst_size: tapBurstSize,
11792
- settle_ms: settleMs,
11793
- interval_ms: intervalMs,
11794
- expected_value: hasExpectedValue ? toJsonValue(rawExpectedValue) : void 0,
11795
- min_value: minValue,
11796
- max_value: maxValue,
11797
- text: stringValue6(input.text),
11798
- pattern: stringValue6(input.pattern),
11799
- flags: stringValue6(input.flags),
11800
- accept: dialogAccept,
11801
- prompt_text: stringFromOwn(input, "prompt_text", "promptText", "prompt_value", "promptValue"),
11802
- message_text: stringFromOwn(input, "message_text", "messageText", "dialog_text", "dialogText"),
11803
- message_pattern: stringFromOwn(input, "message_pattern", "messagePattern", "dialog_pattern", "dialogPattern"),
11804
- index: numberValue4(valueFromOwn(input, "index", "target_index", "targetIndex")),
11805
- expected_count: expectedCount,
11806
- ms: numberValue4(input.ms) ?? numberValue4(input.wait_ms) ?? numberValue4(input.waitMs),
11807
- timeout_ms: numberValue4(input.timeout_ms) ?? numberValue4(input.timeoutMs),
11808
- after_ms: numberValue4(input.after_ms) ?? numberValue4(input.afterMs),
11809
- repeat: normalizeSetupActionRepeat(input, index),
11810
- reload: input.reload === true,
11811
- storage: normalizeSetupActionStorage(input.storage, index),
11812
- viewports: normalizeStringList(input.viewports ?? input.viewport_names ?? input.viewportNames, `target.setup_actions[${index}] viewports`),
11813
- optional: input.optional === true || input.required === false,
11814
- continue_on_failure: input.continue_on_failure === true || input.continueOnFailure === true
11815
- };
11816
- }
11817
- function normalizeSetupActions(value) {
11818
- if (value === void 0) return void 0;
11819
- if (!Array.isArray(value)) throw new Error("target.setup_actions must be an array.");
11820
- return value.map(normalizeSetupAction);
11821
- }
11822
- function normalizeTargetScreenshotFullPage(input) {
11823
- const directFullPage = booleanValue2(valueFromOwn(
11824
- input,
11825
- "screenshot_full_page",
11826
- "screenshotFullPage",
11827
- "final_screenshot_full_page",
11828
- "finalScreenshotFullPage",
11829
- "full_page_screenshots",
11830
- "fullPageScreenshots"
11831
- ));
11832
- const viewportOnly = booleanValue2(valueFromOwn(
11833
- input,
11834
- "viewport_screenshots",
11835
- "viewportScreenshots",
11836
- "viewport_only_screenshots",
11837
- "viewportOnlyScreenshots"
11838
- ));
11839
- const modeInput = stringFromOwn(input, "screenshot_mode", "screenshotMode", "final_screenshot_mode", "finalScreenshotMode");
11840
- let modeFullPage;
11841
- if (modeInput) {
11842
- const mode = modeInput.trim().toLowerCase().replace(/[-\s]+/g, "_");
11843
- if (mode === "full_page" || mode === "fullpage" || mode === "page" || mode === "document") {
11844
- modeFullPage = true;
11845
- } else if (mode === "viewport" || mode === "view") {
11846
- modeFullPage = false;
11847
- } else {
11848
- throw new Error(`target.screenshot_mode ${modeInput} is not supported. Supported modes: full_page, viewport.`);
11849
- }
11850
- }
11851
- const values = [directFullPage, viewportOnly === void 0 ? void 0 : !viewportOnly, modeFullPage].filter((value) => value !== void 0);
11852
- if (!values.length) return void 0;
11853
- if (values.some((value) => value !== values[0])) {
11854
- throw new Error("target has conflicting screenshot full_page / viewport mode options.");
11855
- }
11856
- return values[0];
11857
- }
11858
- function normalizeNetworkMock(input, index) {
11859
- if (!isRecord2(input)) throw new Error(`target.network_mocks[${index}] must be an object.`);
11860
- const url = stringValue6(input.url) || stringValue6(input.glob) || stringValue6(input.pattern);
11861
- if (!url) throw new Error(`target.network_mocks[${index}] requires url.`);
11862
- const payload = normalizeNetworkMockResponsePayload(input, `target.network_mocks[${index}]`);
11863
- const responsesInput = input.responses ?? input.sequence;
11864
- const responses = normalizeNetworkMockResponses(responsesInput, index, payload);
11865
- const requestBody = normalizeNetworkMockRequestBodyConstraints(input, `target.network_mocks[${index}]`);
11866
- const requiredHitCount = numberValue4(
11867
- input.required_hit_count ?? input.requiredHitCount ?? input.required_hits ?? input.requiredHits ?? input.min_hits ?? input.minHits
11868
- );
11869
- if (requiredHitCount !== void 0 && (!Number.isInteger(requiredHitCount) || requiredHitCount < 1)) {
11870
- throw new Error(`target.network_mocks[${index}].required_hit_count must be a positive integer.`);
11871
- }
11872
- const forbidden = input.forbidden === true || input.must_not_hit === true || input.mustNotHit === true || input.should_not_run === true || input.shouldNotRun === true;
11873
- const configuredMaxHitCount = numberValue4(
11874
- input.max_hit_count ?? input.maxHitCount ?? input.max_hits ?? input.maxHits
11875
- );
11876
- if (configuredMaxHitCount !== void 0 && (!Number.isInteger(configuredMaxHitCount) || configuredMaxHitCount < 0)) {
11877
- throw new Error(`target.network_mocks[${index}].max_hit_count must be a non-negative integer.`);
11878
- }
11879
- if (forbidden && configuredMaxHitCount !== void 0 && configuredMaxHitCount !== 0) {
11880
- throw new Error(`target.network_mocks[${index}].forbidden cannot be combined with max_hit_count greater than 0.`);
11881
- }
11882
- const maxHitCount = forbidden ? 0 : configuredMaxHitCount;
11883
- const required = input.required === false || maxHitCount === 0 && input.required !== true ? false : true;
11884
- const effectiveRequiredHitCount = required ? requiredHitCount ?? (Array.isArray(responses) && responses.length ? responses.length : 1) : 0;
11885
- if (maxHitCount !== void 0 && effectiveRequiredHitCount > maxHitCount) {
11886
- throw new Error(`target.network_mocks[${index}].max_hit_count cannot be less than its required hit count.`);
11887
- }
11888
- const sequenceScopeInput = stringValue6(
11889
- input.sequence_scope ?? input.sequenceScope ?? input.response_sequence_scope ?? input.responseSequenceScope
11890
- );
11891
- let sequenceScope;
11892
- if (sequenceScopeInput) {
11893
- const normalizedScope = sequenceScopeInput.toLowerCase().replace(/[-\s]+/g, "_");
11894
- if (normalizedScope === "global" || normalizedScope === "profile" || normalizedScope === "run") {
11895
- sequenceScope = "global";
11896
- } else if (normalizedScope === "viewport" || normalizedScope === "per_viewport" || normalizedScope === "viewport_scoped") {
11897
- sequenceScope = "viewport";
11898
- } else {
11899
- throw new Error(`target.network_mocks[${index}].sequence_scope must be "global" or "viewport".`);
11900
- }
11901
- }
11902
- return {
11903
- ...payload,
11904
- label: normalizeName(input.label || input.name, `network-mock-${index + 1}`),
11905
- url,
11906
- method: stringValue6(input.method)?.toUpperCase(),
11907
- responses,
11908
- repeat_responses: input.repeat_responses === true || input.repeatResponses === true || input.cycle_responses === true || input.cycleResponses === true,
11909
- sequence_scope: sequenceScope,
11910
- required_hit_count: requiredHitCount,
11911
- max_hit_count: maxHitCount,
11912
- forbidden,
11913
- required,
11914
- capture_request_body: requestBody.capture_request_body,
11915
- request_body_contains: requestBody.request_body_contains,
11916
- request_body_patterns: requestBody.request_body_patterns,
11917
- request_body_not_contains: requestBody.request_body_not_contains,
11918
- request_body_not_patterns: requestBody.request_body_not_patterns
11919
- };
11920
- }
11921
- function normalizeNetworkMockRequestBodyConstraints(input, label) {
11922
- const requestBodyContains = normalizeStringList(
11923
- input.request_body_contains ?? input.requestBodyContains ?? input.body_contains ?? input.bodyContains,
11924
- `${label}.request_body_contains`
11925
- );
11926
- const requestBodyPatterns = normalizeStringList(
11927
- input.request_body_patterns ?? input.requestBodyPatterns ?? input.body_patterns ?? input.bodyPatterns,
11928
- `${label}.request_body_patterns`
11929
- );
11930
- validateRegexPatterns(requestBodyPatterns, `${label}.request_body_patterns`);
11931
- const requestBodyNotContains = normalizeStringList(
11932
- input.request_body_not_contains ?? input.requestBodyNotContains ?? input.request_body_absent ?? input.requestBodyAbsent ?? input.body_not_contains ?? input.bodyNotContains ?? input.body_absent ?? input.bodyAbsent,
11933
- `${label}.request_body_not_contains`
11934
- );
11935
- const requestBodyNotPatterns = normalizeStringList(
11936
- input.request_body_not_patterns ?? input.requestBodyNotPatterns ?? input.request_body_forbidden_patterns ?? input.requestBodyForbiddenPatterns ?? input.body_not_patterns ?? input.bodyNotPatterns ?? input.body_forbidden_patterns ?? input.bodyForbiddenPatterns,
11937
- `${label}.request_body_not_patterns`
11938
- );
11939
- validateRegexPatterns(requestBodyNotPatterns, `${label}.request_body_not_patterns`);
11940
- return {
11941
- capture_request_body: input.capture_request_body === true || input.captureRequestBody === true || Boolean(requestBodyContains?.length) || Boolean(requestBodyPatterns?.length) || Boolean(requestBodyNotContains?.length) || Boolean(requestBodyNotPatterns?.length),
11942
- request_body_contains: requestBodyContains,
11943
- request_body_patterns: requestBodyPatterns,
11944
- request_body_not_contains: requestBodyNotContains,
11945
- request_body_not_patterns: requestBodyNotPatterns
11946
- };
11947
- }
11948
- function normalizeNetworkMockResponsePayload(input, label, defaults = {}) {
11949
- const status = numberValue4(input.status) ?? defaults.status ?? 200;
11950
- if (!Number.isInteger(status) || status < 100 || status > 599) {
11951
- throw new Error(`${label}.status must be an HTTP status code.`);
11952
- }
11953
- const body = stringValue6(input.body) ?? stringValue6(input.body_text) ?? stringValue6(input.bodyText) ?? defaults.body;
11954
- const hasJsonBody = Object.prototype.hasOwnProperty.call(input, "body_json") || Object.prototype.hasOwnProperty.call(input, "bodyJson") || Object.prototype.hasOwnProperty.call(input, "json");
11955
- const requestBody = normalizeNetworkMockRequestBodyConstraints(input, label);
11956
- const abort = normalizeNetworkMockAbort(input, label, defaults.abort, defaults.abort_error_code);
11957
- return {
11958
- label: stringValue6(input.label) || stringValue6(input.name) || defaults.label,
11959
- status,
11960
- content_type: stringValue6(input.content_type) || stringValue6(input.contentType) || defaults.content_type,
11961
- headers: stringRecord(input.headers) || defaults.headers,
11962
- body,
11963
- body_json: hasJsonBody ? toJsonValue(input.body_json ?? input.bodyJson ?? input.json) : defaults.body_json,
11964
- delay_ms: normalizeNetworkMockDelay(input, label, defaults.delay_ms),
11965
- abort: abort.abort,
11966
- abort_error_code: abort.abort_error_code,
11967
- capture_request_body: requestBody.capture_request_body,
11968
- request_body_contains: requestBody.request_body_contains,
11969
- request_body_patterns: requestBody.request_body_patterns,
11970
- request_body_not_contains: requestBody.request_body_not_contains,
11971
- request_body_not_patterns: requestBody.request_body_not_patterns
11972
- };
11973
- }
11974
- function normalizeNetworkMockAbort(input, label, defaultAbort, defaultErrorCode) {
11975
- const abortInput = input.abort ?? input.route_abort ?? input.routeAbort;
11976
- const explicitAbort = typeof abortInput === "string" ? abortInput.trim().length > 0 : abortInput === true;
11977
- const abort = explicitAbort || defaultAbort === true;
11978
- if (!abort) return {};
11979
- const codeInput = stringValue6(
11980
- typeof abortInput === "string" ? abortInput : input.abort_error_code ?? input.abortErrorCode ?? input.abort_error ?? input.abortError ?? input.network_error ?? input.networkError
11981
- ) || defaultErrorCode || "failed";
11982
- const abort_error_code = codeInput.toLowerCase();
11983
- if (!RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES.includes(abort_error_code)) {
11984
- throw new Error(`${label}.abort_error_code must be one of ${RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES.join(", ")}.`);
11985
- }
11986
- return { abort: true, abort_error_code };
11987
- }
11988
- function normalizeNetworkMockDelay(input, label, defaultValue) {
11989
- const value = numberValue4(
11990
- input.delay_ms ?? input.delayMs ?? input.wait_ms ?? input.waitMs ?? input.latency_ms ?? input.latencyMs
11991
- ) ?? defaultValue;
11992
- if (value === void 0) return void 0;
11993
- if (!Number.isInteger(value) || value < 0 || value > 6e4) {
11994
- throw new Error(`${label}.delay_ms must be an integer from 0 to 60000.`);
11995
- }
11996
- return value;
11997
- }
11998
- function normalizeNetworkMockResponses(value, mockIndex, defaults) {
11999
- if (value === void 0) return void 0;
12000
- if (!Array.isArray(value)) throw new Error(`target.network_mocks[${mockIndex}].responses must be an array.`);
12001
- if (!value.length) throw new Error(`target.network_mocks[${mockIndex}].responses must not be empty.`);
12002
- const responseDefaults = {
12003
- label: void 0,
12004
- status: defaults.status,
12005
- content_type: defaults.content_type,
12006
- headers: defaults.headers,
12007
- body: defaults.body,
12008
- body_json: defaults.body_json,
12009
- delay_ms: defaults.delay_ms,
12010
- abort: defaults.abort,
12011
- abort_error_code: defaults.abort_error_code
12012
- };
12013
- return value.map((response, responseIndex) => {
12014
- if (!isRecord2(response)) {
12015
- throw new Error(`target.network_mocks[${mockIndex}].responses[${responseIndex}] must be an object.`);
12016
- }
12017
- return normalizeNetworkMockResponsePayload(
12018
- response,
12019
- `target.network_mocks[${mockIndex}].responses[${responseIndex}]`,
12020
- responseDefaults
12021
- );
12022
- });
12023
- }
12024
- function normalizeNetworkMocks(value) {
12025
- if (value === void 0) return void 0;
12026
- if (!Array.isArray(value)) throw new Error("target.network_mocks must be an array.");
12027
- return value.map(normalizeNetworkMock);
12028
- }
12029
- function profileStringList(value) {
12030
- return Array.isArray(value) ? value.map((item) => String(item)).filter(Boolean) : [];
12031
- }
12032
- function responseHasRequestBodyContract(response) {
12033
- if (!response) return false;
12034
- return profileStringList(response.request_body_contains).length > 0 || profileStringList(response.request_body_patterns).length > 0 || profileStringList(response.request_body_not_contains).length > 0 || profileStringList(response.request_body_not_patterns).length > 0;
12035
- }
12036
- function responseHasOnlyPositiveTextSelector(response) {
12037
- if (!response) return false;
12038
- return profileStringList(response.request_body_contains).length > 0 && profileStringList(response.request_body_patterns).length === 0 && profileStringList(response.request_body_not_contains).length === 0 && profileStringList(response.request_body_not_patterns).length === 0;
12039
- }
12040
- function responseMayShadowLaterRequestBodyMatch(earlier, later) {
12041
- if (!responseHasOnlyPositiveTextSelector(earlier) || !responseHasRequestBodyContract(later)) return false;
12042
- const earlierContains = profileStringList(earlier.request_body_contains);
12043
- const laterContains = profileStringList(later.request_body_contains);
12044
- if (!laterContains.length) return false;
12045
- return earlierContains.every((fragment) => laterContains.includes(fragment));
12046
- }
12047
- function responseLabel(response, index) {
12048
- return response.label ? `"${response.label}"` : `responses[${index}]`;
12049
- }
12050
- function collectRiddleProofProfileWarnings(profile) {
12051
- const warnings = [];
12052
- for (const [mockIndex, mock] of (profile.target.network_mocks || []).entries()) {
12053
- const responses = Array.isArray(mock.responses) ? mock.responses : [];
12054
- if (responses.length < 2) continue;
12055
- for (let laterIndex = 1; laterIndex < responses.length; laterIndex += 1) {
12056
- const later = responses[laterIndex];
12057
- if (!responseHasRequestBodyContract(later)) continue;
12058
- for (let earlierIndex = 0; earlierIndex < laterIndex; earlierIndex += 1) {
12059
- const earlier = responses[earlierIndex];
12060
- if (!responseMayShadowLaterRequestBodyMatch(earlier, later)) continue;
12061
- const mockLabel = mock.label ? ` (${mock.label})` : "";
12062
- warnings.push(
12063
- `target.network_mocks[${mockIndex}]${mockLabel} ${responseLabel(earlier, earlierIndex)} can shadow ${responseLabel(later, laterIndex)} because the earlier request_body_contains fragments are a subset of the later response and have no negative or pattern disambiguator. First matching request-body response wins.`
12064
- );
12065
- break;
12066
- }
12067
- }
12068
- }
12069
- return warnings;
12070
- }
12071
- function profileStatusProbeCounts(profile) {
12072
- let httpStatus = 0;
12073
- let linkStatus = 0;
12074
- for (const check of profile.checks || []) {
12075
- if (check.type === "http_status") httpStatus += 1;
12076
- if (check.type === "link_status" || check.type === "artifact_link_status") linkStatus += 1;
12077
- }
12078
- return { httpStatus, linkStatus };
12079
- }
12080
- function riddleApiStrictSafetyWarnings(blocker) {
12081
- const rawWarnings = Array.isArray(blocker?.warnings) ? blocker.warnings.filter((warning) => typeof warning === "string") : [];
12082
- const errorText = typeof blocker?.error === "string" ? blocker.error.toLowerCase() : "";
12083
- const hasSafetyError = errorText.includes("potentially unsafe operations");
12084
- const hasDirectNetworkWarning = rawWarnings.some((warning) => warning.toLowerCase().includes("direct network operations"));
12085
- return hasSafetyError || hasDirectNetworkWarning ? rawWarnings : [];
12086
- }
12087
- function collectRiddleProofProfileEnvironmentBlockedWarnings(profile, blocker) {
12088
- const warnings = collectRiddleProofProfileWarnings(profile);
12089
- const safetyWarnings = riddleApiStrictSafetyWarnings(blocker);
12090
- if (!safetyWarnings.length) return warnings;
12091
- const counts = profileStatusProbeCounts(profile);
12092
- const statusProbeCount = counts.httpStatus + counts.linkStatus;
12093
- if (!statusProbeCount) return warnings;
12094
- const parts = [
12095
- counts.httpStatus ? `${counts.httpStatus} http_status` : "",
12096
- counts.linkStatus ? `${counts.linkStatus} link_status/artifact_link_status` : ""
12097
- ].filter(Boolean);
12098
- warnings.push(
12099
- `Riddle API strict script validation blocked a hosted profile runner with ${parts.join(" and ")} check(s). These checks intentionally collect endpoint/link evidence from inside the generated browser runner; hosted run-profile defaults to --strict=false, so omit --strict=true or rerun with --strict=false for trusted generated profile runs.`
12100
- );
12101
- return warnings;
12102
- }
12103
- function normalizeRouteInventoryPath(value, label) {
12104
- const path5 = stringValue6(value);
12105
- if (!path5) throw new Error(`${label} requires path.`);
12106
- if (!path5.startsWith("/")) throw new Error(`${label}.path must start with /.`);
12107
- return normalizeRoutePath2(path5);
12108
- }
12109
- function normalizeRouteInventoryRoute(input, index) {
12110
- if (typeof input === "string") return { path: normalizeRouteInventoryPath(input, `checks route_inventory expected_routes[${index}]`) };
12111
- if (!isRecord2(input)) throw new Error(`checks route_inventory expected_routes[${index}] must be a string or object.`);
12112
- return {
12113
- name: stringValue6(input.name),
12114
- path: normalizeRouteInventoryPath(input.path, `checks route_inventory expected_routes[${index}]`)
12115
- };
12116
- }
12117
- function normalizeRouteInventoryRoutes(value, index) {
12118
- if (value === void 0) return void 0;
12119
- if (!Array.isArray(value) || value.length === 0) {
12120
- throw new Error(`checks[${index}] route_inventory expected_routes must be a non-empty array.`);
12121
- }
12122
- const routes = value.map(normalizeRouteInventoryRoute);
12123
- const seen = /* @__PURE__ */ new Set();
12124
- for (const route of routes) {
12125
- if (seen.has(route.path)) throw new Error(`checks[${index}] route_inventory expected_routes contains duplicate path ${route.path}.`);
12126
- seen.add(route.path);
12127
- }
12128
- return routes;
12129
- }
12130
- function normalizeExpectedTexts(value, index) {
12131
- if (value === void 0) return void 0;
12132
- if (!Array.isArray(value) || value.length === 0) {
12133
- throw new Error(`checks[${index}] selector_text_order expected_texts must be a non-empty array.`);
12134
- }
12135
- const texts = value.map((item) => String(item).replace(/\s+/g, " ").trim()).filter(Boolean);
12136
- if (!texts.length) throw new Error(`checks[${index}] selector_text_order expected_texts must contain non-empty strings.`);
12137
- return texts;
12138
- }
12139
- function normalizeStringList(value, label) {
12140
- if (value === void 0) return void 0;
12141
- if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);
12142
- const values = value.map((item) => String(item).replace(/\s+/g, " ").trim()).filter(Boolean);
12143
- if (!values.length) throw new Error(`${label} must contain non-empty strings.`);
12144
- return values;
12145
- }
12146
- function normalizeHttpStatus(value, label) {
12147
- if (value === void 0) return void 0;
12148
- const status = numberValue4(value);
12149
- if (status === void 0 || !Number.isInteger(status) || status < 100 || status > 599) {
12150
- throw new Error(`${label} must be an HTTP status code.`);
12151
- }
12152
- return status;
12153
- }
12154
- function normalizeHttpStatuses(value, label) {
12155
- if (value === void 0) return void 0;
12156
- if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);
12157
- if (!value.length) throw new Error(`${label} must not be empty.`);
12158
- const statuses = value.map((item, index) => normalizeHttpStatus(item, `${label}[${index}]`));
12159
- return Array.from(new Set(statuses));
12160
- }
12161
- function normalizePositiveInteger(value, label, max) {
12162
- if (value === void 0) return void 0;
12163
- const number = numberValue4(value);
12164
- if (number === void 0 || !Number.isInteger(number) || number < 1 || max !== void 0 && number > max) {
12165
- throw new Error(`${label} must be an integer from 1 to ${max ?? "unbounded"}.`);
12166
- }
12167
- return number;
12168
- }
12169
- function validateRegexPatterns(patterns, label) {
12170
- for (const pattern of patterns || []) {
12171
- try {
12172
- new RegExp(pattern);
12173
- } catch (error) {
12174
- const message = error instanceof Error ? error.message : String(error);
12175
- throw new Error(`${label} contains invalid regex ${JSON.stringify(pattern)}: ${message}`);
12176
- }
12177
- }
12178
- }
12179
- function normalizeHttpStatusBodyJsonAssertions(value, label) {
12180
- if (value === void 0) return void 0;
12181
- if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);
12182
- if (!value.length) throw new Error(`${label} must not be empty.`);
12183
- return value.map((item, index) => {
12184
- const itemLabel = `${label}[${index}]`;
12185
- if (typeof item === "string") {
12186
- const path6 = stringValue6(item);
12187
- if (!path6) throw new Error(`${itemLabel} path must not be empty.`);
12188
- return { path: path6, exists: true };
12189
- }
12190
- if (!isRecord2(item)) throw new Error(`${itemLabel} must be an object or JSON path string.`);
12191
- const path5 = stringFromOwn(item, "path", "json_path", "jsonPath", "key");
12192
- if (!path5) throw new Error(`${itemLabel}.path is required.`);
12193
- const assertion = {
12194
- label: stringValue6(item.label),
12195
- path: path5
12196
- };
12197
- const exists = booleanValue2(valueFromOwn(item, "exists", "present"));
12198
- if (exists !== void 0) assertion.exists = exists;
12199
- const type = stringValue6(valueFromOwn(item, "type", "value_type", "valueType"));
12200
- if (type !== void 0) {
12201
- const allowedTypes = ["array", "boolean", "null", "number", "object", "string"];
12202
- if (!allowedTypes.includes(type)) {
12203
- throw new Error(`${itemLabel}.type must be one of ${allowedTypes.join(", ")}.`);
12204
- }
12205
- assertion.type = type;
12206
- }
12207
- const equalsValue = valueFromOwn(item, "equals", "expected", "expected_value", "expectedValue", "value");
12208
- if (equalsValue !== void 0) assertion.equals = toJsonValue(equalsValue);
12209
- const notEqualsValue = valueFromOwn(item, "not_equals", "notEquals", "forbidden", "forbidden_value", "forbiddenValue");
12210
- if (notEqualsValue !== void 0) assertion.not_equals = toJsonValue(notEqualsValue);
12211
- const containsValue = valueFromOwn(item, "contains", "includes", "contains_value", "containsValue", "include");
12212
- if (containsValue !== void 0) assertion.contains = toJsonValue(containsValue);
12213
- if (assertion.exists === void 0 && assertion.type === void 0 && !hasOwn(assertion, "equals") && !hasOwn(assertion, "not_equals") && !hasOwn(assertion, "contains")) {
12214
- assertion.exists = true;
12215
- }
12216
- return assertion;
12217
- });
12218
- }
12219
- function isDialogCountCheckType(type) {
12220
- return type === "dialog_count_equals" || type === "dialog_accept_count_equals" || type === "dialog_dismiss_count_equals";
12221
- }
12222
- function dialogCountFieldForCheckType(type) {
12223
- if (type === "dialog_accept_count_equals") return "dialog_accept_count";
12224
- if (type === "dialog_dismiss_count_equals") return "dialog_dismiss_count";
12225
- return "dialog_count";
12226
- }
12227
- function normalizeOrderedTraceEvents(value, label) {
12228
- if (value === void 0) return void 0;
12229
- if (!Array.isArray(value) || !value.length) throw new Error(`${label} must be a non-empty array.`);
12230
- const seenLabels = /* @__PURE__ */ new Set();
12231
- return value.map((item, eventIndex) => {
12232
- const eventLabel = `${label}[${eventIndex}]`;
12233
- if (!isRecord2(item)) throw new Error(`${eventLabel} must be an object.`);
12234
- const name = stringFromOwn(item, "label", "name", "event");
12235
- if (!name) throw new Error(`${eventLabel}.label is required.`);
12236
- if (seenLabels.has(name)) throw new Error(`${eventLabel}.label must be unique.`);
12237
- seenLabels.add(name);
12238
- const predicatesInput = item.predicates ?? item.all ?? item.where;
12239
- if (!Array.isArray(predicatesInput) || !predicatesInput.length) {
12240
- throw new Error(`${eventLabel}.predicates must be a non-empty array.`);
12241
- }
12242
- const predicates = predicatesInput.map((predicateInput, predicateIndex) => {
12243
- const predicateLabel = `${eventLabel}.predicates[${predicateIndex}]`;
12244
- if (!isRecord2(predicateInput)) throw new Error(`${predicateLabel} must be an object.`);
12245
- const path5 = stringFromOwn(predicateInput, "path", "field", "key");
12246
- if (!path5) throw new Error(`${predicateLabel}.path is required.`);
12247
- const op = stringFromOwn(predicateInput, "op", "operator");
12248
- if (!op || !RIDDLE_PROOF_ORDERED_TRACE_OPERATORS.includes(op)) {
12249
- throw new Error(`${predicateLabel}.op must be one of ${RIDDLE_PROOF_ORDERED_TRACE_OPERATORS.join(", ")}.`);
12250
- }
12251
- const requiresValue = !["exists", "truthy", "falsy"].includes(op);
12252
- const hasValue = hasOwn(predicateInput, "value") || hasOwn(predicateInput, "expected");
12253
- if (requiresValue && !hasValue) throw new Error(`${predicateLabel}.value is required for ${op}.`);
12254
- const value2 = hasOwn(predicateInput, "value") ? predicateInput.value : predicateInput.expected;
12255
- if (["gt", "gte", "lt", "lte", "abs_gt", "abs_gte", "abs_lt", "abs_lte"].includes(op)) {
12256
- if (typeof value2 !== "number" || !Number.isFinite(value2)) {
12257
- throw new Error(`${predicateLabel}.value must be a finite number for ${op}.`);
12258
- }
12259
- if (op.startsWith("abs_") && value2 < 0) {
12260
- throw new Error(`${predicateLabel}.value must be non-negative for ${op}.`);
12261
- }
12262
- }
12263
- return {
12264
- path: path5,
12265
- op,
12266
- value: requiresValue ? toJsonValue(value2) : void 0
12267
- };
12268
- });
12269
- return { label: name, predicates };
12270
- });
12271
- }
12272
- function normalizeCheck(input, index) {
12273
- if (!isRecord2(input)) throw new Error(`checks[${index}] must be an object.`);
12274
- const type = stringValue6(input.type);
12275
- if (!type) throw new Error(`checks[${index}].type is required.`);
12276
- if (!isSupportedCheckType(type)) {
12277
- throw new Error(`checks[${index}].type ${type} is not supported. Supported checks: ${RIDDLE_PROOF_PROFILE_CHECK_TYPES.join(", ")}`);
12278
- }
12279
- const isDialogCountCheck = isDialogCountCheckType(type);
12280
- if ((type === "selector_visible" || type === "selector_absent" || type === "selector_count_at_least" || type === "selector_count_equals" || type === "selector_count_equal" || type === "selector_count_eq" || type === "selector_text_visible" || type === "selector_text_absent" || type === "observe_within" && !stringValue6(input.text) && !stringValue6(input.pattern)) && !stringValue6(input.selector)) {
12281
- throw new Error(`checks[${index}] ${type} requires selector.`);
12282
- }
12283
- if ((type === "frame_text_visible" || type === "frame_url_equals" || type === "frame_url_matches" || type === "frame_no_horizontal_overflow") && !stringValue6(input.selector)) {
12284
- throw new Error(`checks[${index}] ${type} requires selector.`);
12285
- }
12286
- if (type === "frame_text_visible" && !stringValue6(input.text) && !stringValue6(input.pattern)) {
12287
- throw new Error(`checks[${index}] frame_text_visible requires text or pattern.`);
12288
- }
12289
- const expectedUrl = stringFromOwn(input, "expected_url", "expectedUrl", "url", "expected_value", "expectedValue", "value");
12290
- if (type === "frame_url_equals" && expectedUrl === void 0) {
12291
- throw new Error(`checks[${index}] frame_url_equals requires expected_url.`);
12292
- }
12293
- if (type === "frame_url_matches" && !stringValue6(input.pattern)) {
12294
- throw new Error(`checks[${index}] frame_url_matches requires pattern.`);
12295
- }
12296
- if ((type === "text_visible" || type === "text_absent" || type === "selector_text_visible" || type === "selector_text_absent") && !stringValue6(input.text) && !stringValue6(input.pattern)) {
12297
- throw new Error(`checks[${index}] ${type} requires text or pattern.`);
12298
- }
12299
- if ((type === "url_search_param_equals" || type === "url_search_param_absent") && !stringValue6(input.param) && !stringValue6(input.search_param) && !stringValue6(input.searchParam) && !stringValue6(input.key)) {
12300
- throw new Error(`checks[${index}] ${type} requires param.`);
12301
- }
12302
- const expectedValue = stringFromOwn(input, "expected_value", "expectedValue", "value");
12303
- if (type === "url_search_param_equals" && expectedValue === void 0) {
12304
- throw new Error(`checks[${index}] url_search_param_equals requires expected_value.`);
12305
- }
12306
- const minCount = numberValue4(input.min_count) ?? numberValue4(input.minCount);
12307
- if (type === "selector_count_at_least" && minCount === void 0) {
12308
- throw new Error(`checks[${index}] selector_count_at_least requires min_count.`);
12309
- }
12310
- const expectedCount = numberValue4(input.expected_count) ?? numberValue4(input.expectedCount) ?? numberValue4(input.count);
12311
- if ((type === "selector_count_equals" || type === "selector_count_equal" || type === "selector_count_eq" || isDialogCountCheck) && expectedCount === void 0) {
12312
- throw new Error(`checks[${index}] ${type} requires expected_count.`);
12313
- }
12314
- if (isDialogCountCheck && (expectedCount === void 0 || !Number.isInteger(expectedCount) || expectedCount < 0)) {
12315
- throw new Error(`checks[${index}] ${type} expected_count must be a non-negative integer.`);
12316
- }
12317
- const expectedTexts = normalizeExpectedTexts(input.expected_texts ?? input.expectedTexts, index);
12318
- if (type === "selector_text_order") {
12319
- if (!stringValue6(input.selector)) throw new Error(`checks[${index}] selector_text_order requires selector.`);
12320
- if (!expectedTexts?.length) throw new Error(`checks[${index}] selector_text_order requires expected_texts.`);
12321
- }
12322
- const setupActionLabel = stringFromOwn(input, "setup_action_label", "setupActionLabel", "source_action_label", "sourceActionLabel");
12323
- const tracePath = stringFromOwn(input, "trace_path", "tracePath", "path");
12324
- const orderedTraceEvents = normalizeOrderedTraceEvents(
12325
- input.events ?? input.sequence ?? input.ordered_events ?? input.orderedEvents,
12326
- `checks[${index}].events`
12327
- );
12328
- if (type === "ordered_trace") {
12329
- if (!setupActionLabel) throw new Error(`checks[${index}] ordered_trace requires setup_action_label.`);
12330
- if (!tracePath) throw new Error(`checks[${index}] ordered_trace requires trace_path.`);
12331
- if (!orderedTraceEvents?.length) throw new Error(`checks[${index}] ordered_trace requires events.`);
12332
- }
12333
- const expectedRoutes = normalizeRouteInventoryRoutes(input.expected_routes ?? input.expectedRoutes, index);
12334
- if (type === "route_inventory" && !expectedRoutes?.length) {
12335
- throw new Error(`checks[${index}] route_inventory requires expected_routes.`);
12336
- }
12337
- const isHttpStatusCheck = type === "http_status";
12338
- const isLinkStatusCheck = type === "link_status" || type === "artifact_link_status";
12339
- const isStatusCheck = isHttpStatusCheck || isLinkStatusCheck;
12340
- const requestUrl = stringFromOwn(input, "url", "endpoint_url", "endpointUrl", "endpoint", "request_url", "requestUrl", "path");
12341
- if (isHttpStatusCheck && !requestUrl) {
12342
- throw new Error(`checks[${index}] http_status requires url.`);
12343
- }
12344
- const method = stringFromOwn(input, "method", "http_method", "httpMethod")?.toUpperCase();
12345
- if (isHttpStatusCheck && method && !/^[A-Z]+$/.test(method)) {
12346
- throw new Error(`checks[${index}] http_status method must contain only letters.`);
12347
- }
12348
- const hasBodyJson = hasOwn(input, "body_json") || hasOwn(input, "bodyJson") || hasOwn(input, "json");
12349
- const expectedStatus = isStatusCheck ? normalizeHttpStatus(input.expected_status ?? input.expectedStatus ?? input.status, `checks[${index}] expected_status`) : void 0;
12350
- const allowedStatuses = isStatusCheck ? normalizeHttpStatuses(
12351
- input.allowed_statuses ?? input.allowedStatuses ?? input.expected_statuses ?? input.expectedStatuses,
12352
- `checks[${index}] allowed_statuses`
12353
- ) : void 0;
12354
- const maxLinks = isLinkStatusCheck ? normalizePositiveInteger(input.max_links ?? input.maxLinks ?? input.limit, `checks[${index}] max_links`, 500) : void 0;
12355
- const minBytes = isStatusCheck ? normalizePositiveInteger(input.min_bytes ?? input.minBytes ?? input.min_response_bytes ?? input.minResponseBytes, `checks[${index}] min_bytes`) : void 0;
12356
- const expectedContentType = isStatusCheck ? stringValue6(input.expected_content_type) || stringValue6(input.expectedContentType) || stringValue6(input.content_type) || stringValue6(input.contentType) : void 0;
12357
- const allowedContentTypes = isStatusCheck ? normalizeStringList(
12358
- input.allowed_content_types ?? input.allowedContentTypes ?? input.expected_content_types ?? input.expectedContentTypes,
12359
- `checks[${index}] allowed_content_types`
12360
- ) ?? (expectedContentType ? [expectedContentType] : void 0) : void 0;
12361
- const bodyContains = isHttpStatusCheck ? normalizeStringList(
12362
- input.body_contains ?? input.bodyContains ?? input.expected_body_contains ?? input.expectedBodyContains ?? input.response_body_contains ?? input.responseBodyContains ?? input.body_includes ?? input.bodyIncludes,
12363
- `checks[${index}] body_contains`
12364
- ) : void 0;
12365
- const bodyNotContains = isHttpStatusCheck ? normalizeStringList(
12366
- input.body_not_contains ?? input.bodyNotContains ?? input.expected_body_not_contains ?? input.expectedBodyNotContains ?? input.response_body_not_contains ?? input.responseBodyNotContains ?? input.body_absent ?? input.bodyAbsent,
12367
- `checks[${index}] body_not_contains`
12368
- ) : void 0;
12369
- const bodyNotPatterns = isHttpStatusCheck ? normalizeStringList(
12370
- input.body_not_patterns ?? input.bodyNotPatterns ?? input.expected_body_not_patterns ?? input.expectedBodyNotPatterns ?? input.response_body_not_patterns ?? input.responseBodyNotPatterns ?? input.body_forbidden_patterns ?? input.bodyForbiddenPatterns,
12371
- `checks[${index}] body_not_patterns`
12372
- ) : void 0;
12373
- if (bodyNotPatterns?.length) validateRegexPatterns(bodyNotPatterns, `checks[${index}] body_not_patterns`);
12374
- const bodyJsonAssertions = isHttpStatusCheck ? normalizeHttpStatusBodyJsonAssertions(
12375
- input.body_json_assertions ?? input.bodyJsonAssertions ?? input.json_body_assertions ?? input.jsonBodyAssertions ?? input.json_assertions ?? input.jsonAssertions ?? input.response_json_assertions ?? input.responseJsonAssertions,
12376
- `checks[${index}] body_json_assertions`
12377
- ) : void 0;
12378
- if (isLinkStatusCheck) {
12379
- if (minCount !== void 0 && (!Number.isInteger(minCount) || minCount < 0)) {
12380
- throw new Error(`checks[${index}] ${type} min_count must be a non-negative integer.`);
12381
- }
12382
- if (expectedCount !== void 0 && (!Number.isInteger(expectedCount) || expectedCount < 0)) {
12383
- throw new Error(`checks[${index}] ${type} expected_count must be a non-negative integer.`);
12384
- }
12385
- }
12386
- return {
12387
- type,
12388
- label: stringValue6(input.label),
12389
- expected_path: stringValue6(input.expected_path),
12390
- param: stringValue6(input.param) || stringValue6(input.search_param) || stringValue6(input.searchParam) || stringValue6(input.key),
12391
- expected_value: expectedValue,
12392
- expected_url: expectedUrl,
12393
- expected_routes: expectedRoutes,
12394
- selector: stringValue6(input.selector),
12395
- url: isHttpStatusCheck ? requestUrl : void 0,
12396
- method: isHttpStatusCheck ? method || "GET" : void 0,
12397
- headers: isHttpStatusCheck ? stringRecord(input.headers) : void 0,
12398
- body: isHttpStatusCheck ? stringValue6(input.body) : void 0,
12399
- body_json: isHttpStatusCheck && hasBodyJson ? toJsonValue(input.body_json ?? input.bodyJson ?? input.json) : void 0,
12400
- body_contains: bodyContains,
12401
- body_not_contains: bodyNotContains,
12402
- body_not_patterns: bodyNotPatterns,
12403
- body_json_assertions: bodyJsonAssertions,
12404
- expected_texts: expectedTexts,
12405
- setup_action_label: type === "ordered_trace" ? setupActionLabel : void 0,
12406
- trace_path: type === "ordered_trace" ? tracePath : void 0,
12407
- events: type === "ordered_trace" ? orderedTraceEvents : void 0,
12408
- link_selector: stringValue6(input.link_selector) || stringValue6(input.linkSelector),
12409
- source_selector: stringValue6(input.source_selector) || stringValue6(input.sourceSelector),
12410
- route_path_prefix: stringValue6(input.route_path_prefix) || stringValue6(input.routePathPrefix),
12411
- route_ready_selector: stringValue6(input.route_ready_selector) || stringValue6(input.routeReadySelector),
12412
- route_ready_text: stringValue6(input.route_ready_text) || stringValue6(input.routeReadyText),
12413
- route_ready_pattern: stringValue6(input.route_ready_pattern) || stringValue6(input.routeReadyPattern),
12414
- route_ready_flags: stringValue6(input.route_ready_flags) || stringValue6(input.routeReadyFlags),
12415
- text: stringValue6(input.text),
12416
- pattern: stringValue6(input.pattern),
12417
- flags: stringValue6(input.flags),
12418
- viewports: normalizeStringList(input.viewports ?? input.viewport_names ?? input.viewportNames, `checks[${index}] viewports`),
12419
- allowed_console_texts: normalizeStringList(input.allowed_console_texts ?? input.allowedConsoleTexts ?? input.allow_console_texts ?? input.allowConsoleTexts, `checks[${index}] allowed_console_texts`),
12420
- allowed_console_patterns: normalizeStringList(input.allowed_console_patterns ?? input.allowedConsolePatterns ?? input.allow_console_patterns ?? input.allowConsolePatterns, `checks[${index}] allowed_console_patterns`),
12421
- allowed_page_error_texts: normalizeStringList(input.allowed_page_error_texts ?? input.allowedPageErrorTexts ?? input.allow_page_error_texts ?? input.allowPageErrorTexts, `checks[${index}] allowed_page_error_texts`),
12422
- allowed_page_error_patterns: normalizeStringList(input.allowed_page_error_patterns ?? input.allowedPageErrorPatterns ?? input.allow_page_error_patterns ?? input.allowPageErrorPatterns, `checks[${index}] allowed_page_error_patterns`),
12423
- min_count: minCount,
12424
- expected_count: expectedCount,
12425
- expected_status: expectedStatus,
12426
- allowed_statuses: allowedStatuses,
12427
- max_links: maxLinks,
12428
- same_origin_only: isLinkStatusCheck ? input.same_origin_only === true || input.sameOriginOnly === true : void 0,
12429
- dedupe: isLinkStatusCheck ? input.dedupe === false ? false : true : void 0,
12430
- require_nonzero_bytes: isStatusCheck ? input.require_nonzero_bytes === true || input.requireNonzeroBytes === true : void 0,
12431
- min_bytes: minBytes,
12432
- allowed_content_types: allowedContentTypes,
12433
- allow_get_fallback: isLinkStatusCheck ? input.allow_get_fallback === false || input.allowGetFallback === false ? false : true : void 0,
12434
- max_overflow_px: numberValue4(input.max_overflow_px),
12435
- timeout_ms: numberValue4(input.timeout_ms) ?? numberValue4(input.timeoutMs) ?? numberValue4(input.within_ms) ?? numberValue4(input.withinMs),
12436
- run_direct_routes: input.run_direct_routes === false || input.runDirectRoutes === false ? false : true,
12437
- run_clickthroughs: input.run_clickthroughs === false || input.runClickthroughs === false ? false : true,
12438
- run_all_viewports: input.run_all_viewports === true || input.runAllViewports === true,
12439
- require_unique_routes: input.require_unique_routes === false || input.requireUniqueRoutes === false ? false : true,
12440
- allow_unexpected_routes: input.allow_unexpected_routes === true || input.allowUnexpectedRoutes === true,
12441
- save_route_screenshots: input.save_route_screenshots === true || input.saveRouteScreenshots === true
12442
- };
12443
- }
12444
- function normalizeFailurePolicy(input) {
12445
- const defaults = {
12446
- product_regression: "fail",
12447
- proof_insufficient: "fail",
12448
- environment_blocked: "neutral",
12449
- configuration_error: "fail",
12450
- needs_human_review: "fail"
12451
- };
12452
- if (!isRecord2(input)) return defaults;
12453
- const next = { ...defaults };
12454
- for (const [key, value] of Object.entries(input)) {
12455
- if (!RIDDLE_PROOF_PROFILE_STATUSES.includes(key)) continue;
12456
- if (value === "fail" || value === "neutral" || value === "review") {
12457
- next[key] = value;
12458
- }
12459
- }
12460
- return next;
12461
- }
12462
- function normalizeRiddleProofProfile(input, options = {}) {
12463
- if (!isRecord2(input)) throw new Error("profile must be a JSON object.");
12464
- const version = stringValue6(input.version) || RIDDLE_PROOF_PROFILE_VERSION;
12465
- if (version !== RIDDLE_PROOF_PROFILE_VERSION) {
12466
- throw new Error(`Unsupported profile version ${version}. Expected ${RIDDLE_PROOF_PROFILE_VERSION}.`);
12467
- }
12468
- const targetInput = isRecord2(input.target) ? input.target : {};
12469
- const checks = Array.isArray(input.checks) ? input.checks.map(normalizeCheck) : [];
12470
- if (!checks.length) throw new Error("profile.checks must contain at least one check.");
12471
- const targetUrl = stringValue6(options.url) || stringValue6(targetInput.url);
12472
- const route = stringValue6(options.route) || stringValue6(targetInput.route);
12473
- if (!targetUrl && !route) throw new Error("profile.target requires url or route, or pass --url.");
12474
- const setupActions = normalizeSetupActions(targetInput.setup_actions ?? targetInput.setupActions);
12475
- for (const [index, check] of checks.entries()) {
12476
- if (check.type !== "ordered_trace") continue;
12477
- const matches = (setupActions || []).filter((action) => action.label === check.setup_action_label);
12478
- if (matches.length !== 1) {
12479
- throw new Error(`checks[${index}] ordered_trace setup_action_label must match exactly one target.setup_actions label.`);
12480
- }
12481
- if (!["window_eval", "window_call", "window_call_until"].includes(matches[0].type)) {
12482
- throw new Error(`checks[${index}] ordered_trace source action must capture a window_eval, window_call, or window_call_until return.`);
12483
- }
12484
- if (matches[0].capture_return === false) {
12485
- throw new Error(`checks[${index}] ordered_trace source action must not set capture_return to false.`);
12486
- }
12487
- }
12488
- return {
12489
- version: RIDDLE_PROOF_PROFILE_VERSION,
12490
- name: normalizeName(input.name, "riddle-proof-profile"),
12491
- target: {
12492
- url: targetUrl,
12493
- route,
12494
- viewports: options.viewports?.length ? options.viewports : normalizeViewports(targetInput.viewports),
12495
- auth: stringValue6(targetInput.auth) || "none",
12496
- timeout_sec: timeoutSecValue(targetInput.timeout_sec) ?? timeoutSecValue(targetInput.timeoutSec) ?? timeoutSecValue(targetInput.riddle_timeout_sec) ?? timeoutSecValue(targetInput.riddleTimeoutSec),
12497
- wait_for_selector: stringValue6(targetInput.wait_for_selector) || stringValue6(targetInput.waitForSelector),
12498
- wait_ms: numberValue4(targetInput.wait_ms) ?? numberValue4(targetInput.waitMs),
12499
- screenshot_full_page: normalizeTargetScreenshotFullPage(targetInput),
12500
- setup_actions: setupActions,
12501
- network_mocks: normalizeNetworkMocks(targetInput.network_mocks ?? targetInput.networkMocks)
12502
- },
12503
- checks,
12504
- artifacts: Array.isArray(input.artifacts) ? input.artifacts.map((item) => String(item)).filter(Boolean) : ["screenshot", "console", "dom_summary", "proof_json"],
12505
- baseline_policy: stringValue6(input.baseline_policy) || stringValue6(input.baselinePolicy) || "invariant_only",
12506
- failure_policy: normalizeFailurePolicy(input.failure_policy || input.failurePolicy),
12507
- metadata: jsonRecord(input.metadata)
12508
- };
12509
- }
12510
- function resolveRiddleProofProfileTargetUrl(profile) {
12511
- const route = profile.target.route || "";
12512
- const targetUrl = profile.target.url || "";
12513
- if (targetUrl && route) return resolveRiddleProofProfileRouteUrl(targetUrl, route);
12514
- if (/^https?:\/\//i.test(route)) return route;
12515
- if (targetUrl) return targetUrl;
12516
- throw new Error("profile target URL could not be resolved.");
12517
- }
12518
- function resolveRiddleProofProfileTimeoutSec(profile, requestedTimeoutSec) {
12519
- return timeoutSecValue(requestedTimeoutSec) ?? timeoutSecValue(profile.target.timeout_sec);
12520
- }
12521
- function routeForViewport(viewport, targetUrl) {
12522
- if (viewport?.route) {
12523
- return {
12524
- ...viewport.route,
12525
- matched: viewport.route.matched || routePathMatches(viewport.route.observed, viewport.route.expected_path, targetUrl)
12526
- };
12527
- }
12528
- return {
12529
- requested: "",
12530
- observed: "",
12531
- matched: false,
12532
- error: "missing viewport evidence"
12533
- };
12534
- }
12535
- function checkLabel(check) {
12536
- return check.label || check.type;
12537
- }
12538
- function selectorKey(check) {
12539
- return check.selector || "";
12540
- }
12541
- function linkStatusSelector(check) {
12542
- return check.selector || check.link_selector || "a[href]";
12543
- }
12544
- function httpStatusRequestUrl(check, baseUrl) {
12545
- const rawUrl = check.url || "";
12546
- if (!rawUrl) return "";
12547
- try {
12548
- if (baseUrl && rawUrl.startsWith("/") && !rawUrl.startsWith("//")) {
12549
- const base = new URL(baseUrl);
12550
- const mountPrefix = previewMountPrefix(base.pathname);
12551
- if (mountPrefix) {
12552
- const requested = new URL(rawUrl, base.origin);
12553
- base.pathname = joinMountedRoutePath(mountPrefix, requested.pathname);
12554
- base.search = requested.search;
12555
- base.hash = requested.hash;
12556
- return base.href;
12557
- }
12558
- }
12559
- return baseUrl ? new URL(rawUrl, baseUrl).href : new URL(rawUrl).href;
12560
- } catch {
12561
- return rawUrl;
12562
- }
12563
- }
12564
- function httpStatusMethod(check) {
12565
- return (check.method || "GET").toUpperCase();
12566
- }
12567
- function httpStatusKey(check, baseUrl) {
12568
- return `${httpStatusMethod(check)} ${httpStatusRequestUrl(check, baseUrl)}`;
12569
- }
12570
- function httpStatusAllowedStatuses(check) {
12571
- if (check.allowed_statuses?.length) return check.allowed_statuses;
12572
- if (check.expected_status !== void 0) return [check.expected_status];
12573
- return void 0;
12574
- }
12575
- function linkStatusAllowedStatuses(check) {
12576
- return httpStatusAllowedStatuses(check);
12577
- }
12578
- function httpStatusIsAllowed(status, check) {
12579
- if (status === void 0) return false;
12580
- const allowed = httpStatusAllowedStatuses(check);
12581
- return allowed?.length ? allowed.includes(status) : status >= 200 && status < 400;
12582
- }
12583
- function linkStatusObservedBytes(result) {
12584
- const bytes = numberValue4(result.bytes);
12585
- const contentLength = numberValue4(result.content_length);
12586
- return Math.max(bytes ?? 0, contentLength ?? 0) || void 0;
12587
- }
12588
- function normalizeLinkStatusContentType(value) {
12589
- const normalized = value?.split(";")[0]?.trim().toLowerCase();
12590
- return normalized || void 0;
12591
- }
12592
- function linkStatusContentTypesMatch(actual, expected) {
12593
- if (!actual || !expected) return false;
12594
- if (expected.endsWith("/*")) return actual.startsWith(expected.slice(0, -1));
12595
- if (actual === expected) return true;
12596
- const yamlTypes = /* @__PURE__ */ new Set(["application/yaml", "application/x-yaml", "text/yaml", "text/x-yaml"]);
12597
- return yamlTypes.has(actual) && yamlTypes.has(expected);
12598
- }
12599
- function linkStatusContentTypeOk(result, check) {
12600
- const expected = check.allowed_content_types;
12601
- if (!expected?.length) return true;
12602
- const actual = normalizeLinkStatusContentType(stringValue6(result.content_type));
12603
- if (!actual) return false;
12604
- return expected.some((contentType) => {
12605
- const normalized = normalizeLinkStatusContentType(contentType);
12606
- if (!normalized) return false;
12607
- return linkStatusContentTypesMatch(actual, normalized);
12608
- });
12609
- }
12610
- function httpStatusBodyContainsFailures(result, check) {
12611
- const expected = check.body_contains?.filter(Boolean) ?? [];
12612
- if (!expected.length) return [];
12613
- const observed = isRecord2(result.body_contains) ? result.body_contains : {};
12614
- return expected.filter((text) => observed[text] !== true);
12615
- }
12616
- function httpStatusBodyNotContainsFailures(result, check) {
12617
- const forbidden = check.body_not_contains?.filter(Boolean) ?? [];
12618
- if (!forbidden.length) return [];
12619
- const observed = isRecord2(result.body_not_contains) ? result.body_not_contains : {};
12620
- return forbidden.filter((text) => observed[text] !== false);
12621
- }
12622
- function httpStatusBodyNotPatternFailures(result, check) {
12623
- const forbidden = check.body_not_patterns?.filter(Boolean) ?? [];
12624
- if (!forbidden.length) return [];
12625
- const observed = isRecord2(result.body_not_patterns) ? result.body_not_patterns : {};
12626
- return forbidden.filter((pattern) => observed[pattern] !== false);
12627
- }
12628
- function httpStatusBodyJsonAssertionFailures(result, check) {
12629
- const expected = check.body_json_assertions?.filter((assertion) => assertion.path) ?? [];
12630
- if (!expected.length) return [];
12631
- if (!Array.isArray(result.body_json_assertions)) {
12632
- return expected.map((assertion) => ({
12633
- label: assertion.label || assertion.path,
12634
- path: assertion.path,
12635
- ok: false,
12636
- exists: false,
12637
- observed_type: "missing",
12638
- errors: ["body_json_assertions evidence missing"]
12639
- }));
12640
- }
12641
- return result.body_json_assertions.filter((assertion) => isRecord2(assertion) && assertion.ok !== true).map((assertion) => ({
12642
- label: stringValue6(assertion.label) || stringValue6(assertion.path) || "json assertion",
12643
- path: stringValue6(assertion.path) || "",
12644
- ok: false,
12645
- exists: assertion.exists === true,
12646
- observed: hasOwn(assertion, "observed") ? toJsonValue(assertion.observed) : void 0,
12647
- observed_sample: hasOwn(assertion, "observed_sample") ? toJsonValue(assertion.observed_sample) : void 0,
12648
- observed_length: numberValue4(assertion.observed_length),
12649
- observed_key_count: numberValue4(assertion.observed_key_count),
12650
- observed_omitted_count: numberValue4(assertion.observed_omitted_count),
12651
- observed_type: stringValue6(assertion.observed_type) || "missing",
12652
- expected_exists: booleanValue2(assertion.expected_exists),
12653
- equals: hasOwn(assertion, "equals") ? toJsonValue(assertion.equals) : void 0,
12654
- not_equals: hasOwn(assertion, "not_equals") ? toJsonValue(assertion.not_equals) : void 0,
12655
- contains: hasOwn(assertion, "contains") ? toJsonValue(assertion.contains) : void 0,
12656
- type: stringValue6(assertion.type),
12657
- errors: Array.isArray(assertion.errors) ? assertion.errors.map(String) : void 0
12658
- }));
12659
- }
12660
- function linkStatusResultOk(result, check) {
12661
- const status = numberValue4(result.status);
12662
- if (!httpStatusIsAllowed(status, check)) return false;
12663
- if (stringValue6(result.error)) return false;
12664
- if (result.ok === false) return false;
12665
- if (!linkStatusContentTypeOk(result, check)) return false;
12666
- if (check.require_nonzero_bytes) {
12667
- const observedBytes = linkStatusObservedBytes(result);
12668
- if (observedBytes === void 0 || observedBytes <= 0) return false;
12669
- }
12670
- if (check.min_bytes !== void 0) {
12671
- const observedBytes = linkStatusObservedBytes(result);
12672
- if (observedBytes === void 0 || observedBytes < check.min_bytes) return false;
12673
- }
12674
- if (httpStatusBodyContainsFailures(result, check).length) return false;
12675
- if (httpStatusBodyNotContainsFailures(result, check).length) return false;
12676
- if (httpStatusBodyNotPatternFailures(result, check).length) return false;
12677
- if (httpStatusBodyJsonAssertionFailures(result, check).length) return false;
12678
- return true;
12679
- }
12680
- function responseHeader(response, name) {
12681
- const getter = response.headers?.get;
12682
- if (typeof getter !== "function") return null;
12683
- return getter.call(response.headers, name);
12684
- }
12685
- function responseContentLength(response) {
12686
- const value = responseHeader(response, "content-length");
12687
- return value && /^\d+$/.test(value) ? Number(value) : null;
12688
- }
12689
- async function responseBodyText(response) {
12690
- if (typeof response.arrayBuffer === "function") {
12691
- const buffer = await response.arrayBuffer();
12692
- return {
12693
- text: new TextDecoder().decode(buffer),
12694
- bytes: buffer.byteLength
12695
- };
12696
- }
12697
- if (typeof response.text === "function") {
12698
- const text = await response.text();
12699
- return {
12700
- text,
12701
- bytes: new TextEncoder().encode(text).byteLength
12702
- };
12703
- }
12704
- return { text: "", bytes: null };
12705
- }
12706
- function httpStatusRequestBody(check) {
12707
- const headers = isRecord2(check.headers) ? Object.fromEntries(Object.entries(check.headers).map(([key, value]) => [key, String(value)]).filter(([key]) => key.trim())) : {};
12708
- if (check.body_json !== void 0) {
12709
- if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
12710
- headers["content-type"] = "application/json";
12711
- }
12712
- return { headers, body: JSON.stringify(check.body_json) };
12713
- }
12714
- if (typeof check.body === "string") {
12715
- return { headers, body: check.body };
12716
- }
12717
- return { headers };
12718
- }
12719
- async function preflightHttpStatusCheck(check, index, targetUrl, fetchImpl) {
12720
- const url = httpStatusRequestUrl(check, targetUrl);
12721
- const method = httpStatusMethod(check);
12722
- const request = httpStatusRequestBody(check);
12723
- const init = {
12724
- method,
12725
- redirect: "follow",
12726
- cache: "no-store",
12727
- headers: request.headers
12728
- };
12729
- if (request.body !== void 0 && method !== "GET" && method !== "HEAD") {
12730
- init.body = request.body;
12731
- }
12732
- const result = {
12733
- status: null,
12734
- content_type: null,
12735
- content_length: null,
12736
- bytes: null
12737
- };
12738
- let error = null;
12739
- let statusText = "";
12740
- try {
12741
- const response = await fetchImpl(url, init);
12742
- result.status = typeof response.status === "number" && Number.isFinite(response.status) ? response.status : null;
12743
- statusText = typeof response.statusText === "string" ? response.statusText : "";
12744
- result.content_type = responseHeader(response, "content-type");
12745
- result.content_length = responseContentLength(response);
12746
- const shouldReadBody = check.require_nonzero_bytes === true || typeof check.min_bytes === "number" || Boolean(check.body_contains?.length) || Boolean(check.body_not_contains?.length) || Boolean(check.body_not_patterns?.length) || Boolean(check.body_json_assertions?.length);
12747
- if (shouldReadBody && method !== "HEAD") {
12748
- const body = await responseBodyText(response);
12749
- result.bytes = body.bytes;
12750
- if (check.body_contains?.length) {
12751
- result.body_contains = Object.fromEntries(check.body_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
12752
- }
12753
- if (check.body_not_contains?.length) {
12754
- result.body_not_contains = Object.fromEntries(check.body_not_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
12755
- }
12756
- if (check.body_not_patterns?.length) {
12757
- result.body_not_patterns = Object.fromEntries(check.body_not_patterns.filter(Boolean).map((pattern) => [pattern, new RegExp(pattern).test(body.text)]));
12758
- }
12759
- if (check.body_json_assertions?.length) {
12760
- result.body_json_assertions = evaluateHttpStatusBodyJsonAssertions(body.text, check.body_json_assertions);
12761
- }
12762
- }
12763
- } catch (caught) {
12764
- error = String(caught instanceof Error ? caught.message : caught).slice(0, 500);
12765
- result.error = error;
12766
- }
12767
- const bodyContainsMissing = httpStatusBodyContainsFailures(result, check);
12768
- const bodyNotContainsFound = httpStatusBodyNotContainsFailures(result, check);
12769
- const bodyNotPatternsFound = httpStatusBodyNotPatternFailures(result, check);
12770
- const bodyJsonAssertionsFailed = httpStatusBodyJsonAssertionFailures(result, check);
12771
- const ok = !error && linkStatusResultOk(result, check);
12772
- return {
12773
- index,
12774
- label: checkLabel(check) || `checks[${index}]`,
12775
- url,
12776
- method,
12777
- ok,
12778
- status: numberValue4(result.status) ?? null,
12779
- status_text: statusText,
12780
- error,
12781
- content_type: stringValue6(result.content_type) ?? null,
12782
- content_length: numberValue4(result.content_length) ?? null,
12783
- bytes: numberValue4(result.bytes) ?? null,
12784
- body_contains: isRecord2(result.body_contains) ? Object.fromEntries(Object.entries(result.body_contains).map(([key, value]) => [key, value === true])) : null,
12785
- body_contains_missing: bodyContainsMissing,
12786
- body_not_contains: isRecord2(result.body_not_contains) ? Object.fromEntries(Object.entries(result.body_not_contains).map(([key, value]) => [key, value === true])) : null,
12787
- body_not_contains_found: bodyNotContainsFound,
12788
- body_not_patterns: isRecord2(result.body_not_patterns) ? Object.fromEntries(Object.entries(result.body_not_patterns).map(([key, value]) => [key, value === true])) : null,
12789
- body_not_patterns_found: bodyNotPatternsFound,
12790
- body_json_assertions: Array.isArray(result.body_json_assertions) ? result.body_json_assertions : null,
12791
- body_json_assertions_failed: bodyJsonAssertionsFailed
12792
- };
12793
- }
12794
- async function preflightRiddleProofProfileHttpStatusChecks(profile, options = {}) {
12795
- const targetUrl = options.target_url || resolveRiddleProofProfileTargetUrl(profile);
12796
- const fetchImpl = options.fetchImpl ?? globalThis.fetch;
12797
- if (typeof fetchImpl !== "function") {
12798
- throw new Error("profile http_status preflight requires fetch support or options.fetchImpl.");
12799
- }
12800
- const httpStatusChecks = profile.checks.map((check, index) => ({ check, index })).filter((item) => item.check.type === "http_status");
12801
- const checks = await Promise.all(httpStatusChecks.map((item) => preflightHttpStatusCheck(item.check, item.index, targetUrl, fetchImpl)));
12802
- const failed = checks.filter((check) => !check.ok).length;
12803
- return {
12804
- version: "riddle-proof.profile-http-status-preflight.v1",
12805
- ok: failed === 0,
12806
- profile_name: profile.name,
12807
- target_url: targetUrl,
12808
- checked: checks.length,
12809
- failed,
12810
- checks,
12811
- summary: failed === 0 ? `${profile.name} http_status preflight passed ${checks.length} check(s).` : `${profile.name} http_status preflight failed ${failed} of ${checks.length} check(s).`
12812
- };
12813
- }
12814
- function httpStatusEvidenceForCheck(viewport, check) {
12815
- const evidence = viewport.http_statuses?.[httpStatusKey(check, viewport.url)];
12816
- return isRecord2(evidence) ? evidence : void 0;
12817
- }
12818
- function summarizeHttpStatusEvidence(viewport, check) {
12819
- const key = httpStatusKey(check, viewport.url);
12820
- const statusEvidence = httpStatusEvidenceForCheck(viewport, check);
12821
- if (!statusEvidence) {
12822
- return {
12823
- viewport: viewport.name,
12824
- key,
12825
- url: httpStatusRequestUrl(check, viewport.url),
12826
- method: httpStatusMethod(check),
12827
- ok: false,
12828
- status: null,
12829
- failures: [{ code: "http_status_evidence_missing" }]
12830
- };
12831
- }
12832
- const failures = [];
12833
- const bodyContainsMissing = httpStatusBodyContainsFailures(statusEvidence, check);
12834
- const bodyNotContainsFound = httpStatusBodyNotContainsFailures(statusEvidence, check);
12835
- const bodyNotPatternsFound = httpStatusBodyNotPatternFailures(statusEvidence, check);
12836
- const bodyJsonAssertionsFailed = httpStatusBodyJsonAssertionFailures(statusEvidence, check);
12837
- if (!linkStatusResultOk(statusEvidence, check)) {
12838
- failures.push({
12839
- code: "http_status_failed",
12840
- url: stringValue6(statusEvidence.url) ?? httpStatusRequestUrl(check, viewport.url),
12841
- status: numberValue4(statusEvidence.status) ?? null,
12842
- method: stringValue6(statusEvidence.method) ?? httpStatusMethod(check),
12843
- error: stringValue6(statusEvidence.error) ?? null,
12844
- content_type: stringValue6(statusEvidence.content_type) ?? null,
12845
- bytes: linkStatusObservedBytes(statusEvidence) ?? null,
12846
- allowed_statuses: httpStatusAllowedStatuses(check) ?? ["2xx", "3xx"],
12847
- min_bytes: check.min_bytes ?? null,
12848
- allowed_content_types: check.allowed_content_types ?? null,
12849
- body_contains: check.body_contains ?? null,
12850
- body_contains_missing: bodyContainsMissing,
12851
- body_not_contains: check.body_not_contains ?? null,
12852
- body_not_contains_found: bodyNotContainsFound,
12853
- body_not_patterns: check.body_not_patterns ?? null,
12854
- body_not_patterns_found: bodyNotPatternsFound,
12855
- body_json_assertions: check.body_json_assertions ?? null,
12856
- body_json_assertions_failed: bodyJsonAssertionsFailed.map((assertion) => toJsonValue(assertion)),
12857
- body_sample: stringValue6(statusEvidence.body_sample) ?? null
12858
- });
12859
- }
12860
- return {
12861
- viewport: viewport.name,
12862
- key,
12863
- url: stringValue6(statusEvidence.url) ?? httpStatusRequestUrl(check, viewport.url),
12864
- method: stringValue6(statusEvidence.method) ?? httpStatusMethod(check),
12865
- status: numberValue4(statusEvidence.status) ?? null,
12866
- status_text: stringValue6(statusEvidence.status_text) ?? null,
12867
- ok: failures.length === 0,
12868
- error: stringValue6(statusEvidence.error) ?? null,
12869
- content_type: stringValue6(statusEvidence.content_type) ?? null,
12870
- content_length: numberValue4(statusEvidence.content_length) ?? null,
12871
- bytes: linkStatusObservedBytes(statusEvidence) ?? null,
12872
- body_contains: isRecord2(statusEvidence.body_contains) ? toJsonValue(statusEvidence.body_contains) : null,
12873
- body_contains_missing: bodyContainsMissing,
12874
- body_not_contains: isRecord2(statusEvidence.body_not_contains) ? toJsonValue(statusEvidence.body_not_contains) : null,
12875
- body_not_contains_found: bodyNotContainsFound,
12876
- body_not_patterns: isRecord2(statusEvidence.body_not_patterns) ? toJsonValue(statusEvidence.body_not_patterns) : null,
12877
- body_not_patterns_found: bodyNotPatternsFound,
12878
- body_json_assertions: Array.isArray(statusEvidence.body_json_assertions) ? toJsonValue(statusEvidence.body_json_assertions) : null,
12879
- body_json_assertions_failed: bodyJsonAssertionsFailed.map((assertion) => toJsonValue(assertion)),
12880
- body_sample: stringValue6(statusEvidence.body_sample) ?? null,
12881
- failures
12882
- };
12883
- }
12884
- function linkStatusEvidenceForCheck(viewport, check) {
12885
- const evidence = viewport.link_statuses?.[linkStatusSelector(check)];
12886
- return isRecord2(evidence) ? evidence : void 0;
12887
- }
12888
- function summarizeLinkStatusEvidence(viewport, check) {
12889
- const linkEvidence = linkStatusEvidenceForCheck(viewport, check);
12890
- if (!linkEvidence) {
12891
- return {
12892
- viewport: viewport.name,
12893
- selector: linkStatusSelector(check),
12894
- total_count: 0,
12895
- ok_count: 0,
12896
- failed_count: 1,
12897
- failures: [{ code: "link_status_evidence_missing" }]
12898
- };
12899
- }
12900
- const results = Array.isArray(linkEvidence.results) ? linkEvidence.results.filter(isRecord2) : [];
12901
- const totalCount = numberValue4(linkEvidence.total_count) ?? results.length;
12902
- const resultCount = numberValue4(linkEvidence.result_count) ?? totalCount;
12903
- const storedResultCount = numberValue4(linkEvidence.stored_result_count) ?? results.length;
12904
- const omittedResultCount = numberValue4(linkEvidence.omitted_result_count) ?? Math.max(0, resultCount - storedResultCount);
12905
- const omittedSuccessCount = numberValue4(linkEvidence.omitted_success_count) ?? 0;
12906
- const okCount = results.filter((result) => linkStatusResultOk(result, check)).length;
12907
- const failures = results.filter((result) => !linkStatusResultOk(result, check)).map((result) => ({
12908
- code: "link_status_failed",
12909
- url: stringValue6(result.url) ?? null,
12910
- status: numberValue4(result.status) ?? null,
12911
- method: stringValue6(result.method) ?? null,
12912
- error: stringValue6(result.error) ?? null,
12913
- content_type: stringValue6(result.content_type) ?? null,
12914
- bytes: linkStatusObservedBytes(result) ?? null,
12915
- min_bytes: check.min_bytes ?? null,
12916
- allowed_content_types: check.allowed_content_types ?? null
12917
- }));
12918
- if (stringValue6(linkEvidence.error)) {
12919
- failures.push({ code: "link_status_capture_failed", error: stringValue6(linkEvidence.error) ?? "" });
12920
- }
12921
- const recordedFailedCount = numberValue4(linkEvidence.failed_count) ?? 0;
12922
- if (!failures.length && recordedFailedCount > 0) {
12923
- const recordedFailures = Array.isArray(linkEvidence.failures) ? linkEvidence.failures.slice(0, 20) : [];
12924
- failures.push({
12925
- code: "link_status_recorded_failures",
12926
- failed_count: recordedFailedCount,
12927
- failures: toJsonValue(recordedFailures)
12928
- });
12929
- }
12930
- if (linkEvidence.truncated === true) {
12931
- failures.push({
12932
- code: "link_status_probe_truncated",
12933
- discovered_count: numberValue4(linkEvidence.discovered_count) ?? totalCount,
12934
- max_links: numberValue4(linkEvidence.max_links) ?? check.max_links ?? 100
12935
- });
12936
- }
12937
- if (check.expected_count !== void 0 && totalCount !== check.expected_count) {
12938
- failures.push({ code: "link_status_count_mismatch", expected: check.expected_count, actual: totalCount });
12939
- }
12940
- if (check.min_count !== void 0 && totalCount < check.min_count) {
12941
- failures.push({ code: "link_status_count_below_minimum", min_count: check.min_count, actual: totalCount });
12942
- }
12943
- const statusCounts = isRecord2(linkEvidence.status_counts) ? linkEvidence.status_counts : {};
12944
- return {
12945
- viewport: viewport.name,
12946
- selector: linkStatusSelector(check),
12947
- total_count: totalCount,
12948
- discovered_count: numberValue4(linkEvidence.discovered_count) ?? totalCount,
12949
- ok_count: numberValue4(linkEvidence.ok_count) ?? okCount,
12950
- failed_count: failures.length,
12951
- truncated: linkEvidence.truncated === true,
12952
- max_links: numberValue4(linkEvidence.max_links) ?? check.max_links ?? 100,
12953
- result_count: resultCount,
12954
- stored_result_count: storedResultCount,
12955
- omitted_result_count: omittedResultCount,
12956
- omitted_success_count: omittedSuccessCount,
12957
- results_compacted: linkEvidence.results_compacted === true || omittedResultCount > 0,
12958
- min_bytes: check.min_bytes ?? null,
12959
- allowed_content_types: check.allowed_content_types ?? null,
12960
- status_counts: statusCounts,
12961
- failures: failures.slice(0, 20)
12962
- };
12963
- }
12964
- function textKey(check) {
12965
- return check.pattern ? `pattern:${check.pattern}/${check.flags || ""}` : `text:${check.text || ""}`;
12966
- }
12967
- function observeWithinTimeoutMs(check) {
12968
- const raw = check.timeout_ms;
12969
- if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) return Math.min(Math.round(raw), 6e4);
12970
- return 2e3;
12971
- }
12972
- function observeWithinKey(check) {
12973
- const target = check.selector ? `selector:${check.selector}` : "page";
12974
- const expectation = check.pattern ? `pattern:${check.pattern}/${check.flags || ""}` : check.text ? `text:${check.text}` : "visible";
12975
- return `${target}|${expectation}|within:${observeWithinTimeoutMs(check)}`;
12976
- }
12977
- function textSequenceForCheck(viewport, check) {
12978
- const key = selectorKey(check);
12979
- const sequence = viewport.text_sequences?.[key];
12980
- if (isRecord2(sequence)) {
12981
- const visibleMatchTexts = Array.isArray(sequence.visible_match_texts) ? sequence.visible_match_texts : [];
12982
- const matchTexts = Array.isArray(sequence.match_texts) ? sequence.match_texts : [];
12983
- const visibleTexts = Array.isArray(sequence.visible_texts) ? sequence.visible_texts : [];
12984
- const texts = Array.isArray(sequence.texts) ? sequence.texts : [];
12985
- let candidates;
12986
- if (check.type === "selector_text_visible") {
12987
- candidates = visibleMatchTexts.length ? visibleMatchTexts : visibleTexts;
12988
- } else if (check.type === "selector_text_absent") {
12989
- candidates = matchTexts.length ? matchTexts : texts;
12990
- } else {
12991
- candidates = visibleMatchTexts.length ? visibleMatchTexts : matchTexts.length ? matchTexts : visibleTexts.length ? visibleTexts : texts;
12992
- }
12993
- return candidates.map((text) => String(text).replace(/\s+/g, " ").trim()).filter(Boolean);
12994
- }
12995
- return [];
12996
- }
12997
- function textOrderMatch(texts, expectedTexts) {
12998
- const positions = [];
12999
- let startAt = 0;
13000
- for (const expected of expectedTexts) {
13001
- const index = texts.findIndex((text, offset) => offset >= startAt && text.includes(expected));
13002
- if (index < 0) return { matched: false, positions };
13003
- positions.push(index);
13004
- startAt = index + 1;
13005
- }
13006
- return { matched: true, positions };
13007
- }
13008
- function frameEvidenceForSelector(viewport, selector) {
13009
- const container = viewport.frames?.[selector];
13010
- if (!isRecord2(container)) return [];
13011
- const frames = Array.isArray(container.frames) ? container.frames : [];
13012
- return frames.filter((frame) => isRecord2(frame));
13013
- }
13014
- function frameTextSample(frame) {
13015
- const parts = [
13016
- frame.title,
13017
- frame.text_sample,
13018
- frame.body_text_sample,
13019
- frame.body_text,
13020
- frame.text
13021
- ];
13022
- return parts.map((part) => String(part || "")).filter(Boolean).join(" ");
13023
- }
13024
- function summarizeRouteInventory(viewport, inventory) {
13025
- const directRoutes = Array.isArray(inventory.direct_routes) ? inventory.direct_routes : [];
13026
- const clickthroughs = Array.isArray(inventory.clickthroughs) ? inventory.clickthroughs : [];
13027
- const sourceLinkCount = numberValue4(inventory.source_link_count) ?? numberValue4(inventory.home_game_link_count) ?? null;
13028
- const sourceUniqueLinkCount = numberValue4(inventory.source_unique_link_count) ?? numberValue4(inventory.home_unique_game_link_count) ?? null;
13029
- const sourceCandidateCount = numberValue4(inventory.source_candidate_count);
13030
- const sourceCandidateUniqueLinkCount = numberValue4(inventory.source_candidate_unique_link_count);
13031
- const sourceLinkScope = stringValue6(inventory.source_link_scope);
13032
- const duplicateSourceLinks = Array.isArray(inventory.duplicate_source_link_paths) ? inventory.duplicate_source_link_paths.map((path5) => String(path5)) : [];
13033
- const duplicateSourceLinkCount = numberValue4(inventory.duplicate_source_link_count) ?? (sourceLinkCount !== null && sourceUniqueLinkCount !== null ? Math.max(0, sourceLinkCount - sourceUniqueLinkCount) : null);
13034
- const failures = Array.isArray(inventory.failures) ? inventory.failures : [];
13035
- return {
13036
- viewport,
13037
- source_link_scope: sourceLinkScope ?? null,
13038
- source_candidate_count: sourceCandidateCount ?? sourceLinkCount,
13039
- source_candidate_unique_link_count: sourceCandidateUniqueLinkCount ?? sourceUniqueLinkCount,
13040
- source_link_count: sourceLinkCount,
13041
- source_unique_link_count: sourceUniqueLinkCount,
13042
- duplicate_source_link_count: duplicateSourceLinkCount,
13043
- duplicate_source_links: duplicateSourceLinks,
13044
- direct_route_count: directRoutes.length,
13045
- clickthrough_count: clickthroughs.length,
13046
- failure_count: failures.length
13047
- };
13048
- }
13049
- function routeInventoryExpectedRouteSummaries(value, fallback) {
13050
- const rawRoutes = Array.isArray(value) ? value : Array.isArray(fallback) ? fallback : [];
13051
- return rawRoutes.map((route) => {
13052
- if (typeof route === "string") {
13053
- const path6 = route.trim();
13054
- return path6 ? { path: path6 } : void 0;
13055
- }
13056
- if (!isRecord2(route)) return void 0;
13057
- const path5 = stringValue6(route.path);
13058
- if (!path5) return void 0;
13059
- const name = stringValue6(route.name);
13060
- return name ? { name, path: path5 } : { path: path5 };
13061
- }).filter((route) => Boolean(route));
13062
- }
13063
- function matchText(sample, check) {
13064
- if (check.pattern) {
13065
- try {
13066
- return new RegExp(check.pattern, check.flags || "").test(sample);
13067
- } catch {
13068
- return false;
13069
- }
13070
- }
13071
- return sample.includes(check.text || "");
13072
- }
13073
- function compactTextEvidenceSample(value) {
13074
- return String(value || "").replace(/\s+/g, " ").trim();
13075
- }
13076
- function textSampleAroundMatch(sample, index, length) {
13077
- if (index < 0) return void 0;
13078
- const source = String(sample || "");
13079
- const context = 120;
13080
- const start = Math.max(0, index - context);
13081
- const end = Math.min(source.length, index + Math.max(length, 1) + context);
13082
- const prefix = start > 0 ? "..." : "";
13083
- const suffix = end < source.length ? "..." : "";
13084
- const compacted = compactTextEvidenceSample(`${prefix}${source.slice(start, end)}${suffix}`);
13085
- return compacted ? compacted.slice(0, 240) : void 0;
13086
- }
13087
- function textMatchSamples(sample, check) {
13088
- const source = String(sample || "");
13089
- if (!source) return [];
13090
- if (check.pattern) {
13091
- try {
13092
- const flags = Array.from(new Set(String(check.flags || "").replace(/[gy]/g, "").split(""))).join("");
13093
- const match = new RegExp(check.pattern, flags).exec(source);
13094
- const sampleText2 = match ? textSampleAroundMatch(source, match.index, match[0]?.length || 1) : void 0;
13095
- return sampleText2 ? [sampleText2] : [];
13096
- } catch {
13097
- return [];
13098
- }
13099
- }
13100
- const text = check.text || "";
13101
- if (!text) return [];
13102
- const index = source.indexOf(text);
13103
- const sampleText = textSampleAroundMatch(source, index, text.length);
13104
- return sampleText ? [sampleText] : [];
13105
- }
13106
- function textCaseInsensitiveSamples(sample, check) {
13107
- const source = String(sample || "");
13108
- const text = check.pattern ? "" : check.text || "";
13109
- if (!source || !text) return [];
13110
- const index = source.toLowerCase().indexOf(text.toLowerCase());
13111
- const sampleText = textSampleAroundMatch(source, index, text.length);
13112
- return sampleText ? [sampleText] : [];
13113
- }
13114
- function textCaseInsensitiveSequenceSamples(texts, check) {
13115
- const text = check.pattern ? "" : compactTextEvidenceSample(check.text || "");
13116
- if (!text) return [];
13117
- const expected = text.toLowerCase();
13118
- return texts.map((candidate) => compactTextEvidenceSample(candidate)).filter((candidate) => candidate && candidate.toLowerCase().includes(expected)).slice(0, 3).map((candidate) => candidate.slice(0, 240));
13119
- }
13120
- function textCaseInsensitiveFailureSamples(viewport, check) {
13121
- const key = textKey(check);
13122
- const captured = viewport.text_case_insensitive_samples?.[key] || [];
13123
- const capturedSamples = captured.map((sample) => compactTextEvidenceSample(sample).slice(0, 240)).filter(Boolean);
13124
- if (capturedSamples.length) return capturedSamples.slice(0, 3);
13125
- return textCaseInsensitiveSamples(viewport.body_text_sample || "", check).slice(0, 3);
13126
- }
13127
- function textCheckFailureSamples(viewport, check) {
13128
- const key = textKey(check);
13129
- const captured = viewport.text_match_samples?.[key] || [];
13130
- const capturedSamples = captured.map((sample) => compactTextEvidenceSample(sample).slice(0, 240)).filter(Boolean);
13131
- if (capturedSamples.length) return capturedSamples.slice(0, 3);
13132
- const matchedSamples = textMatchSamples(viewport.body_text_sample || "", check);
13133
- if (matchedSamples.length) return matchedSamples.slice(0, 3);
13134
- const fallback = compactTextEvidenceSample(viewport.body_text_sample || "").slice(0, 240);
13135
- return fallback ? [fallback] : [];
13136
- }
13137
- function allowedMessageSample(input) {
13138
- if (!isRecord2(input)) return String(input || "");
13139
- const parts = [
13140
- input.text,
13141
- input.message,
13142
- isRecord2(input.location) ? input.location.url : void 0
13143
- ];
13144
- return parts.map((part) => String(part || "")).filter(Boolean).join(" ");
13145
- }
13146
- function matchesAllowedMessage(input, texts, patterns) {
13147
- const sample = allowedMessageSample(input);
13148
- if (texts?.some((text) => sample.includes(text))) return true;
13149
- for (const pattern of patterns || []) {
13150
- try {
13151
- if (new RegExp(pattern).test(sample)) return true;
13152
- } catch {
13153
- continue;
13154
- }
13155
- }
13156
- return false;
13157
- }
13158
- function consoleEventLocationUrl(input) {
13159
- if (!isRecord2(input) || !isRecord2(input.location)) return void 0;
13160
- return stringValue6(input.location.url);
13161
- }
13162
- function expectedFailedNetworkMockEvents(evidence) {
13163
- return (evidence.network_mocks || []).filter((event) => {
13164
- if (!isRecord2(event) || event.ok === false) return false;
13165
- const status = numberValue4(event.status);
13166
- const isHttpFailure = status !== void 0 && status >= 400;
13167
- const isAbortedMock = event.abort === true && Boolean(stringValue6(event.abort_error_code));
13168
- return (isHttpFailure || isAbortedMock) && Boolean(stringValue6(event.url));
13169
- });
13170
- }
13171
- function matchingExpectedFailedNetworkMockConsoleEvent(event, evidence) {
13172
- const sample = allowedMessageSample(event);
13173
- if (!/Failed to load resource/i.test(sample)) return void 0;
13174
- const eventUrl = consoleEventLocationUrl(event);
13175
- if (!eventUrl) return void 0;
13176
- return expectedFailedNetworkMockEvents(evidence).find((mockEvent) => {
13177
- const status = numberValue4(mockEvent.status);
13178
- const abortErrorCode = stringValue6(mockEvent.abort_error_code);
13179
- return stringValue6(mockEvent.url) === eventUrl && (status !== void 0 && sample.includes(String(status)) || Boolean(abortErrorCode) && /Failed to load resource/i.test(sample));
13180
- });
13181
- }
13182
- function isExpectedFailedNetworkMockConsoleEvent(event, evidence) {
13183
- return Boolean(matchingExpectedFailedNetworkMockConsoleEvent(event, evidence));
13184
- }
13185
- function expectedFailedNetworkMockConsoleEventSummary(event, evidence) {
13186
- const match = matchingExpectedFailedNetworkMockConsoleEvent(event, evidence);
13187
- const sample = allowedMessageSample(event);
13188
- return {
13189
- url: consoleEventLocationUrl(event) ?? null,
13190
- status: match ? numberValue4(match.status) ?? null : null,
13191
- abort_error_code: match ? stringValue6(match.abort_error_code) ?? null : null,
13192
- label: match ? stringValue6(match.label) ?? null : null,
13193
- response_label: match ? stringValue6(match.response_label) ?? null : null,
13194
- text: isRecord2(event) && typeof event.text === "string" ? event.text.slice(0, 300) : sample.slice(0, 300)
13195
- };
13196
- }
13197
- function normalizeRoutePath2(path5) {
13198
- const value = path5 || "/";
13199
- if (value === "/") return "/";
13200
- return value.replace(/\/+$/, "") || "/";
13201
- }
13202
- function previewMountPrefix(pathname) {
13203
- const value = pathname || "/";
13204
- const apiPreview = value.match(/^(\/s\/[^/]+)(?:\/|$)/);
13205
- if (apiPreview) return apiPreview[1];
13206
- const internalPreview = value.match(/^(\/preview\/[^/]+\/[^/]+)(?:\/|$)/);
13207
- return internalPreview ? internalPreview[1] : "";
13208
- }
13209
- function joinMountedRoutePath(mountPrefix, routePath) {
13210
- const route = routePath.startsWith("/") ? routePath : `/${routePath}`;
13211
- if (!mountPrefix) return route;
13212
- if (route === mountPrefix || route.startsWith(`${mountPrefix}/`)) return route;
13213
- return `${mountPrefix}${route}`;
13214
- }
13215
- function resolveRiddleProofProfileRouteUrl(targetUrl, route) {
13216
- if (/^https?:\/\//i.test(route)) return route;
13217
- if (!targetUrl) return route;
13218
- if (route.startsWith("/")) {
13219
- const base = new URL(targetUrl);
13220
- const mountPrefix = previewMountPrefix(base.pathname);
13221
- if (mountPrefix) {
13222
- const routeParts = new URL(route, base.origin);
13223
- base.pathname = joinMountedRoutePath(mountPrefix, routeParts.pathname);
13224
- base.search = routeParts.search;
13225
- base.hash = routeParts.hash;
13226
- return base.href;
13227
- }
13228
- }
13229
- return new URL(route, targetUrl).href;
13230
- }
13231
- function mountedExpectedRoutePath(targetUrl, expected) {
13232
- if (!targetUrl || !expected || !expected.startsWith("/")) return expected;
13233
- const mountPrefix = previewMountPrefix(new URL(targetUrl).pathname);
13234
- return mountPrefix ? joinMountedRoutePath(mountPrefix, expected) : expected;
13235
- }
13236
- function routePathMatches(observed, expected, targetUrl) {
13237
- const normalizedObserved = normalizeRoutePath2(observed);
13238
- const normalizedExpected = normalizeRoutePath2(expected);
13239
- if (normalizedObserved === normalizedExpected) return true;
13240
- return normalizedObserved === normalizeRoutePath2(mountedExpectedRoutePath(targetUrl, expected));
13241
- }
13242
- function successfulRoute(route, targetUrl) {
13243
- const matched = route.matched || routePathMatches(route.observed, route.expected_path, targetUrl);
13244
- return matched && !route.error && (route.http_status === null || route.http_status === void 0 || route.http_status < 400);
13245
- }
13246
- function routeReadinessFailed(route, targetUrl) {
13247
- const matched = route.matched || routePathMatches(route.observed, route.expected_path, targetUrl);
13248
- const httpOk = route.http_status === null || route.http_status === void 0 || route.http_status < 400;
13249
- return matched && httpOk && Boolean(route.error);
13250
- }
13251
- function compactRouteError(error) {
13252
- const text = typeof error === "string" ? error.replace(/\s+/g, " ").trim() : "";
13253
- return text ? text.slice(0, 240) : void 0;
13254
- }
13255
- function routeLoadedFailureMessage(failedRoutes, expectedPath, targetUrl) {
13256
- const readinessFailures = failedRoutes.filter((route) => routeReadinessFailed(route, targetUrl));
13257
- if (readinessFailures.length === failedRoutes.length && readinessFailures.length) {
13258
- const sample = compactRouteError(readinessFailures.find((route) => route.error)?.error);
13259
- return `Route matched ${expectedPath}, but readiness failed in ${readinessFailures.length} viewport(s)${sample ? `: ${sample}` : "."}`;
13260
- }
13261
- if (readinessFailures.length) {
13262
- const sample = compactRouteError(readinessFailures.find((route) => route.error)?.error);
13263
- return `Route did not become ready as ${expectedPath} in ${failedRoutes.length} viewport(s); ${readinessFailures.length} matched path and HTTP but failed readiness${sample ? `: ${sample}` : "."}`;
13264
- }
13265
- return `Route did not load as ${expectedPath} in ${failedRoutes.length} viewport(s).`;
13266
- }
13267
- function parseEvidenceUrl(value, targetUrl) {
13268
- if (!value) return void 0;
13269
- try {
13270
- return targetUrl ? new URL(value, targetUrl) : new URL(value);
13271
- } catch {
13272
- try {
13273
- return new URL(value);
13274
- } catch {
13275
- return void 0;
13276
- }
13277
- }
13278
- }
13279
- function observedUrlForViewport(viewport, targetUrl) {
13280
- return parseEvidenceUrl(viewport.url, targetUrl) || parseEvidenceUrl(viewport.route?.observed, targetUrl) || parseEvidenceUrl(viewport.route?.requested, targetUrl) || parseEvidenceUrl(targetUrl, void 0);
13281
- }
13282
- function searchParamObservation(viewport, targetUrl, param) {
13283
- const url = observedUrlForViewport(viewport, targetUrl);
13284
- const values = url ? url.searchParams.getAll(param) : [];
13285
- return {
13286
- viewport: viewport.name,
13287
- url: url?.href || null,
13288
- value: values.length ? values[0] : null,
13289
- values,
13290
- present: values.length > 0
13291
- };
13292
- }
13293
- function viewportsForCheck(check, viewports) {
13294
- if (!check.viewports?.length) return viewports;
13295
- const names = new Set(check.viewports);
13296
- return viewports.filter((viewport) => names.has(viewport.name));
13297
- }
13298
- function setupActionAppliesToViewport(action, viewportName) {
13299
- if (!action.viewports?.length) return true;
13300
- return Boolean(viewportName && action.viewports.includes(viewportName));
13301
- }
13302
- function setupActionsForViewport(actions, viewportName) {
13303
- return (actions || []).filter((action) => setupActionAppliesToViewport(action, viewportName));
13304
- }
13305
- function assessCheckFromEvidence(check, evidence) {
13306
- const viewports = viewportsForCheck(check, evidence.viewports || []);
13307
- if (!viewports.length) {
13308
- return {
13309
- type: check.type,
13310
- label: checkLabel(check),
13311
- status: "failed",
13312
- evidence: {
13313
- expected_viewports: check.viewports || []
13314
- },
13315
- message: check.viewports?.length ? `No matching viewport evidence was captured for ${check.viewports.join(", ")}.` : "No viewport evidence was captured."
13316
- };
13317
- }
13318
- if (isDialogCountCheckType(check.type)) {
13319
- const field = dialogCountFieldForCheckType(check.type);
13320
- const expectedCount = check.expected_count ?? 0;
13321
- const actualCount = numberValue4(evidence.dom_summary?.[field]) ?? 0;
13322
- return {
13323
- type: check.type,
13324
- label: checkLabel(check),
13325
- status: actualCount === expectedCount ? "passed" : "failed",
13326
- evidence: {
13327
- field,
13328
- expected_count: expectedCount,
13329
- count: actualCount
13330
- },
13331
- message: actualCount === expectedCount ? void 0 : `${field} did not equal ${expectedCount}; observed ${actualCount}.`
13332
- };
13333
- }
13334
- if (check.type === "route_loaded") {
13335
- const expectedPath = check.expected_path || new URL(evidence.target_url).pathname || "/";
13336
- const routes = viewports.map((viewport) => ({
13337
- ...viewport.route,
13338
- expected_path: expectedPath,
13339
- matched: routePathMatches(viewport.route.observed, expectedPath, evidence.target_url) || viewport.route.matched
13340
- }));
13341
- const failed = routes.filter((route) => !successfulRoute(route, evidence.target_url));
13342
- return {
13343
- type: check.type,
13344
- label: checkLabel(check),
13345
- status: failed.length ? "failed" : "passed",
13346
- evidence: {
13347
- expected_path: expectedPath,
13348
- observed_paths: viewports.map((viewport) => viewport.route.observed),
13349
- http_statuses: viewports.map((viewport) => viewport.route.http_status ?? null),
13350
- route_errors: viewports.map((viewport) => viewport.route.error ?? null)
13351
- },
13352
- message: failed.length ? routeLoadedFailureMessage(failed, expectedPath, evidence.target_url) : void 0
13353
- };
13354
- }
13355
- if (check.type === "url_search_param_equals") {
13356
- const param = check.param || "";
13357
- const expectedValue = check.expected_value ?? "";
13358
- const observations = viewports.map((viewport) => searchParamObservation(viewport, evidence.target_url, param));
13359
- const failed = observations.filter((observation) => observation.value !== expectedValue);
13360
- return {
13361
- type: check.type,
13362
- label: checkLabel(check),
13363
- status: failed.length ? "failed" : "passed",
13364
- evidence: {
13365
- param,
13366
- expected_value: expectedValue,
13367
- observed_values: observations.map((observation) => observation.value),
13368
- observed_all_values: observations.map((observation) => observation.values),
13369
- observed_urls: observations.map((observation) => observation.url),
13370
- viewports: observations.map((observation) => toJsonValue(observation))
13371
- },
13372
- message: failed.length ? `URL search param ${param} did not equal ${JSON.stringify(expectedValue)} in ${failed.length} viewport(s).` : void 0
13373
- };
13374
- }
13375
- if (check.type === "url_search_param_absent") {
13376
- const param = check.param || "";
13377
- const observations = viewports.map((viewport) => searchParamObservation(viewport, evidence.target_url, param));
13378
- const failed = observations.filter((observation) => observation.present);
13379
- return {
13380
- type: check.type,
13381
- label: checkLabel(check),
13382
- status: failed.length ? "failed" : "passed",
13383
- evidence: {
13384
- param,
13385
- observed_values: observations.map((observation) => observation.value),
13386
- observed_all_values: observations.map((observation) => observation.values),
13387
- observed_urls: observations.map((observation) => observation.url),
13388
- viewports: observations.map((observation) => toJsonValue(observation))
13389
- },
13390
- message: failed.length ? `URL search param ${param} was present in ${failed.length} viewport(s).` : void 0
13391
- };
13392
- }
13393
- if (check.type === "selector_visible") {
13394
- const key = selectorKey(check);
13395
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.visible_count || 0) < 1);
13396
- return {
13397
- type: check.type,
13398
- label: checkLabel(check),
13399
- status: failed.length ? "failed" : "passed",
13400
- evidence: {
13401
- selector: key,
13402
- visible_counts: viewports.map((viewport) => viewport.selectors?.[key]?.visible_count || 0)
13403
- },
13404
- message: failed.length ? `Selector ${key} was not visible in ${failed.length} viewport(s).` : void 0
13405
- };
13406
- }
13407
- if (check.type === "selector_absent") {
13408
- const key = selectorKey(check);
13409
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.count || 0) > 0);
13410
- return {
13411
- type: check.type,
13412
- label: checkLabel(check),
13413
- status: failed.length ? "failed" : "passed",
13414
- evidence: {
13415
- selector: key,
13416
- counts: viewports.map((viewport) => viewport.selectors?.[key]?.count || 0)
13417
- },
13418
- message: failed.length ? `Selector ${key} was present in ${failed.length} viewport(s).` : void 0
13419
- };
13420
- }
13421
- if (check.type === "selector_count_at_least") {
13422
- const key = selectorKey(check);
13423
- const minCount = check.min_count ?? 1;
13424
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.count || 0) < minCount);
13425
- return {
13426
- type: check.type,
13427
- label: checkLabel(check),
13428
- status: failed.length ? "failed" : "passed",
13429
- evidence: {
13430
- selector: key,
13431
- min_count: minCount,
13432
- counts: viewports.map((viewport) => viewport.selectors?.[key]?.count || 0)
13433
- },
13434
- message: failed.length ? `Selector ${key} count was below ${minCount} in ${failed.length} viewport(s).` : void 0
13435
- };
13436
- }
13437
- if (check.type === "selector_count_equals" || check.type === "selector_count_equal" || check.type === "selector_count_eq") {
13438
- const key = selectorKey(check);
13439
- const expectedCount = check.expected_count ?? 0;
13440
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.count || 0) !== expectedCount);
13441
- return {
13442
- type: check.type,
13443
- label: checkLabel(check),
13444
- status: failed.length ? "failed" : "passed",
13445
- evidence: {
13446
- selector: key,
13447
- expected_count: expectedCount,
13448
- counts: viewports.map((viewport) => viewport.selectors?.[key]?.count || 0)
13449
- },
13450
- message: failed.length ? `Selector ${key} count did not equal ${expectedCount} in ${failed.length} viewport(s).` : void 0
13451
- };
13452
- }
13453
- if (check.type === "selector_text_visible" || check.type === "selector_text_absent") {
13454
- const key = selectorKey(check);
13455
- const expectedVisible = check.type === "selector_text_visible";
13456
- const results = viewports.map((viewport) => {
13457
- const texts = textSequenceForCheck(viewport, check);
13458
- const matches = texts.filter((text) => matchText(text, check));
13459
- const matched = matches.length > 0;
13460
- const failedAgainstExpectation = matched !== expectedVisible;
13461
- const sampleTexts = matches.length ? matches : failedAgainstExpectation ? texts : [];
13462
- const caseInsensitiveSamples = failedAgainstExpectation && expectedVisible && !matched ? textCaseInsensitiveSequenceSamples(texts, check) : [];
13463
- return {
13464
- viewport: viewport.name,
13465
- selector_count: viewport.selectors?.[key]?.count || 0,
13466
- visible_count: viewport.selectors?.[key]?.visible_count || 0,
13467
- matched_count: matches.length,
13468
- matched,
13469
- samples: sampleTexts.slice(0, 3).map((text) => text.slice(0, 240)),
13470
- case_insensitive_samples: caseInsensitiveSamples
13471
- };
13472
- });
13473
- const failed = results.filter((result) => result.matched !== expectedVisible).length;
13474
- return {
13475
- type: check.type,
13476
- label: checkLabel(check),
13477
- status: failed ? "failed" : "passed",
13478
- evidence: {
13479
- selector: key,
13480
- text: check.text || null,
13481
- pattern: check.pattern || null,
13482
- viewports: results.map((result) => toJsonValue(result))
13483
- },
13484
- message: failed ? `Selector ${key} text assertion failed in ${failed} viewport(s).` : void 0
13485
- };
13486
- }
13487
- if (check.type === "selector_text_order") {
13488
- const key = selectorKey(check);
13489
- const expectedTexts = check.expected_texts || [];
13490
- const results = viewports.map((viewport) => {
13491
- const texts = textSequenceForCheck(viewport, check);
13492
- const match = textOrderMatch(texts, expectedTexts);
13493
- return {
13494
- viewport: viewport.name,
13495
- matched: match.matched,
13496
- matched_positions: match.positions,
13497
- visible_texts: texts.slice(0, 20).map((text) => text.slice(0, 240))
13498
- };
13499
- });
13500
- const failed = results.filter((result) => !result.matched).length;
13501
- return {
13502
- type: check.type,
13503
- label: checkLabel(check),
13504
- status: failed ? "failed" : "passed",
13505
- evidence: {
13506
- selector: key,
13507
- expected_texts: expectedTexts,
13508
- viewports: results.map((result) => toJsonValue(result))
13509
- },
13510
- message: failed ? `Selector ${key} text order failed in ${failed} viewport(s).` : void 0
13511
- };
13512
- }
13513
- if (check.type === "ordered_trace") {
13514
- const assessments = viewports.map((viewport) => ({
13515
- viewport: viewport.name,
13516
- assessment: assessRiddleProofOrderedTraceSetupResults(
13517
- viewport.setup_action_results,
13518
- check.setup_action_label || "",
13519
- check.trace_path || "",
13520
- check.events || []
13521
- )
13522
- }));
13523
- const insufficient = assessments.filter((item) => item.assessment.status === "proof_insufficient");
13524
- const failed = assessments.filter((item) => item.assessment.status === "failed");
13525
- const status = insufficient.length ? "proof_insufficient" : failed.length ? "failed" : "passed";
13526
- return {
13527
- type: check.type,
13528
- label: checkLabel(check),
13529
- status,
13530
- evidence: {
13531
- setup_action_label: check.setup_action_label || "",
13532
- trace_path: check.trace_path || "",
13533
- events: toJsonValue((check.events || []).map((event) => event.label)),
13534
- viewports: toJsonValue(assessments)
13535
- },
13536
- message: insufficient.length ? `Ordered trace evidence was insufficient in ${insufficient.length} viewport(s).` : failed.length ? `Ordered trace did not contain the required event sequence in ${failed.length} viewport(s).` : void 0
13537
- };
13538
- }
13539
- if (check.type === "observe_within") {
13540
- const key = observeWithinKey(check);
13541
- const timeoutMs = observeWithinTimeoutMs(check);
13542
- const results = viewports.map((viewport) => {
13543
- const observation = viewport.observations?.[key];
13544
- const matched = observation?.matched === true;
13545
- return {
13546
- viewport: viewport.name,
13547
- matched,
13548
- elapsed_ms: numberValue4(observation?.elapsed_ms) ?? null,
13549
- timeout_ms: numberValue4(observation?.timeout_ms) ?? timeoutMs,
13550
- attempts: numberValue4(observation?.attempts) ?? null,
13551
- selector_count: numberValue4(observation?.selector_count) ?? null,
13552
- visible_count: numberValue4(observation?.visible_count) ?? null,
13553
- matched_count: numberValue4(observation?.matched_count) ?? null,
13554
- sample: stringValue6(observation?.sample) ?? null,
13555
- error: stringValue6(observation?.error) ?? null
13556
- };
13557
- });
13558
- const failed = results.filter((result) => !result.matched).length;
13559
- return {
13560
- type: check.type,
13561
- label: checkLabel(check),
13562
- status: failed ? "failed" : "passed",
13563
- evidence: {
13564
- selector: check.selector || null,
13565
- text: check.text || null,
13566
- pattern: check.pattern || null,
13567
- timeout_ms: timeoutMs,
13568
- viewports: results.map((result) => toJsonValue(result))
13569
- },
13570
- message: failed ? `Observation did not match within ${timeoutMs}ms in ${failed} viewport(s).` : void 0
13571
- };
13572
- }
13573
- if (check.type === "frame_text_visible") {
13574
- const key = selectorKey(check);
13575
- const results = viewports.map((viewport) => {
13576
- const frames = frameEvidenceForSelector(viewport, key);
13577
- const matches = frames.map((frame, index) => ({ index, frame, matched: matchText(frameTextSample(frame), check) })).filter((item) => item.matched);
13578
- return {
13579
- viewport: viewport.name,
13580
- frame_count: frames.length,
13581
- matched_count: matches.length,
13582
- matched: matches.length > 0,
13583
- urls: frames.map((frame) => String(frame.url || "")).filter(Boolean).slice(0, 10),
13584
- samples: matches.map((item) => frameTextSample(item.frame).replace(/\s+/g, " ").trim().slice(0, 240)).slice(0, 3)
13585
- };
13586
- });
13587
- const failed = results.filter((result) => !result.matched).length;
13588
- return {
13589
- type: check.type,
13590
- label: checkLabel(check),
13591
- status: failed ? "failed" : "passed",
13592
- evidence: {
13593
- selector: key,
13594
- text: check.text || null,
13595
- pattern: check.pattern || null,
13596
- viewports: results.map((result) => toJsonValue(result))
13597
- },
13598
- message: failed ? `Frame selector ${key} did not contain expected text in ${failed} viewport(s).` : void 0
13599
- };
13600
- }
13601
- if (check.type === "frame_url_equals" || check.type === "frame_url_matches") {
13602
- const key = selectorKey(check);
13603
- const expectedUrl = check.expected_url || check.expected_value || "";
13604
- const results = viewports.map((viewport) => {
13605
- const frames = frameEvidenceForSelector(viewport, key);
13606
- const urls = frames.map((frame) => String(frame.url || "")).filter(Boolean);
13607
- const matches = urls.filter((url) => check.type === "frame_url_equals" ? url === expectedUrl : matchText(url, check));
13608
- return {
13609
- viewport: viewport.name,
13610
- frame_count: frames.length,
13611
- matched_count: matches.length,
13612
- matched: matches.length > 0,
13613
- urls: urls.slice(0, 10)
13614
- };
13615
- });
13616
- const failed = results.filter((result) => !result.matched).length;
13617
- return {
13618
- type: check.type,
13619
- label: checkLabel(check),
13620
- status: failed ? "failed" : "passed",
13621
- evidence: {
13622
- selector: key,
13623
- expected_url: check.type === "frame_url_equals" ? expectedUrl : null,
13624
- pattern: check.type === "frame_url_matches" ? check.pattern || null : null,
13625
- viewports: results.map((result) => toJsonValue(result))
13626
- },
13627
- message: failed ? `Frame selector ${key} URL assertion failed in ${failed} viewport(s).` : void 0
13628
- };
13629
- }
13630
- if (check.type === "frame_no_horizontal_overflow") {
13631
- const key = selectorKey(check);
13632
- const maxOverflow = check.max_overflow_px ?? 4;
13633
- const results = viewports.map((viewport) => {
13634
- const frames = frameEvidenceForSelector(viewport, key);
13635
- const frameOverflows = frames.map((frame, index) => ({
13636
- index,
13637
- url: String(frame.url || ""),
13638
- overflow_px: horizontalBoundsOverflowPx2(frame),
13639
- offender_count: boundsOffendersForEvidence2(frame).length
13640
- }));
13641
- const maxFrameOverflow = frameOverflows.reduce((max, frame) => Math.max(max, frame.overflow_px), 0);
13642
- return {
13643
- viewport: viewport.name,
13644
- frame_count: frames.length,
13645
- max_overflow_px: roundPixels2(maxFrameOverflow),
13646
- failed_frame_count: frameOverflows.filter((frame) => frame.overflow_px > maxOverflow).length,
13647
- frames: frameOverflows.map((frame) => toJsonValue(frame))
13648
- };
13649
- });
13650
- const failed = results.filter((result) => result.frame_count < 1 || result.failed_frame_count > 0).length;
13651
- return {
13652
- type: check.type,
13653
- label: checkLabel(check),
13654
- status: failed ? "failed" : "passed",
13655
- evidence: {
13656
- selector: key,
13657
- max_overflow_px: maxOverflow,
13658
- viewports: results.map((result) => toJsonValue(result))
13659
- },
13660
- message: failed ? `Frame selector ${key} overflow exceeded ${maxOverflow}px or was missing in ${failed} viewport(s).` : void 0
13661
- };
13662
- }
13663
- if (check.type === "text_visible" || check.type === "text_absent") {
13664
- const key = textKey(check);
13665
- const expectedVisible = check.type === "text_visible";
13666
- const results = viewports.map((viewport) => {
13667
- const fromEvidence = viewport.text_matches?.[key];
13668
- const matched = typeof fromEvidence === "boolean" ? fromEvidence : matchText(viewport.body_text_sample || "", check);
13669
- const failedAgainstExpectation = matched !== expectedVisible;
13670
- return {
13671
- viewport: viewport.name,
13672
- matched,
13673
- samples: failedAgainstExpectation ? textCheckFailureSamples(viewport, check) : [],
13674
- case_insensitive_samples: failedAgainstExpectation && expectedVisible && !matched ? textCaseInsensitiveFailureSamples(viewport, check) : []
13675
- };
13676
- });
13677
- const matches = results.map((result) => result.matched);
13678
- const failed = matches.filter((matched) => matched !== expectedVisible).length;
13679
- return {
13680
- type: check.type,
13681
- label: checkLabel(check),
13682
- status: failed ? "failed" : "passed",
13683
- evidence: {
13684
- text: check.text || null,
13685
- pattern: check.pattern || null,
13686
- matches,
13687
- viewports: results.map((result) => toJsonValue(result))
13688
- },
13689
- message: failed ? `Text assertion failed in ${failed} viewport(s).` : void 0
13690
- };
13691
- }
13692
- if (check.type === "http_status") {
13693
- const url = httpStatusRequestUrl(check, evidence.target_url);
13694
- const method = httpStatusMethod(check);
13695
- const summaries = viewports.map((viewport) => summarizeHttpStatusEvidence(viewport, check));
13696
- const failed = summaries.filter((summary) => Array.isArray(summary.failures) && summary.failures.length > 0);
13697
- return {
13698
- type: check.type,
13699
- label: checkLabel(check),
13700
- status: failed.length ? "failed" : "passed",
13701
- evidence: {
13702
- url,
13703
- method,
13704
- allowed_statuses: httpStatusAllowedStatuses(check) || ["2xx", "3xx"],
13705
- require_nonzero_bytes: check.require_nonzero_bytes === true,
13706
- min_bytes: check.min_bytes ?? null,
13707
- allowed_content_types: check.allowed_content_types ?? null,
13708
- body_contains: check.body_contains ?? [],
13709
- body_not_contains: check.body_not_contains ?? [],
13710
- body_not_patterns: check.body_not_patterns ?? [],
13711
- body_json_assertions: toJsonValue(check.body_json_assertions ?? []),
13712
- viewports: summaries.map((summary) => toJsonValue(summary)),
13713
- failures: failed.flatMap((summary) => Array.isArray(summary.failures) ? summary.failures.map((failure) => toJsonValue({ viewport: stringValue6(summary.viewport) ?? null, failure })) : [])
13714
- },
13715
- message: failed.length ? `HTTP status failed in ${failed.length} viewport(s).` : void 0
13716
- };
13717
- }
13718
- if (check.type === "link_status" || check.type === "artifact_link_status") {
13719
- const selector = linkStatusSelector(check);
13720
- const summaries = viewports.map((viewport) => summarizeLinkStatusEvidence(viewport, check));
13721
- const failed = summaries.filter((summary) => (numberValue4(summary.failed_count) ?? 0) > 0);
13722
- return {
13723
- type: check.type,
13724
- label: checkLabel(check),
13725
- status: failed.length ? "failed" : "passed",
13726
- evidence: {
13727
- selector,
13728
- expected_count: check.expected_count ?? null,
13729
- min_count: check.min_count ?? null,
13730
- allowed_statuses: linkStatusAllowedStatuses(check) || ["2xx", "3xx"],
13731
- require_nonzero_bytes: check.require_nonzero_bytes === true,
13732
- min_bytes: check.min_bytes ?? null,
13733
- allowed_content_types: check.allowed_content_types ?? null,
13734
- viewports: summaries.map((summary) => toJsonValue(summary)),
13735
- failures: failed.flatMap((summary) => Array.isArray(summary.failures) ? summary.failures.map((failure) => toJsonValue({ viewport: stringValue6(summary.viewport) ?? null, failure })) : [])
13736
- },
13737
- message: failed.length ? `Link status failed in ${failed.length} viewport(s).` : void 0
13738
- };
13739
- }
13740
- if (check.type === "route_inventory") {
13741
- const inventories = viewports.map((viewport) => ({ viewport: viewport.name, inventory: viewport.route_inventory })).filter((item) => isRecord2(item.inventory));
13742
- if (!inventories.length) {
13743
- return {
13744
- type: check.type,
13745
- label: checkLabel(check),
13746
- status: "failed",
13747
- evidence: {
13748
- expected_count: check.expected_routes?.length || 0,
13749
- expected_routes: routeInventoryExpectedRouteSummaries(void 0, check.expected_routes)
13750
- },
13751
- message: "No route inventory evidence was captured."
13752
- };
13753
- }
13754
- const viewportSummaries = inventories.map((item) => summarizeRouteInventory(item.viewport, item.inventory));
13755
- const failures = inventories.flatMap((item) => Array.isArray(item.inventory?.failures) ? item.inventory.failures.map((failure) => toJsonValue({ viewport: item.viewport, failure })) : []);
13756
- const first = inventories[0]?.inventory;
13757
- const directRoutes = Array.isArray(first?.direct_routes) ? first.direct_routes : [];
13758
- const clickthroughs = Array.isArray(first?.clickthroughs) ? first.clickthroughs : [];
13759
- const sourceLinkCount = numberValue4(first?.source_link_count) ?? numberValue4(first?.home_game_link_count) ?? null;
13760
- const sourceUniqueLinkCount = numberValue4(first?.source_unique_link_count) ?? numberValue4(first?.home_unique_game_link_count) ?? null;
13761
- const sourceCandidateCount = numberValue4(first?.source_candidate_count);
13762
- const sourceCandidateUniqueLinkCount = numberValue4(first?.source_candidate_unique_link_count);
13763
- const sourceLinkScope = stringValue6(first?.source_link_scope);
13764
- const duplicateSourceLinks = Array.isArray(first?.duplicate_source_link_paths) ? first.duplicate_source_link_paths.map((path5) => String(path5)) : [];
13765
- const duplicateSourceLinkCount = numberValue4(first?.duplicate_source_link_count) ?? (sourceLinkCount !== null && sourceUniqueLinkCount !== null ? Math.max(0, sourceLinkCount - sourceUniqueLinkCount) : null);
13766
- const expectedRoutes = routeInventoryExpectedRouteSummaries(first?.expected_routes, check.expected_routes);
13767
- return {
13768
- type: check.type,
13769
- label: checkLabel(check),
13770
- status: failures.length ? "failed" : "passed",
13771
- evidence: {
13772
- expected_count: check.expected_routes?.length || 0,
13773
- expected_routes: expectedRoutes,
13774
- source_link_scope: sourceLinkScope ?? null,
13775
- source_candidate_count: sourceCandidateCount ?? sourceLinkCount,
13776
- source_candidate_unique_link_count: sourceCandidateUniqueLinkCount ?? sourceUniqueLinkCount,
13777
- source_link_count: sourceLinkCount,
13778
- source_unique_link_count: sourceUniqueLinkCount,
13779
- duplicate_source_link_count: duplicateSourceLinkCount,
13780
- duplicate_source_links: duplicateSourceLinks,
13781
- duplicates_allowed: check.require_unique_routes === false,
13782
- homepage_link_count: numberValue4(first?.home_game_link_count) ?? sourceLinkCount,
13783
- homepage_unique_link_count: numberValue4(first?.home_unique_game_link_count) ?? sourceUniqueLinkCount,
13784
- direct_route_count: directRoutes.length,
13785
- clickthrough_count: clickthroughs.length,
13786
- viewport_count: inventories.length,
13787
- viewports: viewportSummaries.map((summary) => toJsonValue(summary)),
13788
- failures
13789
- },
13790
- message: failures.length ? `Route inventory failed with ${failures.length} issue(s).` : void 0
13791
- };
13792
- }
13793
- if (check.type === "no_horizontal_overflow" || check.type === "no_mobile_horizontal_overflow") {
13794
- const maxOverflow = check.max_overflow_px ?? 4;
13795
- const applicable = check.type === "no_mobile_horizontal_overflow" ? viewports.filter((viewport) => viewport.width <= 820) : viewports;
13796
- if (!applicable.length) {
13797
- const mobileOnly = check.type === "no_mobile_horizontal_overflow";
13798
- return {
13799
- type: check.type,
13800
- label: checkLabel(check),
13801
- status: mobileOnly ? "skipped" : "failed",
13802
- evidence: { max_overflow_px: maxOverflow, viewports: [] },
13803
- message: mobileOnly ? "No mobile viewport evidence was captured; mobile overflow check skipped." : "No applicable viewport evidence was captured for overflow check."
13804
- };
13805
- }
13806
- const failed = applicable.filter((viewport) => horizontalBoundsOverflowPx2(viewport) > maxOverflow);
13807
- return {
13808
- type: check.type,
13809
- label: checkLabel(check),
13810
- status: failed.length ? "failed" : "passed",
13811
- evidence: {
13812
- max_overflow_px: maxOverflow,
13813
- overflow_px: applicable.map((viewport) => viewport.overflow_px ?? null),
13814
- bounds_overflow_px: applicable.map((viewport) => horizontalBoundsOverflowPx2(viewport)),
13815
- overflow_offender_counts: applicable.map((viewport) => boundsOffendersForEvidence2(viewport).length),
13816
- viewports: applicable.map((viewport) => viewport.name)
13817
- },
13818
- message: failed.length ? `Horizontal bounds overflow exceeded ${maxOverflow}px in ${failed.length} viewport(s).` : void 0
13819
- };
13820
- }
13821
- if (check.type === "no_fatal_console_errors") {
13822
- const fatalConsoleEvents = (evidence.console?.events || []).filter((event) => event.type === "error" || event.type === "assert");
13823
- const explicitlyAllowedConsoleEvents = fatalConsoleEvents.filter((event) => matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns));
13824
- const expectedNetworkMockConsoleEvents = fatalConsoleEvents.filter((event) => !matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns) && isExpectedFailedNetworkMockConsoleEvent(event, evidence));
13825
- const allowedConsoleEvents = fatalConsoleEvents.filter((event) => matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns) || isExpectedFailedNetworkMockConsoleEvent(event, evidence));
13826
- const unallowedConsoleEvents = fatalConsoleEvents.filter((event) => !matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns) && !isExpectedFailedNetworkMockConsoleEvent(event, evidence));
13827
- const pageErrors = evidence.page_errors || [];
13828
- const allowedPageErrors = pageErrors.filter((error) => matchesAllowedMessage(error, check.allowed_page_error_texts, check.allowed_page_error_patterns));
13829
- const unallowedPageErrors = pageErrors.filter((error) => !matchesAllowedMessage(error, check.allowed_page_error_texts, check.allowed_page_error_patterns));
13830
- const fatalCount = unallowedConsoleEvents.length + unallowedPageErrors.length;
13831
- return {
13832
- type: check.type,
13833
- label: checkLabel(check),
13834
- status: fatalCount ? "failed" : "passed",
13835
- evidence: {
13836
- console_fatal_count: unallowedConsoleEvents.length,
13837
- page_error_count: unallowedPageErrors.length,
13838
- total_console_fatal_count: fatalConsoleEvents.length,
13839
- total_page_error_count: pageErrors.length,
13840
- allowed_console_fatal_count: allowedConsoleEvents.length,
13841
- explicitly_allowed_console_fatal_count: explicitlyAllowedConsoleEvents.length,
13842
- allowed_expected_network_mock_console_count: expectedNetworkMockConsoleEvents.length,
13843
- allowed_expected_network_mock_console_events: expectedNetworkMockConsoleEvents.slice(0, 5).map((event) => expectedFailedNetworkMockConsoleEventSummary(event, evidence)),
13844
- allowed_page_error_count: allowedPageErrors.length,
13845
- allowed_console_texts: check.allowed_console_texts || [],
13846
- allowed_console_patterns: check.allowed_console_patterns || [],
13847
- allowed_page_error_texts: check.allowed_page_error_texts || [],
13848
- allowed_page_error_patterns: check.allowed_page_error_patterns || []
13849
- },
13850
- message: fatalCount ? `${fatalCount} fatal browser error(s) were captured.` : void 0
13851
- };
13852
- }
13853
- if (check.type === "no_console_warnings") {
13854
- const warningConsoleEvents = (evidence.console?.events || []).filter((event) => event.type === "warning" || event.type === "warn");
13855
- const allowedConsoleEvents = warningConsoleEvents.filter((event) => matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns));
13856
- const unallowedConsoleEvents = warningConsoleEvents.filter((event) => !matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns));
13857
- return {
13858
- type: check.type,
13859
- label: checkLabel(check),
13860
- status: unallowedConsoleEvents.length ? "failed" : "passed",
13861
- evidence: {
13862
- console_warning_count: unallowedConsoleEvents.length,
13863
- total_console_warning_count: warningConsoleEvents.length,
13864
- allowed_console_warning_count: allowedConsoleEvents.length,
13865
- allowed_console_texts: check.allowed_console_texts || [],
13866
- allowed_console_patterns: check.allowed_console_patterns || [],
13867
- unallowed_console_warning_samples: unallowedConsoleEvents.slice(0, 5).map((event) => allowedMessageSample(event)),
13868
- allowed_console_warning_samples: allowedConsoleEvents.slice(0, 5).map((event) => allowedMessageSample(event))
13869
- },
13870
- message: unallowedConsoleEvents.length ? `${unallowedConsoleEvents.length} console warning(s) were captured.` : void 0
13871
- };
13872
- }
13873
- return {
13874
- type: check.type,
13875
- label: checkLabel(check),
13876
- status: "needs_human_review",
13877
- evidence: {},
13878
- message: "Unsupported check type."
13879
- };
13880
- }
13881
- function assessSetupActionsFromEvidence(profile, evidence) {
13882
- if (!profile.target.setup_actions?.length) return void 0;
13883
- const actionCount = profile.target.setup_actions.length;
13884
- const failed = [];
13885
- const viewports = evidence.viewports || [];
13886
- const expectedActionCountByViewport = /* @__PURE__ */ new Map();
13887
- for (const viewport of viewports) {
13888
- const expectedActionCount = setupActionsForViewport(profile.target.setup_actions, viewport.name).length;
13889
- expectedActionCountByViewport.set(viewport.name, expectedActionCount);
13890
- const results = viewport.setup_action_results || [];
13891
- for (const result of results) {
13892
- if (result.ok === false && result.optional !== true) {
13893
- failed.push({
13894
- viewport: viewport.name,
13895
- action: result.action ?? result.type ?? null,
13896
- selector: result.selector ?? null,
13897
- frame_selector: result.frame_selector ?? null,
13898
- frame_index: result.frame_index ?? null,
13899
- reason: result.reason ?? result.error ?? null
13900
- });
13901
- }
13902
- }
13903
- if (results.length < expectedActionCount && results.every((result) => result.ok !== false || result.optional === true)) {
13904
- failed.push({
13905
- viewport: viewport.name,
13906
- action: "setup_actions",
13907
- selector: null,
13908
- reason: `missing setup action results: ${results.length}/${expectedActionCount}`
13909
- });
13910
- }
13911
- }
13912
- return {
13913
- type: "setup_actions_succeeded",
13914
- label: "setup actions succeeded",
13915
- status: failed.length ? "failed" : "passed",
13916
- evidence: {
13917
- action_count: actionCount,
13918
- viewports: viewports.map((viewport) => ({
13919
- name: viewport.name,
13920
- expected_action_count: expectedActionCountByViewport.get(viewport.name) ?? actionCount,
13921
- ok: (viewport.setup_action_results || []).length >= (expectedActionCountByViewport.get(viewport.name) ?? actionCount) && (viewport.setup_action_results || []).every((result) => result.ok !== false || result.optional === true),
13922
- result_count: (viewport.setup_action_results || []).length
13923
- })),
13924
- setup_summary: profileSetupSummary(viewports, actionCount, expectedActionCountByViewport, profile.target.screenshot_full_page),
13925
- failed
13926
- },
13927
- message: failed.length ? `Setup actions failed in ${failed.length} viewport action(s).` : void 0
13928
- };
13929
- }
13930
- function assessNetworkMocksFromEvidence(profile, evidence) {
13931
- const mocks = profile.target.network_mocks || [];
13932
- if (!mocks.length) return void 0;
13933
- const events = evidence.network_mocks || [];
13934
- const failed = [];
13935
- const requiredMocks = mocks.filter((mock) => mock.required !== false);
13936
- const hitCountForMock = (mock) => events.filter((event) => event.label === mock.label && event.ok !== false).length;
13937
- for (const mock of requiredMocks) {
13938
- const hits = hitCountForMock(mock);
13939
- const requiredHitCount = requiredNetworkMockHitCount(mock);
13940
- if (hits < requiredHitCount) {
13941
- failed.push({
13942
- label: mock.label,
13943
- url: mock.url,
13944
- method: mock.method || null,
13945
- reason: hits < 1 ? "required_mock_not_hit" : "required_mock_hit_count_not_met",
13946
- required_hit_count: requiredHitCount,
13947
- hit_count: hits
13948
- });
13949
- }
13950
- }
13951
- for (const mock of mocks) {
13952
- if (mock.max_hit_count === void 0) continue;
13953
- const hits = hitCountForMock(mock);
13954
- if (hits > mock.max_hit_count) {
13955
- failed.push({
13956
- label: mock.label,
13957
- url: mock.url,
13958
- method: mock.method || null,
13959
- reason: mock.max_hit_count === 0 ? "forbidden_mock_hit" : "mock_hit_count_exceeded",
13960
- max_hit_count: mock.max_hit_count,
13961
- hit_count: hits
13962
- });
13963
- }
13964
- }
13965
- for (const event of events) {
13966
- if (event.ok === false) {
13967
- failed.push({
13968
- label: event.label ?? null,
13969
- url: event.url ?? null,
13970
- method: event.method ?? null,
13971
- reason: event.reason ?? event.error ?? "mock_failed"
13972
- });
13973
- }
13974
- if (event.request_body_matches === false) {
13975
- failed.push({
13976
- label: event.label ?? null,
13977
- response_label: event.response_label ?? null,
13978
- hit_index: event.hit_index ?? null,
13979
- response_index: event.response_index ?? null,
13980
- url: event.url ?? null,
13981
- method: event.method ?? null,
13982
- reason: "request_body_mismatch",
13983
- request_body_failures: event.request_body_failures ?? [],
13984
- request_body_length: event.request_body_length ?? null,
13985
- request_body_sample: event.request_body_sample ?? null
13986
- });
13987
- }
10576
+ function httpStatusBodyJsonAssertionFailures(result, check) {
10577
+ const expected = check.body_json_assertions?.filter((assertion) => assertion.path) ?? [];
10578
+ if (!expected.length) return [];
10579
+ if (!Array.isArray(result.body_json_assertions)) {
10580
+ return expected.map((assertion) => ({
10581
+ label: assertion.label || assertion.path,
10582
+ path: assertion.path,
10583
+ ok: false,
10584
+ exists: false,
10585
+ observed_type: "missing",
10586
+ errors: ["body_json_assertions evidence missing"]
10587
+ }));
13988
10588
  }
13989
- return {
13990
- type: "network_mocks_succeeded",
13991
- label: "network mocks succeeded",
13992
- status: failed.length ? "failed" : "passed",
13993
- evidence: {
13994
- mock_count: mocks.length,
13995
- required_count: requiredMocks.length,
13996
- hit_count: events.filter((event) => event.ok !== false).length,
13997
- hits_by_label: Object.fromEntries(mocks.map((mock) => [
13998
- mock.label,
13999
- hitCountForMock(mock)
14000
- ])),
14001
- required_hits_by_label: Object.fromEntries(requiredMocks.map((mock) => [
14002
- mock.label,
14003
- requiredNetworkMockHitCount(mock)
14004
- ])),
14005
- max_hits_by_label: Object.fromEntries(mocks.filter((mock) => mock.max_hit_count !== void 0).map((mock) => [mock.label, mock.max_hit_count ?? null])),
14006
- response_hits_by_label: networkMockResponseHitsByLabel(events),
14007
- failed
14008
- },
14009
- message: failed.length ? `Network mocks failed or hit-count contracts failed for ${failed.length} mock(s).` : void 0
14010
- };
10589
+ return result.body_json_assertions.filter((assertion) => isRecord2(assertion) && assertion.ok !== true).map((assertion) => ({
10590
+ label: stringValue6(assertion.label) || stringValue6(assertion.path) || "json assertion",
10591
+ path: stringValue6(assertion.path) || "",
10592
+ ok: false,
10593
+ exists: assertion.exists === true,
10594
+ observed: hasOwn(assertion, "observed") ? toJsonValue(assertion.observed) : void 0,
10595
+ observed_sample: hasOwn(assertion, "observed_sample") ? toJsonValue(assertion.observed_sample) : void 0,
10596
+ observed_length: numberValue4(assertion.observed_length),
10597
+ observed_key_count: numberValue4(assertion.observed_key_count),
10598
+ observed_omitted_count: numberValue4(assertion.observed_omitted_count),
10599
+ observed_type: stringValue6(assertion.observed_type) || "missing",
10600
+ expected_exists: booleanValue2(assertion.expected_exists),
10601
+ equals: hasOwn(assertion, "equals") ? toJsonValue(assertion.equals) : void 0,
10602
+ not_equals: hasOwn(assertion, "not_equals") ? toJsonValue(assertion.not_equals) : void 0,
10603
+ contains: hasOwn(assertion, "contains") ? toJsonValue(assertion.contains) : void 0,
10604
+ type: stringValue6(assertion.type),
10605
+ errors: Array.isArray(assertion.errors) ? assertion.errors.map(String) : void 0
10606
+ }));
14011
10607
  }
14012
- function networkMockResponseHitsByLabel(events) {
14013
- const responseHits = {};
14014
- for (const event of events) {
14015
- if (!event || event.ok === false) continue;
14016
- const label = typeof event.label === "string" ? event.label : "";
14017
- const responseLabel2 = typeof event.response_label === "string" ? event.response_label : "";
14018
- const hasSequenceResponse = typeof event.response_index === "number" || event.sequence_cycle === true || Boolean(responseLabel2 && responseLabel2 !== label);
14019
- if (!label || !responseLabel2 || !hasSequenceResponse) continue;
14020
- responseHits[label] || (responseHits[label] = {});
14021
- responseHits[label][responseLabel2] = (responseHits[label][responseLabel2] || 0) + 1;
10608
+ function linkStatusResultOk(result, check) {
10609
+ const status = numberValue4(result.status);
10610
+ if (!httpStatusIsAllowed(status, check)) return false;
10611
+ if (stringValue6(result.error)) return false;
10612
+ if (result.ok === false) return false;
10613
+ if (!linkStatusContentTypeOk(result, check)) return false;
10614
+ if (check.require_nonzero_bytes) {
10615
+ const observedBytes = linkStatusObservedBytes(result);
10616
+ if (observedBytes === void 0 || observedBytes <= 0) return false;
10617
+ }
10618
+ if (check.min_bytes !== void 0) {
10619
+ const observedBytes = linkStatusObservedBytes(result);
10620
+ if (observedBytes === void 0 || observedBytes < check.min_bytes) return false;
14022
10621
  }
14023
- return responseHits;
10622
+ if (httpStatusBodyContainsFailures(result, check).length) return false;
10623
+ if (httpStatusBodyNotContainsFailures(result, check).length) return false;
10624
+ if (httpStatusBodyNotPatternFailures(result, check).length) return false;
10625
+ if (httpStatusBodyJsonAssertionFailures(result, check).length) return false;
10626
+ return true;
14024
10627
  }
14025
- function requiredNetworkMockHitCount(mock) {
14026
- if (mock.required === false) return 0;
14027
- if (mock.required_hit_count !== void 0) return mock.required_hit_count;
14028
- if (Array.isArray(mock.responses) && mock.responses.length) return mock.responses.length;
14029
- return 1;
10628
+ function responseHeader(response, name) {
10629
+ const getter = response.headers?.get;
10630
+ if (typeof getter !== "function") return null;
10631
+ return getter.call(response.headers, name);
14030
10632
  }
14031
- function profileStatusFromEvidence(profile, evidence, checks) {
14032
- if (!evidence) return "proof_insufficient";
14033
- const viewports = evidence.viewports || [];
14034
- const expectedViewportCount = profile.target.viewports?.length || 0;
14035
- if (!viewports.length || !checks.length) return "proof_insufficient";
14036
- if (viewports.some((viewport) => viewport.navigation_error)) return "environment_blocked";
14037
- if (expectedViewportCount && viewports.length < expectedViewportCount) return "proof_insufficient";
14038
- if (checks.some((check) => check.status === "proof_insufficient")) return "proof_insufficient";
14039
- if (checks.some((check) => check.status === "needs_human_review")) return "needs_human_review";
14040
- if (checks.some((check) => check.status === "failed")) return "product_regression";
14041
- return "passed";
10633
+ function responseContentLength(response) {
10634
+ const value = responseHeader(response, "content-length");
10635
+ return value && /^\d+$/.test(value) ? Number(value) : null;
14042
10636
  }
14043
- var RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS = [
14044
- "screenshot",
14045
- "console",
14046
- "dom_summary",
14047
- "proof_json"
14048
- ];
14049
- function preflightRiddleProofProfileRunnerArtifacts(profile, runner) {
14050
- const requested = uniqueNonEmptyStrings(profile.artifacts || []);
14051
- if (runner !== "riddle") {
10637
+ async function responseBodyText(response) {
10638
+ if (typeof response.arrayBuffer === "function") {
10639
+ const buffer = await response.arrayBuffer();
14052
10640
  return {
14053
- ok: true,
14054
- runner,
14055
- requested,
14056
- local_only: [],
14057
- hosted_artifacts: [...RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS]
10641
+ text: new TextDecoder().decode(buffer),
10642
+ bytes: buffer.byteLength
14058
10643
  };
14059
10644
  }
14060
- const localOnly = requested.filter(profileArtifactIsHostedLocalOnly);
14061
- const subject = localOnly.join(", ");
14062
- const message = localOnly.length ? `${subject} ${localOnly.length === 1 ? "is" : "are"} local-runner output; hosted runs produce proof_json, console, dom_summary, and screenshots. Remove ${localOnly.length === 1 ? "it" : "them"} from profile.artifacts for --runner riddle.` : void 0;
14063
- return {
14064
- ok: localOnly.length === 0,
14065
- runner,
14066
- requested,
14067
- local_only: localOnly,
14068
- hosted_artifacts: [...RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS],
14069
- message
14070
- };
14071
- }
14072
- function assessRiddleProofProfileArtifactCompleteness(profile, result, artifacts) {
14073
- const required = profileRequiredArtifactKeys(profile, result);
14074
- const missing = required.filter((key) => !profileArtifactKeyPresent(key, artifacts));
14075
- return {
14076
- ok: missing.length === 0,
14077
- required,
14078
- observed: artifacts.map((artifact) => profileArtifactObservedLabel(artifact)).filter(Boolean),
14079
- missing
14080
- };
14081
- }
14082
- function applyRiddleProofProfileArtifactCompleteness(profile, result, artifacts) {
14083
- if (artifacts === void 0) return result;
14084
- const completeness = assessRiddleProofProfileArtifactCompleteness(profile, result, artifacts);
14085
- if (result.status !== "passed" || completeness.ok) {
10645
+ if (typeof response.text === "function") {
10646
+ const text = await response.text();
14086
10647
  return {
14087
- ...result,
14088
- artifacts: {
14089
- ...result.artifacts,
14090
- riddle_artifacts: artifacts
14091
- }
10648
+ text,
10649
+ bytes: new TextEncoder().encode(text).byteLength
14092
10650
  };
14093
10651
  }
14094
- const missing = completeness.missing.join(", ");
14095
- const message = `Missing required profile artifact(s): ${missing}`;
14096
- const warnings = [...result.warnings || [], message];
14097
- return {
14098
- ...result,
14099
- status: "proof_insufficient",
14100
- artifacts: {
14101
- ...result.artifacts,
14102
- riddle_artifacts: artifacts
14103
- },
14104
- summary: `${profile.name} did not produce required profile artifact(s): ${missing}.`,
14105
- warnings,
14106
- error: message
14107
- };
10652
+ return { text: "", bytes: null };
14108
10653
  }
14109
- function profileRequiredArtifactKeys(profile, result) {
14110
- const keys = [];
14111
- for (const artifact of profile.artifacts || []) {
14112
- const role = normalizeProfileArtifactRole(artifact);
14113
- if (!role) continue;
14114
- if (role === "screenshot") {
14115
- const screenshots = result.artifacts.screenshots || [];
14116
- if (screenshots.length) {
14117
- keys.push(...screenshots.map((label) => `screenshot:${label}`));
14118
- } else {
14119
- keys.push("screenshot");
14120
- }
14121
- continue;
10654
+ function httpStatusRequestBody(check) {
10655
+ const headers = isRecord2(check.headers) ? Object.fromEntries(Object.entries(check.headers).map(([key, value]) => [key, String(value)]).filter(([key]) => key.trim())) : {};
10656
+ if (check.body_json !== void 0) {
10657
+ if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
10658
+ headers["content-type"] = "application/json";
14122
10659
  }
14123
- keys.push(role);
10660
+ return { headers, body: JSON.stringify(check.body_json) };
14124
10661
  }
14125
- return uniqueNonEmptyStrings(keys);
14126
- }
14127
- function normalizeProfileArtifactRole(input) {
14128
- const normalized = input.trim().toLowerCase().replace(/[\s-]+/g, "_");
14129
- if (!normalized) return "";
14130
- if (normalized === "screenshots") return "screenshot";
14131
- if (normalized === "console" || normalized === "console_json" || normalized === "console.json") return "console.json";
14132
- if (normalized === "dom_summary" || normalized === "dom_summary_json" || normalized === "dom-summary.json") return "dom-summary.json";
14133
- if (normalized === "proof" || normalized === "proof_json" || normalized === "proof.json") return "proof.json";
14134
- return normalizeRiddleProfileArtifactName(input.trim()).toLowerCase();
14135
- }
14136
- function profileArtifactIsHostedLocalOnly(input) {
14137
- const raw = input.trim().toLowerCase();
14138
- const normalized = raw.replace(/[\s-]+/g, "_");
14139
- const role = normalizeProfileArtifactRole(input);
14140
- return [
14141
- raw,
14142
- normalized,
14143
- role
14144
- ].some((value) => value === "artifact_manifest" || value === "artifact_manifest.json" || value === "artifact-manifest" || value === "artifact-manifest.json");
14145
- }
14146
- function profileArtifactKeyPresent(key, artifacts) {
14147
- if (key.startsWith("screenshot:")) {
14148
- const label = key.slice("screenshot:".length);
14149
- return artifacts.some((artifact) => profileArtifactRefIsScreenshot(artifact) && profileArtifactRefText(artifact).includes(label.toLowerCase()));
14150
- }
14151
- if (key === "screenshot") {
14152
- return artifacts.some((artifact) => profileArtifactRefIsScreenshot(artifact));
14153
- }
14154
- return artifacts.some((artifact) => {
14155
- const name = normalizeRiddleProfileArtifactName(artifact.name || artifactNameFromPath(artifact.url || artifact.path) || "").toLowerCase();
14156
- return name === key || profileArtifactRefText(artifact).includes(key);
14157
- });
14158
- }
14159
- function profileArtifactRefIsScreenshot(artifact) {
14160
- const kind = (artifact.kind || "").toLowerCase();
14161
- const contentType = (artifact.content_type || "").toLowerCase();
14162
- const text = profileArtifactRefText(artifact);
14163
- return kind === "screenshot" || contentType.startsWith("image/") || /\.(png|jpe?g|webp)(?:$|[?#])/i.test(text) || /\.(png|jpe?g|webp)$/i.test(text);
10662
+ if (typeof check.body === "string") {
10663
+ return { headers, body: check.body };
10664
+ }
10665
+ return { headers };
14164
10666
  }
14165
- function profileArtifactRefText(artifact) {
14166
- return [
14167
- artifact.name,
14168
- artifact.url,
14169
- artifact.path,
14170
- artifact.kind,
14171
- artifact.content_type
14172
- ].filter(Boolean).join(" ").toLowerCase();
14173
- }
14174
- function profileArtifactObservedLabel(artifact) {
14175
- return artifact.name || artifact.url || artifact.path || artifact.kind || "";
14176
- }
14177
- function assessRiddleProofProfileEvidence(profile, evidence, options = {}) {
14178
- const capturedAt = evidence?.captured_at || (/* @__PURE__ */ new Date()).toISOString();
14179
- const warnings = collectRiddleProofProfileWarnings(profile);
14180
- const checks = evidence ? [
14181
- assessNetworkMocksFromEvidence(profile, evidence),
14182
- assessSetupActionsFromEvidence(profile, evidence),
14183
- ...profile.checks.map((check) => assessCheckFromEvidence(check, evidence))
14184
- ].filter((check) => Boolean(check)) : [];
14185
- const status = profileStatusFromEvidence(profile, evidence, checks);
14186
- const firstViewport = evidence?.viewports?.[0];
14187
- const screenshots = profileScreenshotLabels(evidence?.viewports);
14188
- const canonicalScreenshots = profileFinalScreenshotLabels(evidence?.viewports);
14189
- const setupScreenshots = profileAllSetupScreenshotLabels(evidence?.viewports);
14190
- const result = {
14191
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
14192
- profile_name: profile.name,
14193
- runner: options.runner || "riddle",
14194
- status,
14195
- baseline_policy: profile.baseline_policy,
14196
- route: routeForViewport(firstViewport, evidence?.target_url),
14197
- artifacts: {
14198
- screenshots,
14199
- canonical_screenshots: canonicalScreenshots,
14200
- setup_screenshots: setupScreenshots,
14201
- console: "console.json",
14202
- proof_json: "proof.json",
14203
- dom_summary: "dom-summary.json",
14204
- riddle_artifacts: options.artifacts
14205
- },
14206
- checks,
14207
- summary: summarizeRiddleProofProfileResult({ profile_name: profile.name, status, checks, viewports: evidence?.viewports || [] }),
14208
- captured_at: capturedAt,
14209
- metadata: profile.metadata,
14210
- warnings: warnings.length ? warnings : void 0,
14211
- evidence,
14212
- riddle: options.riddle
10667
+ async function preflightHttpStatusCheck(check, index, targetUrl, fetchImpl) {
10668
+ const url = httpStatusRequestUrl(check, targetUrl);
10669
+ const method = httpStatusMethod(check);
10670
+ const request = httpStatusRequestBody(check);
10671
+ const init = {
10672
+ method,
10673
+ redirect: "follow",
10674
+ cache: "no-store",
10675
+ headers: request.headers
14213
10676
  };
14214
- return applyRiddleProofProfileArtifactCompleteness(profile, result, options.artifacts);
14215
- }
14216
- function summarizeRiddleProofProfileResult(input) {
14217
- const passedChecks = input.checks.filter((check) => check.status === "passed").length;
14218
- const failedChecks = input.checks.filter((check) => check.status === "failed").length;
14219
- const viewportNames = input.viewports.map((viewport) => viewport.name).join(", ");
14220
- if (input.status === "passed") {
14221
- return `${input.profile_name} passed ${passedChecks} check(s) across ${input.viewports.length} viewport(s)${viewportNames ? ` (${viewportNames})` : ""}.`;
14222
- }
14223
- if (input.status === "product_regression") {
14224
- return `${input.profile_name} failed ${failedChecks} product invariant(s) across ${input.viewports.length} viewport(s).`;
14225
- }
14226
- if (input.status === "environment_blocked") {
14227
- return `${input.profile_name} could not collect reliable evidence because navigation or the browser environment was blocked.`;
14228
- }
14229
- if (input.status === "proof_insufficient") {
14230
- return `${input.profile_name} did not produce enough evidence for a profile judgment.`;
14231
- }
14232
- if (input.status === "configuration_error") {
14233
- return `${input.profile_name} has a profile configuration error.`;
10677
+ if (request.body !== void 0 && method !== "GET" && method !== "HEAD") {
10678
+ init.body = request.body;
14234
10679
  }
14235
- return `${input.profile_name} collected artifacts but needs human review.`;
14236
- }
14237
- function profileStatusExitCode(profile, status) {
14238
- if (status === "passed") return 0;
14239
- return profile.failure_policy[status] === "neutral" ? 0 : 1;
14240
- }
14241
- function createRiddleProofProfileConfigurationError(profileOrName, error, runner = "riddle", options = {}) {
14242
- const profile = typeof profileOrName === "string" ? void 0 : profileOrName;
14243
- const name = profile ? profile.name : String(profileOrName);
14244
- const message = error instanceof Error ? error.message : String(error);
14245
- let requested = "";
14246
- if (profile) {
14247
- try {
14248
- requested = resolveRiddleProofProfileTargetUrl(profile);
14249
- } catch {
14250
- requested = "";
10680
+ const result = {
10681
+ status: null,
10682
+ content_type: null,
10683
+ content_length: null,
10684
+ bytes: null
10685
+ };
10686
+ let error = null;
10687
+ let statusText = "";
10688
+ try {
10689
+ const response = await fetchImpl(url, init);
10690
+ result.status = typeof response.status === "number" && Number.isFinite(response.status) ? response.status : null;
10691
+ statusText = typeof response.statusText === "string" ? response.statusText : "";
10692
+ result.content_type = responseHeader(response, "content-type");
10693
+ result.content_length = responseContentLength(response);
10694
+ const shouldReadBody = check.require_nonzero_bytes === true || typeof check.min_bytes === "number" || Boolean(check.body_contains?.length) || Boolean(check.body_not_contains?.length) || Boolean(check.body_not_patterns?.length) || Boolean(check.body_json_assertions?.length);
10695
+ if (shouldReadBody && method !== "HEAD") {
10696
+ const body = await responseBodyText(response);
10697
+ result.bytes = body.bytes;
10698
+ if (check.body_contains?.length) {
10699
+ result.body_contains = Object.fromEntries(check.body_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
10700
+ }
10701
+ if (check.body_not_contains?.length) {
10702
+ result.body_not_contains = Object.fromEntries(check.body_not_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
10703
+ }
10704
+ if (check.body_not_patterns?.length) {
10705
+ result.body_not_patterns = Object.fromEntries(check.body_not_patterns.filter(Boolean).map((pattern) => [pattern, new RegExp(pattern).test(body.text)]));
10706
+ }
10707
+ if (check.body_json_assertions?.length) {
10708
+ result.body_json_assertions = evaluateHttpStatusBodyJsonAssertions(body.text, check.body_json_assertions);
10709
+ }
14251
10710
  }
10711
+ } catch (caught) {
10712
+ error = String(caught instanceof Error ? caught.message : caught).slice(0, 500);
10713
+ result.error = error;
14252
10714
  }
10715
+ const bodyContainsMissing = httpStatusBodyContainsFailures(result, check);
10716
+ const bodyNotContainsFound = httpStatusBodyNotContainsFailures(result, check);
10717
+ const bodyNotPatternsFound = httpStatusBodyNotPatternFailures(result, check);
10718
+ const bodyJsonAssertionsFailed = httpStatusBodyJsonAssertionFailures(result, check);
10719
+ const ok = !error && linkStatusResultOk(result, check);
14253
10720
  return {
14254
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
14255
- profile_name: name,
14256
- runner,
14257
- status: "configuration_error",
14258
- baseline_policy: profile?.baseline_policy || "invariant_only",
14259
- route: { requested, observed: "", matched: false, error: message },
14260
- artifacts: { screenshots: [], proof_json: "proof.json" },
14261
- checks: [],
14262
- summary: `${name} has a profile configuration error.`,
14263
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
14264
- metadata: profile?.metadata,
14265
- warnings: options.warnings?.length ? options.warnings : void 0,
14266
- configuration_blocker: options.configurationBlocker,
14267
- error: message
10721
+ index,
10722
+ label: checkLabel(check) || `checks[${index}]`,
10723
+ url,
10724
+ method,
10725
+ ok,
10726
+ status: numberValue4(result.status) ?? null,
10727
+ status_text: statusText,
10728
+ error,
10729
+ content_type: stringValue6(result.content_type) ?? null,
10730
+ content_length: numberValue4(result.content_length) ?? null,
10731
+ bytes: numberValue4(result.bytes) ?? null,
10732
+ body_contains: isRecord2(result.body_contains) ? Object.fromEntries(Object.entries(result.body_contains).map(([key, value]) => [key, value === true])) : null,
10733
+ body_contains_missing: bodyContainsMissing,
10734
+ body_not_contains: isRecord2(result.body_not_contains) ? Object.fromEntries(Object.entries(result.body_not_contains).map(([key, value]) => [key, value === true])) : null,
10735
+ body_not_contains_found: bodyNotContainsFound,
10736
+ body_not_patterns: isRecord2(result.body_not_patterns) ? Object.fromEntries(Object.entries(result.body_not_patterns).map(([key, value]) => [key, value === true])) : null,
10737
+ body_not_patterns_found: bodyNotPatternsFound,
10738
+ body_json_assertions: Array.isArray(result.body_json_assertions) ? result.body_json_assertions : null,
10739
+ body_json_assertions_failed: bodyJsonAssertionsFailed
14268
10740
  };
14269
10741
  }
14270
- function createRiddleProofProfileEnvironmentBlockedResult(input) {
14271
- const message = input.error instanceof Error ? input.error.message : input.error ? String(input.error) : "Riddle runner did not complete successfully.";
14272
- const environmentBlocker = input.environmentBlocker || extractRiddleRunnerBlocker(message);
14273
- const warnings = collectRiddleProofProfileEnvironmentBlockedWarnings(input.profile, environmentBlocker);
10742
+ async function preflightRiddleProofProfileHttpStatusChecks(profile, options = {}) {
10743
+ const targetUrl = options.target_url || (0, import_profile.resolveRiddleProofProfileTargetUrl)(profile);
10744
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
10745
+ if (typeof fetchImpl !== "function") {
10746
+ throw new Error("profile http_status preflight requires fetch support or options.fetchImpl.");
10747
+ }
10748
+ const httpStatusChecks = profile.checks.map((check, index) => ({ check, index })).filter((item) => item.check.type === "http_status");
10749
+ const checks = await Promise.all(httpStatusChecks.map((item) => preflightHttpStatusCheck(item.check, item.index, targetUrl, fetchImpl)));
10750
+ const failed = checks.filter((check) => !check.ok).length;
14274
10751
  return {
14275
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
14276
- profile_name: input.profile.name,
14277
- runner: input.runner || "riddle",
14278
- status: "environment_blocked",
14279
- baseline_policy: input.profile.baseline_policy,
14280
- route: { requested: resolveRiddleProofProfileTargetUrl(input.profile), observed: "", matched: false, error: message },
14281
- artifacts: { screenshots: [], proof_json: "proof.json", riddle_artifacts: input.artifacts },
14282
- checks: [],
14283
- summary: summarizeEnvironmentBlockedRunner(input.profile.name, environmentBlocker),
14284
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
14285
- metadata: input.profile.metadata,
14286
- warnings: warnings.length ? warnings : void 0,
14287
- riddle: input.riddle,
14288
- environment_blocker: environmentBlocker,
14289
- error: message
10752
+ version: "riddle-proof.profile-http-status-preflight.v1",
10753
+ ok: failed === 0,
10754
+ profile_name: profile.name,
10755
+ target_url: targetUrl,
10756
+ checked: checks.length,
10757
+ failed,
10758
+ checks,
10759
+ summary: failed === 0 ? `${profile.name} http_status preflight passed ${checks.length} check(s).` : `${profile.name} http_status preflight failed ${failed} of ${checks.length} check(s).`
14290
10760
  };
14291
10761
  }
14292
- function extractRiddleRunnerBlocker(message) {
14293
- const apiError = message.match(/^Riddle API\s+(\S+)\s+failed HTTP\s+(\d+):\s+(\{[\s\S]*\})$/);
14294
- if (!apiError) return void 0;
14295
- const details = {
14296
- source: "riddle_api",
14297
- endpoint: apiError[1],
14298
- http_status: Number(apiError[2])
14299
- };
14300
- let payload;
14301
- try {
14302
- const parsed = JSON.parse(apiError[3]);
14303
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
14304
- payload = parsed;
14305
- }
14306
- } catch {
14307
- payload = void 0;
14308
- }
14309
- const copyScalar = (key) => {
14310
- const value = payload?.[key];
14311
- if (typeof value === "string" || typeof value === "boolean") details[key] = value;
14312
- if (typeof value === "number" && Number.isFinite(value)) details[key] = value;
14313
- };
14314
- for (const key of ["error", "required_seconds", "available_seconds", "deficit_seconds", "minimum_purchase_dollars"]) {
14315
- copyScalar(key);
14316
- }
14317
- const warnings = payload?.warnings;
14318
- if (Array.isArray(warnings)) {
14319
- const warningStrings = warnings.filter((warning) => typeof warning === "string");
14320
- if (warningStrings.length) details.warnings = warningStrings;
14321
- }
14322
- const httpStatus = typeof details.http_status === "number" ? details.http_status : void 0;
14323
- const errorText = typeof details.error === "string" ? details.error.toLowerCase() : "";
14324
- if (httpStatus === 402 && errorText.includes("balance")) {
14325
- details.reason = "insufficient_balance";
14326
- }
14327
- return details;
14328
- }
14329
- function summarizeEnvironmentBlockedRunner(profileName, blocker) {
14330
- if (blocker?.reason === "insufficient_balance") {
14331
- const required = typeof blocker.required_seconds === "number" ? blocker.required_seconds : void 0;
14332
- const available = typeof blocker.available_seconds === "number" ? blocker.available_seconds : void 0;
14333
- const deficit = typeof blocker.deficit_seconds === "number" ? blocker.deficit_seconds : void 0;
14334
- const parts = [
14335
- required === void 0 ? "" : `required ${required}s`,
14336
- available === void 0 ? "" : `available ${available}s`,
14337
- deficit === void 0 ? "" : `deficit ${deficit}s`
14338
- ].filter(Boolean);
14339
- return `${profileName} could not start because Riddle balance was insufficient${parts.length ? ` (${parts.join(", ")})` : ""}.`;
14340
- }
14341
- if (blocker?.source === "riddle_api") {
14342
- const endpoint = typeof blocker.endpoint === "string" ? blocker.endpoint : "Riddle API";
14343
- const status = typeof blocker.http_status === "number" ? blocker.http_status : void 0;
14344
- return `${profileName} could not start because ${endpoint} returned${status === void 0 ? "" : ` HTTP ${status}`}.`;
14345
- }
14346
- return `${profileName} could not collect reliable evidence because the runner was blocked.`;
10762
+ function previewMountPrefix(pathname) {
10763
+ const value = pathname || "/";
10764
+ const apiPreview = value.match(/^(\/s\/[^/]+)(?:\/|$)/);
10765
+ if (apiPreview) return apiPreview[1];
10766
+ const internalPreview = value.match(/^(\/preview\/[^/]+\/[^/]+)(?:\/|$)/);
10767
+ return internalPreview ? internalPreview[1] : "";
14347
10768
  }
14348
- function createRiddleProofProfileInsufficientResult(input) {
14349
- const message = input.error instanceof Error ? input.error.message : input.error ? String(input.error) : "No proof.json profile result artifact was found.";
14350
- const warnings = collectRiddleProofProfileWarnings(input.profile);
14351
- return {
14352
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
14353
- profile_name: input.profile.name,
14354
- runner: input.runner || "riddle",
14355
- status: "proof_insufficient",
14356
- baseline_policy: input.profile.baseline_policy,
14357
- route: { requested: resolveRiddleProofProfileTargetUrl(input.profile), observed: "", matched: false, error: message },
14358
- artifacts: { screenshots: [], proof_json: "proof.json", riddle_artifacts: input.artifacts },
14359
- checks: [],
14360
- summary: `${input.profile.name} did not produce enough evidence for a profile judgment.`,
14361
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
14362
- metadata: input.profile.metadata,
14363
- warnings: warnings.length ? warnings : void 0,
14364
- riddle: input.riddle,
14365
- error: message
14366
- };
10769
+ function joinMountedRoutePath(mountPrefix, routePath) {
10770
+ const route = routePath.startsWith("/") ? routePath : `/${routePath}`;
10771
+ if (!mountPrefix) return route;
10772
+ if (route === mountPrefix || route.startsWith(`${mountPrefix}/`)) return route;
10773
+ return `${mountPrefix}${route}`;
14367
10774
  }
14368
10775
  function runtimeScriptAssessmentSource(includeOrderedTrace = false) {
14369
10776
  const orderedTraceSource = includeOrderedTrace ? String.raw`
14370
- const assessRiddleProofOrderedTrace = ${assessRiddleProofOrderedTrace.toString()};
14371
- const assessRiddleProofOrderedTraceSetupResults = ${assessRiddleProofOrderedTraceSetupResults.toString()};` : "";
10777
+ const assessRiddleProofOrderedTrace = ${import_profile.assessRiddleProofOrderedTrace.toString()};
10778
+ const assessRiddleProofOrderedTraceSetupResults = ${import_profile.assessRiddleProofOrderedTraceSetupResults.toString()};` : "";
14372
10779
  return String.raw`
14373
10780
  ${orderedTraceSource}
14374
10781
  function normalizeRoutePath(path) {
@@ -16464,9 +12871,9 @@ function assessProfile(profile, evidence) {
16464
12871
  `;
16465
12872
  }
16466
12873
  function buildRiddleProofProfileScript(profile) {
16467
- const targetUrl = resolveRiddleProofProfileTargetUrl(profile);
16468
- const slug2 = slugifyRiddleProofProfileName(profile.name);
16469
- const profileWarnings = collectRiddleProofProfileWarnings(profile);
12874
+ const targetUrl = (0, import_profile.resolveRiddleProofProfileTargetUrl)(profile);
12875
+ const slug2 = (0, import_profile.slugifyRiddleProofProfileName)(profile.name);
12876
+ const profileWarnings = (0, import_profile.collectRiddleProofProfileWarnings)(profile);
16470
12877
  const serializableProfile = JSON.stringify(profile);
16471
12878
  const serializableProfileWarnings = JSON.stringify(profileWarnings);
16472
12879
  const serializableTargetUrl = JSON.stringify(targetUrl);
@@ -20118,97 +16525,6 @@ for (const viewport of profile.target.viewports || []) {
20118
16525
  return result;
20119
16526
  `.trim();
20120
16527
  }
20121
- function collectRiddleProfileArtifactRefs(input) {
20122
- const refs = [];
20123
- const indexes = /* @__PURE__ */ new Map();
20124
- const priorities = /* @__PURE__ */ new Map();
20125
- function add(item, source) {
20126
- if (!isRecord2(item)) return;
20127
- const url = stringValue6(item.url);
20128
- const path5 = stringValue6(item.path);
20129
- const rawName = stringValue6(item.name) || stringValue6(item.filename) || artifactNameFromPath(url || path5) || "";
20130
- const name = normalizeRiddleProfileArtifactName(rawName);
20131
- if (!name && !url && !path5) return;
20132
- const key = profileArtifactDedupeKey(name, url || path5 || "");
20133
- const priority = profileArtifactPriority(rawName, name);
20134
- const ref = {
20135
- name,
20136
- url,
20137
- path: path5,
20138
- kind: stringValue6(item.kind) || stringValue6(item.type),
20139
- content_type: stringValue6(item.content_type) || stringValue6(item.contentType),
20140
- source
20141
- };
20142
- const existingIndex = indexes.get(key);
20143
- if (existingIndex !== void 0) {
20144
- if (priority > (priorities.get(key) || 0)) {
20145
- refs[existingIndex] = ref;
20146
- priorities.set(key, priority);
20147
- }
20148
- return;
20149
- }
20150
- indexes.set(key, refs.length);
20151
- priorities.set(key, priority);
20152
- refs.push(ref);
20153
- }
20154
- function visit(value, source) {
20155
- if (Array.isArray(value)) {
20156
- for (const item of value) add(item, source);
20157
- return;
20158
- }
20159
- if (!isRecord2(value)) return;
20160
- for (const key of ["artifacts", "outputs", "screenshots", "files"]) {
20161
- if (Array.isArray(value[key])) visit(value[key], key);
20162
- }
20163
- }
20164
- visit(input, "artifacts");
20165
- return refs;
20166
- }
20167
- function normalizeRiddleProfileArtifactName(name) {
20168
- return name.replace(/\.json\.json$/i, ".json");
20169
- }
20170
- function profileArtifactDedupeKey(name, location) {
20171
- if (PROFILE_SINGLETON_ARTIFACT_NAMES.has(name.toLowerCase())) return name.toLowerCase();
20172
- return `${name}:${location}`;
20173
- }
20174
- function profileArtifactPriority(rawName, normalizedName) {
20175
- const lower = normalizedName.toLowerCase();
20176
- if (!PROFILE_SINGLETON_ARTIFACT_NAMES.has(lower)) return 1;
20177
- return /\.json\.json$/i.test(rawName) ? 2 : 1;
20178
- }
20179
- function artifactNameFromPath(value) {
20180
- if (!value) return "";
20181
- try {
20182
- return new URL(value).pathname.split("/").filter(Boolean).pop() || "";
20183
- } catch {
20184
- return value.split(/[\\/]/).filter(Boolean).pop() || "";
20185
- }
20186
- }
20187
- var PROFILE_SINGLETON_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
20188
- "proof.json",
20189
- "console.json",
20190
- "dom-summary.json"
20191
- ]);
20192
- function extractRiddleProofProfileResult(input) {
20193
- if (!isRecord2(input)) return void 0;
20194
- if (input.version === RIDDLE_PROOF_PROFILE_RESULT_VERSION) return input;
20195
- const candidates = [
20196
- input.result,
20197
- input.return_value,
20198
- input.value,
20199
- input.profile_result,
20200
- isRecord2(input["proof.json"]) ? input["proof.json"] : void 0,
20201
- isRecord2(input._proof_json) ? input._proof_json : void 0
20202
- ];
20203
- for (const candidate of candidates) {
20204
- const result = extractRiddleProofProfileResult(candidate);
20205
- if (result) return result;
20206
- }
20207
- if (isRecord2(input._artifact_json)) {
20208
- return extractRiddleProofProfileResult(input._artifact_json["proof.json"]);
20209
- }
20210
- return void 0;
20211
- }
20212
16528
 
20213
16529
  // src/profile-suggestions.ts
20214
16530
  var RIDDLE_PROOF_PROFILE_SUGGESTIONS_VERSION = "riddle-proof.profile-suggestions.v1";
@@ -20351,7 +16667,7 @@ function suggestRiddleProofProfileChecks(input) {
20351
16667
  setup_actions: setupActions.length ? setupActions : void 0
20352
16668
  };
20353
16669
  const profile = {
20354
- version: RIDDLE_PROOF_PROFILE_VERSION,
16670
+ version: import_profile2.RIDDLE_PROOF_PROFILE_VERSION,
20355
16671
  name: suggestionProfileName(input, routeOrDefault, changedFiles),
20356
16672
  target,
20357
16673
  checks,
@@ -20487,6 +16803,15 @@ var import_checked_meaning = require("@riddledc/riddle-proof-core/checked-meanin
20487
16803
  // src/index.ts
20488
16804
  __reExport(index_exports, checked_meaning_exports, module.exports);
20489
16805
 
16806
+ // src/rule-trust-root.ts
16807
+ var import_rule_trust_root = require("@riddledc/riddle-proof-core/rule-trust-root");
16808
+
16809
+ // src/evidence-trust-root.ts
16810
+ var import_evidence_trust_root = require("@riddledc/riddle-proof-core/evidence-trust-root");
16811
+
16812
+ // src/packet.ts
16813
+ var import_packet = require("@riddledc/riddle-proof-core/packet");
16814
+
20490
16815
  // src/change-proof.ts
20491
16816
  var RIDDLE_PROOF_CHANGE_CONTRACT_VERSION = "riddle-proof.change-contract.v1";
20492
16817
  var RIDDLE_PROOF_CHANGE_RESULT_VERSION = "riddle-proof.change-result.v1";
@@ -21029,7 +17354,7 @@ function parseRiddleProofChangeReceipt(value) {
21029
17354
  throw new Error(`Unsupported Change receipt version ${String(value.version || "missing")}.`);
21030
17355
  }
21031
17356
  const receipt = value;
21032
- if (!RIDDLE_PROOF_PROFILE_STATUSES.includes(receipt.status)) {
17357
+ if (!import_profile2.RIDDLE_PROOF_PROFILE_STATUSES.includes(receipt.status)) {
21033
17358
  throw new Error(`Unsupported Change receipt status ${String(receipt.status || "missing")}.`);
21034
17359
  }
21035
17360
  (0, import_receipts.parseRiddleProofObservationReceipt)(receipt.before);
@@ -21915,6 +18240,18 @@ function buildRiddleProofPrCommentMarkdown(input) {
21915
18240
  RIDDLE_PROOF_CHECKED_MEANING_RULE_ENGINE,
21916
18241
  RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
21917
18242
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
18243
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_ARRAY_ITEMS,
18244
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_DEPTH,
18245
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_NODES,
18246
+ RIDDLE_PROOF_EVIDENCE_OBSERVATION_SCHEMA_MAX_PROPERTIES,
18247
+ RIDDLE_PROOF_EVIDENCE_SENSOR_TARGET_BINDING,
18248
+ RIDDLE_PROOF_EVIDENCE_TEMPLATE_PROFILE_MODE,
18249
+ RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_DIGEST_DOMAIN,
18250
+ RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_MAX_PROFILES,
18251
+ RIDDLE_PROOF_EVIDENCE_TRUST_ROOT_VERSION,
18252
+ RIDDLE_PROOF_EXECUTION_DIGEST_DOMAIN,
18253
+ RIDDLE_PROOF_EXECUTION_POLICY_DIGEST_DOMAIN,
18254
+ RIDDLE_PROOF_EXECUTION_POLICY_VERSION,
21918
18255
  RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_ARTIFACTS,
21919
18256
  RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_ARTIFACT_BYTES,
21920
18257
  RIDDLE_PROOF_GROUNDED_CAPTURE_MAX_OBSERVATION_BYTES,
@@ -21939,8 +18276,13 @@ function buildRiddleProofPrCommentMarkdown(input) {
21939
18276
  RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS,
21940
18277
  RIDDLE_PROOF_OBSERVATION_RECEIPT_VERSION,
21941
18278
  RIDDLE_PROOF_ORDERED_TRACE_OPERATORS,
18279
+ RIDDLE_PROOF_PACKET_RECEIPT_DIGEST_DOMAIN,
18280
+ RIDDLE_PROOF_PACKET_RECEIPT_VERSION,
21942
18281
  RIDDLE_PROOF_PLAYABILITY_ASSESSMENT_VERSION,
21943
18282
  RIDDLE_PROOF_PLAYABILITY_VERSION,
18283
+ RIDDLE_PROOF_PRIVATE_PACKET_DIGEST_DOMAIN,
18284
+ RIDDLE_PROOF_PRIVATE_PACKET_MEDIA_TYPE,
18285
+ RIDDLE_PROOF_PRIVATE_PACKET_VERSION,
21944
18286
  RIDDLE_PROOF_PROFILE_CHECK_TYPES,
21945
18287
  RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION,
21946
18288
  RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES,
@@ -21950,6 +18292,8 @@ function buildRiddleProofPrCommentMarkdown(input) {
21950
18292
  RIDDLE_PROOF_PROFILE_SUGGESTIONS_VERSION,
21951
18293
  RIDDLE_PROOF_PROFILE_VERSION,
21952
18294
  RIDDLE_PROOF_PR_COMMENT_MARKER,
18295
+ RIDDLE_PROOF_RULE_TRUST_ROOT_DIGEST_DOMAIN,
18296
+ RIDDLE_PROOF_RULE_TRUST_ROOT_VERSION,
21953
18297
  RIDDLE_PROOF_RUN_CARD_VERSION,
21954
18298
  RIDDLE_PROOF_RUN_STATE_VERSION,
21955
18299
  RIDDLE_PROOF_SEMANTIC_CERTIFICATE_CLOSURE_MAX_CERTIFICATES,
@@ -22016,15 +18360,18 @@ function buildRiddleProofPrCommentMarkdown(input) {
22016
18360
  createRiddleProofChangeReceipt,
22017
18361
  createRiddleProofCheckedMeaningAtomicClosure,
22018
18362
  createRiddleProofCheckedMeaningRule,
18363
+ createRiddleProofEvidenceTrustRoot,
22019
18364
  createRiddleProofGroundedDeclarativeJsonContract,
22020
18365
  createRiddleProofGroundedDeclarativeJsonVerifier,
22021
18366
  createRiddleProofGroundedSemanticAtomicCertificateClosure,
22022
18367
  createRiddleProofGroundedSemanticCertificate,
22023
18368
  createRiddleProofHandoffReceipt,
22024
18369
  createRiddleProofObservationReceipt,
18370
+ createRiddleProofPacketReceipt,
22025
18371
  createRiddleProofProfileConfigurationError,
22026
18372
  createRiddleProofProfileEnvironmentBlockedResult,
22027
18373
  createRiddleProofProfileInsufficientResult,
18374
+ createRiddleProofRuleTrustRoot,
22028
18375
  createRiddleProofRunCard,
22029
18376
  createRiddleProofSemanticAtomicCertificateClosure,
22030
18377
  createRiddleProofSemanticCertificate,
@@ -22036,6 +18383,9 @@ function buildRiddleProofPrCommentMarkdown(input) {
22036
18383
  deployRiddleStaticPreview,
22037
18384
  deriveRiddleProofArtifactBodyAssertions,
22038
18385
  detectRiddlePreviewSource,
18386
+ digestRiddleProofExecution,
18387
+ digestRiddleProofExecutionPolicy,
18388
+ digestRiddleProofPrivatePacketBytes,
22039
18389
  extractBasicGameplayEvidence,
22040
18390
  extractPlayabilityEvidence,
22041
18391
  extractRiddleProofProfileResult,
@@ -22051,6 +18401,7 @@ function buildRiddleProofPrCommentMarkdown(input) {
22051
18401
  matchRiddleProofGroundedSemanticCertificateClosure,
22052
18402
  matchRiddleProofSemanticCertificate,
22053
18403
  matchRiddleProofSemanticCertificateClosure,
18404
+ materializeRiddleProofEvidenceTrustProfile,
22054
18405
  migrateRiddleProofChangeReceipt,
22055
18406
  nonEmptyString,
22056
18407
  normalizeCheckpointResponse,
@@ -22081,9 +18432,11 @@ function buildRiddleProofPrCommentMarkdown(input) {
22081
18432
  resolveBasicGameplayProgressionCheckWithArtifactScreenshots,
22082
18433
  resolveRiddleApiKey,
22083
18434
  resolveRiddleApiKeySource,
18435
+ resolveRiddleProofEvidenceTrustRoot,
22084
18436
  resolveRiddleProofProfileRouteUrl,
22085
18437
  resolveRiddleProofProfileTargetUrl,
22086
18438
  resolveRiddleProofProfileTimeoutSec,
18439
+ resolveRiddleProofRuleTrustRoot,
22087
18440
  riddleProofChangeReceiptHtml,
22088
18441
  riddleProofChangeReceiptMarkdown,
22089
18442
  riddleProofPublicStateAllowsClaim,
@@ -22111,8 +18464,10 @@ function buildRiddleProofPrCommentMarkdown(input) {
22111
18464
  summarizeRiddleProofPublicConsumerSurface,
22112
18465
  summarizeRiddleProofPublicState,
22113
18466
  validateRiddleProofCheckedMeaningClosure,
18467
+ validateRiddleProofEvidenceObservationSchema,
22114
18468
  validateRiddleProofGroundedSemanticCertificateClosure,
22115
18469
  validateRiddleProofSemanticCertificateClosure,
18470
+ verifyRiddleProofPacketReceipt,
22116
18471
  verifyRiddleProofSignedCaptureBundle,
22117
18472
  visualSessionFingerprint,
22118
18473
  visualSessionFingerprintBasis