@unbrained/pm-cli 2026.11.2 → 2026.11.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +24 -0
- package/dist/cli/error-guidance.d.ts +23 -35
- package/dist/cli/error-guidance.js +4 -3
- package/dist/cli/expected-revisions.d.ts +55 -0
- package/dist/cli/expected-revisions.js +2 -0
- package/dist/cli/main.js +2 -2
- package/dist/cli/runtime/field-route-retry.d.ts +15 -0
- package/dist/cli/runtime/field-route-retry.js +2 -0
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-3A4NVHYS.js → chunk-2GW662DP.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-3OXQGGRD.js +115 -0
- package/dist/cli-bundle/chunks/chunk-5BVZ32G7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5S6RT5LX.js +9 -0
- package/dist/cli-bundle/chunks/chunk-5Z6LWFDL.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-RGHLQGEX.js → chunk-6T2V3UIK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JRXD7SIL.js → chunk-7PGNAHNW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7RCI7AAA.js +20 -0
- package/dist/cli-bundle/chunks/chunk-AQ5UHHQS.js +2 -0
- package/dist/cli-bundle/chunks/chunk-BK2XAQVC.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ABFFRQRO.js → chunk-BRIPGUAO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-BWAXA6S4.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-HOGKWJU5.js → chunk-CERNIZLB.js} +66 -66
- package/dist/cli-bundle/chunks/chunk-DSCFJTHB.js +122 -0
- package/dist/cli-bundle/chunks/{chunk-VEOFWE32.js → chunk-L4BKTPJ6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NGRPD3ZO.js → chunk-NPEDFOVQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J3JM36EH.js → chunk-O4ZLEN4T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-533L6D2N.js → chunk-ODMJ3HIB.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-KJLGBLR3.js → chunk-QN7VCOUU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QQHMNUZT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-D52QQ7LP.js → chunk-RSAN2YUU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-SRDO2NJU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-T56MB6SF.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TX2W6G37.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-GK2CHAT3.js → chunk-UJMQP2HP.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-IEJ2QOW3.js → indexed-receipt-blobs-I6RQGD6Y.js} +2 -2
- package/dist/cli-bundle/chunks/item-revision-UAZOBP2Q.js +2 -0
- package/dist/cli-bundle/chunks/item-transaction-N5F4LXYV.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-QZQI2NN5.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NZTK3AXA.js → register-list-query-P3NOKQUA.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-2OFAMOVH.js → register-mutation-A6I5K5N6.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-SPKB3TNM.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-ZZRHJ4IS.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-UTCEZBFT.js → settlement-hook-JHXLUBEN.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-VLI4OBVX.js → stage-L3T725DS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5NGNO54M.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PCCZ72C3.js → chunk-A2246ZM7.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-B6U44WPW.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-BAW3DGQO.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-BHNY3KPJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-745IDMTD.js → chunk-C7UX2ZI3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CBG67HUP.js +23 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NJFMG3IK.js → chunk-CO2DNPH7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CXTDEQ3N.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-FEPE2CE4.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-FFO7RBLN.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QNXXOFLQ.js → chunk-FXFDVM5O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QVFE5LIX.js → chunk-G6ERMFJ5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MQVBWFJF.js → chunk-IDAYTYNN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-J3YOATXR.js +80 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3UD6F2KQ.js → chunk-J6FDCAMH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-J7M52SCZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-JQS7TYQ6.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-MEJKELWC.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-PMKR4MJI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-PNPYQDHU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Q4OIRSKL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-I4Z2SCV5.js → chunk-QEVJ3Y67.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Q23K6WLV.js → chunk-SDLIUZEL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-TFYTTDAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-W3CSX6GI.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-B6OOKKOX.js → chunk-Y5GOUUYJ.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FT3KF6VJ.js → indexed-receipt-blobs-7XGVHYAO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-L6GVT42D.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-GYGP264N.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-UWTH56OD.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-KMIBD4F2.js → settlement-hook-H56537UV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-6B3O2GZ6.js → stage-WRSNJ7VI.js} +2 -2
- package/dist/cli-bundle/main.js +30 -29
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +5 -5
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/config/positional-value.d.ts +1 -1
- package/dist/core/config/positional-value.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/item-fields.d.ts +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/schema/runtime-field-values.d.ts +30 -0
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/command-types.d.ts +7 -0
- package/dist/core/shared/error-details.d.ts +98 -0
- package/dist/core/shared/error-details.js +2 -0
- package/dist/core/shared/errors.d.ts +37 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-mutation-precondition.d.ts +70 -6
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/mcp/server.js +2 -2
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/completeness.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +11 -0
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-program.js +1 -1
- package/dist/sdk/config.d.ts +1 -1
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +1 -1
- package/dist/sdk/errors.d.ts +6 -2
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/history/salvage.js +3 -3
- package/dist/sdk/history-compact.d.ts +7 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-repair.d.ts +2 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +4 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +10 -2
- package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close-many.d.ts +11 -2
- package/dist/sdk/lifecycle/close-many.js +1 -1
- package/dist/sdk/lifecycle/close.d.ts +15 -0
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/core-field-recovery.d.ts +26 -0
- package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/item-revision.d.ts +162 -0
- package/dist/sdk/lifecycle/item-revision.js +2 -0
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/lifecycle/start-blockers.d.ts +52 -0
- package/dist/sdk/lifecycle/start-blockers.js +2 -0
- package/dist/sdk/lifecycle/task-composition.d.ts +11 -0
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.d.ts +11 -2
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/declared-blockers.d.ts +16 -0
- package/dist/sdk/query/declared-blockers.js +2 -0
- package/dist/sdk/query/get.d.ts +7 -0
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/runtime-input.d.ts +12 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.d.ts +11 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/test/batch.js +2 -2
- package/dist/sdk/test/entry.d.ts +5 -0
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution.d.ts +1 -2
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/linked-command-detection.d.ts +10 -0
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/update.d.ts +2 -0
- package/dist/sdk/test/update.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +17 -6
- package/dist/sdk/workspace-transaction.js +1 -1
- package/dist/types.d.ts +6 -0
- package/dist/types.js +1 -1
- package/docs/COMMANDS.md +91 -0
- package/docs/CONFIGURATION.md +1 -0
- package/docs/EXTENSIONS.md +2 -2
- package/docs/LINKED_TEST_EDITS.md +38 -5
- package/docs/SDK.md +185 -1
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +111 -111
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +15 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3ZQQVJT2.js +0 -20
- package/dist/cli-bundle/chunks/chunk-4HW253W2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4OELCF3O.js +0 -2
- package/dist/cli-bundle/chunks/chunk-BFZUJ5QP.js +0 -115
- package/dist/cli-bundle/chunks/chunk-DAZFCSDV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-EN27ZQSV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-K46GDAKX.js +0 -6
- package/dist/cli-bundle/chunks/chunk-OJR2YGXF.js +0 -31
- package/dist/cli-bundle/chunks/chunk-QHHFXNSQ.js +0 -3
- package/dist/cli-bundle/chunks/chunk-ZNWDYDFF.js +0 -129
- package/dist/cli-bundle/chunks/item-transaction-JHPBH6N7.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-QUNQZCZ5.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-RFMM5KZ6.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-6B6Q7M5L.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4NVPDZLX.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-4UUE3YXZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5UDDRPYR.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EJJWOFP5.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-FUGYXUUL.js +0 -80
- package/dist/cli-bundle/focused-chunks/chunk-HMXVTWIV.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-JLN5CFYM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-K4FMZB4Y.js +0 -23
- package/dist/cli-bundle/focused-chunks/chunk-PF553UVP.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-RUCG6UWN.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-SGWYNU7T.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TGS5RXBY.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-WD43E7RU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-YM4AMP7H.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-F4SN7TXJ.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-7R2FXJ5O.js +0 -2
|
@@ -39,7 +39,7 @@ reason:string;
|
|
|
39
39
|
/** Restricts config positional result values accepted by command, SDK, and storage contracts. */
|
|
40
40
|
export type ConfigPositionalResult = ConfigPositionalRouted | ConfigPositionalNotRoutable;
|
|
41
41
|
/** Canonical snake-case config keys accepted by the config command and positional router. */
|
|
42
|
-
export type ConfigKey = "definition_of_done" | "item_format" | "history_missing_stream_policy" | "sprint_release_format_policy" | "parent_reference_policy" | "metadata_validation_profile" | "metadata_required_fields" | "lifecycle_stale_blocker_reason_patterns" | "lifecycle_closure_like_blocked_reason_patterns" | "lifecycle_closure_like_resolution_patterns" | "lifecycle_closure_like_actual_result_patterns" | "governance_preset" | "governance_ownership_enforcement" | "governance_create_mode_default" | "governance_close_validation_default" | "governance_require_close_reason" | "governance_create_default_type" | "governance_workflow_enforcement" | "governance_parent_reference_policy" | "governance_metadata_validation_profile" | "governance_force_required_for_stale_lock" | "test_result_tracking" | "untrusted_linked_test_execution" | "telemetry_tracking" | "agent_identity_vocabulary" | "context";
|
|
42
|
+
export type ConfigKey = "definition_of_done" | "item_format" | "history_missing_stream_policy" | "sprint_release_format_policy" | "parent_reference_policy" | "metadata_validation_profile" | "metadata_required_fields" | "lifecycle_stale_blocker_reason_patterns" | "lifecycle_closure_like_blocked_reason_patterns" | "lifecycle_closure_like_resolution_patterns" | "lifecycle_closure_like_actual_result_patterns" | "governance_preset" | "governance_ownership_enforcement" | "governance_create_mode_default" | "governance_close_validation_default" | "governance_require_close_reason" | "governance_create_default_type" | "governance_workflow_enforcement" | "governance_start_blocker_enforcement" | "governance_parent_reference_policy" | "governance_metadata_validation_profile" | "governance_force_required_for_stale_lock" | "test_result_tracking" | "untrusted_linked_test_execution" | "telemetry_tracking" | "agent_identity_vocabulary" | "context";
|
|
43
43
|
/**
|
|
44
44
|
* Resolve which typed flag a positional `pm config set <key> <value>` value should
|
|
45
45
|
* populate, plus the normalized value.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="68662c56-1f32-565f-a547-dbe120a36154")}catch{}})();const FORMAT_KEYS=new Set(["item_format"]),CRITERIA_KEYS=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),POLICY_KEYS=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_start_blocker_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),ENABLED_DISABLED_POLICY_KEYS=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),ENABLED_DISABLED_SYNONYMS={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function toCanonicalKey(keyOrAlias){const normalized=keyOrAlias.trim().toLowerCase().replaceAll("-","_");if(FORMAT_KEYS.has(normalized)||CRITERIA_KEYS.has(normalized)||POLICY_KEYS.has(normalized)||normalized==="context")return normalized}function normalizeEnabledDisabled(value){const normalized=value.trim().toLowerCase();return ENABLED_DISABLED_SYNONYMS[normalized]??value}function resolveConfigPositionalValue(canonicalKeyOrAlias,value){const key=toCanonicalKey(canonicalKeyOrAlias);return key===void 0?{routable:!1,reason:`Unknown config key "${canonicalKeyOrAlias}" cannot route a positional value.`}:key==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:FORMAT_KEYS.has(key)?{routable:!0,flag:"format",value}:CRITERIA_KEYS.has(key)?{routable:!0,flag:"criterion",values:[value]}:{routable:!0,flag:"policy",value:ENABLED_DISABLED_POLICY_KEYS.has(key)?normalizeEnabledDisabled(value):value}}export{resolveConfigPositionalValue};
|
|
2
2
|
//# sourceMappingURL=positional-value.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3a15b0ff-f638-5368-95a7-0d5d9abb3f21")}catch{}})();import{cloneCommandOptionsSnapshot,cloneContextSnapshot,cloneGlobalOptionsSnapshot,normalizeCommandName}from"./extension-runtime-helpers.js";import{stableValueEquals}from"../shared/serialization.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const DEFAULT_MUTATION_GUARD_TIMEOUT_MS=5e3;async function executeRegisteredHooks(entries,hookName,context){const warnings=[];for(const entry of entries)try{await entry.run(cloneContextSnapshot(context))}catch{warnings.push(`extension_hook_failed:${entry.layer}:${entry.name}:${hookName}`)}return warnings}async function runBeforeCommandHooks(hooks,context){return executeRegisteredHooks(hooks.beforeCommand,"beforeCommand",context)}function enforceMutationGuardDecision(decision,entry,operation){if(decision===void 0)return;if(typeof decision!="object"||decision===null||!("allow"in decision)||decision.allow!==!0&&decision.allow!==!1)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid decision.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(decision.allow)return;const denial=decision,code=typeof denial.code=="string"?denial.code.trim():"",remediation=typeof denial.remediation=="string"?denial.remediation.trim():"";if(code.length===0||remediation.length===0)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid denial.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});const message=typeof denial.message=="string"?denial.message.trim():"";throw new PmCliError(message||`Extension mutation guard ${entry.name} denied ${operation}.`,EXIT_CODE.CONFLICT,{code,reason:`${entry.layer}:${entry.name}`,nextSteps:[remediation]})}async function runBeforeMutationHooks(hooks,context){for(const entry of hooks.beforeMutation??[]){let decision,timeoutHandle;try{const guardPromise=Promise.resolve().then(()=>entry.run({pm_root:context.pm_root,operation:context.operation,before:context.before===null?null:cloneContextSnapshot(context.before),after:context.after===null?null:cloneContextSnapshot(context.after),changed_fields:[...context.changed_fields],sdk:context.sdk}));guardPromise.catch(()=>{}),decision=await Promise.race([guardPromise,new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(new PmCliError(`Extension mutation guard ${entry.name} timed out before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},DEFAULT_MUTATION_GUARD_TIMEOUT_MS),timeoutHandle.unref?.()})])}catch(error){throw error instanceof PmCliError?error:new PmCliError(`Extension mutation guard ${entry.name} failed before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(timeoutHandle)}enforceMutationGuardDecision(decision,entry,context.operation)}}async function runAfterCommandHooks(hooks,context){return executeRegisteredHooks(hooks.afterCommand,"afterCommand",context)}async function runOnWriteHooks(hooks,context){return executeRegisteredHooks(hooks.onWrite,"onWrite",context)}async function runOnReadHooks(hooks,context){return executeRegisteredHooks(hooks.onRead,"onRead",context)}async function runOnIndexHooks(hooks,context){return executeRegisteredHooks(hooks.onIndex,"onIndex",context)}function describeHandlerError(error){let raw="";error instanceof Error&&typeof error.message=="string"?raw=error.message:typeof error=="string"?raw=error:typeof error=="object"&&error!==null&&typeof error.message=="string"&&(raw=error.message);const normalized=raw.replace(/\s+/gu," ").trim();if(normalized.length===0)return"";const maxLength=300;return normalized.length>maxLength?`${normalized.slice(0,maxLength-1)}\u2026`:normalized}function readHandlerStringField(value,field){if(typeof value!="object"||value===null||typeof value[field]!="string")return;const normalized=String(value[field]).replace(/\s+/gu," ").trim();return normalized.length>0?normalized.slice(0,300):void 0}function readHandlerResultExitCode(result){if(typeof result!="object"||result===null||!Object.hasOwn(result,"exit_code"))return;const exitCode=result.exit_code;if(typeof exitCode!="number"||!Number.isInteger(exitCode)||exitCode<1||exitCode>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return exitCode}async function runCommandHandler(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{handled:!1,result:null,warnings:[]};const matched=[...commands.handlers].reverse().find(entry=>entry.command===command);if(!matched)return{handled:!1,result:null,warnings:[]};try{const result=await matched.run({command,args:cloneContextSnapshot(context.args),options:cloneContextSnapshot(context.options),global:cloneContextSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,...context.sdk===void 0?{}:{sdk:context.sdk}});return{handled:!0,result,warnings:[],...Object.fromEntries([["exitCode",readHandlerResultExitCode(result)],["errorCode",readHandlerStringField(result,"code")],["remediation",readHandlerStringField(result,"remediation")]].filter(entry=>entry[1]!==void 0))}}catch(error){const exitCode=typeof error=="object"&&error!==null&&"exitCode"in error?error.exitCode:void 0;if(typeof exitCode=="number"&&Number.isFinite(exitCode))throw error;return Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${matched.layer}:${matched.name}:${matched.command}`],errorMessage:describeHandlerError(error),...Object.fromEntries([["errorCode",readHandlerStringField(error,"code")],["remediation",readHandlerStringField(error,"remediation")]].filter(entry=>entry[1]!==void 0))},"cause",{value:error,configurable:!0})}}async function runParserOverride(parsers,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};const matched=[...parsers.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};try{const delta=await Promise.resolve(matched.run({command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel}))??{},nextArgs=Array.isArray(delta.args)?cloneContextSnapshot(delta.args):cloneContextSnapshot(context.args),nextOptions=delta.options?cloneCommandOptionsSnapshot(delta.options):cloneCommandOptionsSnapshot(context.options),nextGlobal=delta.global?cloneGlobalOptionsSnapshot(delta.global):cloneGlobalOptionsSnapshot(context.global);return{overridden:!0,context:{command,args:nextArgs,options:nextOptions,global:nextGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[`extension_parser_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}async function runPreflightOverride(preflight,context){const baseContext={command:normalizeCommandName(context.command),args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},baseDecision=cloneContextSnapshot(context.decision),matched=[...preflight.overrides].reverse().find(entry=>!entry.commands?.length||entry.commands.includes(baseContext.command));if(!matched)return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[]};try{const delta=await Promise.resolve(matched.run({command:baseContext.command,args:cloneContextSnapshot(baseContext.args),options:cloneCommandOptionsSnapshot(baseContext.options),global:cloneGlobalOptionsSnapshot(baseContext.global),pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel,decision:cloneContextSnapshot(baseDecision)}))??{},nextContext={command:baseContext.command,args:Array.isArray(delta.args)?cloneContextSnapshot(delta.args):baseContext.args,options:delta.options?cloneCommandOptionsSnapshot(delta.options):baseContext.options,global:delta.global?cloneGlobalOptionsSnapshot(delta.global):baseContext.global,pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel},nextDecision={enforce_item_format_gate:typeof delta.enforce_item_format_gate=="boolean"?delta.enforce_item_format_gate:baseDecision.enforce_item_format_gate,run_preflight_item_format_sync:typeof delta.run_preflight_item_format_sync=="boolean"?delta.run_preflight_item_format_sync:baseDecision.run_preflight_item_format_sync,run_extension_migrations:typeof delta.run_extension_migrations=="boolean"?delta.run_extension_migrations:baseDecision.run_extension_migrations,enforce_mandatory_migration_gate:typeof delta.enforce_mandatory_migration_gate=="boolean"?delta.enforce_mandatory_migration_gate:baseDecision.enforce_mandatory_migration_gate};return{overridden:!0,context:nextContext,decision:nextDecision,warnings:[]}}catch{return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[`extension_preflight_override_failed:${matched.layer}:${matched.name}`]}}}function resolveDefaultServiceResult(context){return{handled:!1,result:context.payload,warnings:[]}}function matchingServiceOverrides(services,service){return[...services.overrides].reverse().filter(entry=>entry.service===service)}function buildServiceOverrideContext(context){return{service:context.service,command:context.command?normalizeCommandName(context.command):void 0,args:context.args?cloneContextSnapshot(context.args):void 0,options:context.options?cloneCommandOptionsSnapshot(context.options):void 0,global:context.global?cloneGlobalOptionsSnapshot(context.global):void 0,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,payload:cloneContextSnapshot(context.payload)}}function isServiceOverrideDecision(value){if(typeof value!="object"||value===null||!Object.hasOwn(value,"handled"))return!1;const handled=value.handled;return handled===!0?Object.hasOwn(value,"result"):handled===!1&&Reflect.ownKeys(value).length===1}function resolveServiceOverrideValue(result,context){return isServiceOverrideDecision(result)?result.handled?{handled:!0,result:result.result}:{handled:!1,result:context.payload}:context.service==="output_format"&&result==null?{handled:!1,result:context.payload}:{handled:!0,result}}function isLegacyOutputPayloadEcho(result,context,serviceContext){return context.service==="output_format"&&typeof result=="object"&&result!==null&&stableValueEquals(result,serviceContext.payload)}function resolveMatchedServiceDecision(matched,decision,warnings){if(decision.handled){if(matched.passThrough===!0){warnings.push(`extension_service_pass_through_contract_violated:${matched.layer}:${matched.name}:${matched.service}`);return}return{handled:!0,result:decision.result,warnings}}}function runServiceOverrideSync(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=matched.run(serviceContext);if(result instanceof Promise){warnings.push(`extension_service_override_async_unsupported:${matched.layer}:${matched.name}:${matched.service}`);continue}if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}async function runServiceOverride(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=await Promise.resolve(matched.run(serviceContext));if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}function runCommandOverride(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,result:context.result,warnings:[]};const matched=[...commands.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,result:context.result,warnings:[]};try{const overrideOptions=cloneCommandOptionsSnapshot(context.options),overrideGlobal=cloneGlobalOptionsSnapshot(context.global),overrideResult=matched.run({command,args:cloneContextSnapshot(context.args),options:overrideOptions,global:overrideGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return overrideResult instanceof Promise?{overridden:!1,result:context.result,warnings:[`extension_command_override_async_unsupported:${matched.layer}:${matched.name}:${matched.command}`]}:{overridden:!0,result:overrideResult,warnings:[]}}catch{return{overridden:!1,result:context.result,warnings:[`extension_command_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}function rendererOwnsContext(entry,command,result){if((entry.commands?.length??0)>0&&!entry.commands?.includes(command))return!1;if(entry.resultDiscriminator===void 0)return!0;try{return entry.resultDiscriminator(cloneContextSnapshot(result))}catch{return!1}}function runRendererOverride(renderers,context){const rendererCommand=typeof context.command=="string"?normalizeCommandName(context.command):"",matched=[...renderers.overrides].reverse().find(entry=>entry.format===context.format&&rendererOwnsContext(entry,rendererCommand,context.result));if(!matched)return{overridden:!1,rendered:null,warnings:[]};try{const rendererArgs=Array.isArray(context.args)?cloneContextSnapshot(context.args):[],rendererOptions=cloneCommandOptionsSnapshot(context.options),rendererGlobal=cloneGlobalOptionsSnapshot(context.global),rendererPmRoot=typeof context.pm_root=="string"?context.pm_root:"",rendered=matched.run({format:context.format,command:rendererCommand,args:rendererArgs,options:rendererOptions,global:rendererGlobal,pm_root:rendererPmRoot,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return rendered==null?{overridden:!1,rendered:null,warnings:[]}:typeof rendered!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${matched.layer}:${matched.name}:${matched.format}`]}:{overridden:!0,rendered,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${matched.layer}:${matched.name}:${matched.format}`]}}}export{runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride,runServiceOverrideSync};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f49bad80-c246-59b3-950d-7143585fbdb5")}catch{}})();import{unicodeSafePrefix}from"../shared/text-normalization.js";import{cloneCommandOptionsSnapshot,cloneContextSnapshot,cloneGlobalOptionsSnapshot,normalizeCommandName}from"./extension-runtime-helpers.js";import{stableValueEquals}from"../shared/serialization.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const DEFAULT_MUTATION_GUARD_TIMEOUT_MS=5e3;async function executeRegisteredHooks(entries,hookName,context){const warnings=[];for(const entry of entries)try{await entry.run(cloneContextSnapshot(context))}catch{warnings.push(`extension_hook_failed:${entry.layer}:${entry.name}:${hookName}`)}return warnings}async function runBeforeCommandHooks(hooks,context){return executeRegisteredHooks(hooks.beforeCommand,"beforeCommand",context)}function enforceMutationGuardDecision(decision,entry,operation){if(decision===void 0)return;if(typeof decision!="object"||decision===null||!("allow"in decision)||decision.allow!==!0&&decision.allow!==!1)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid decision.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(decision.allow)return;const denial=decision,code=typeof denial.code=="string"?denial.code.trim():"",remediation=typeof denial.remediation=="string"?denial.remediation.trim():"";if(code.length===0||remediation.length===0)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid denial.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});const message=typeof denial.message=="string"?denial.message.trim():"";throw new PmCliError(message||`Extension mutation guard ${entry.name} denied ${operation}.`,EXIT_CODE.CONFLICT,{code,reason:`${entry.layer}:${entry.name}`,nextSteps:[remediation]})}async function runBeforeMutationHooks(hooks,context){for(const entry of hooks.beforeMutation??[]){let decision,timeoutHandle;try{const guardPromise=Promise.resolve().then(()=>entry.run({pm_root:context.pm_root,operation:context.operation,before:context.before===null?null:cloneContextSnapshot(context.before),after:context.after===null?null:cloneContextSnapshot(context.after),changed_fields:[...context.changed_fields],sdk:context.sdk}));guardPromise.catch(()=>{}),decision=await Promise.race([guardPromise,new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(new PmCliError(`Extension mutation guard ${entry.name} timed out before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},DEFAULT_MUTATION_GUARD_TIMEOUT_MS),timeoutHandle.unref?.()})])}catch(error){throw error instanceof PmCliError?error:new PmCliError(`Extension mutation guard ${entry.name} failed before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(timeoutHandle)}enforceMutationGuardDecision(decision,entry,context.operation)}}async function runAfterCommandHooks(hooks,context){return executeRegisteredHooks(hooks.afterCommand,"afterCommand",context)}async function runOnWriteHooks(hooks,context){return executeRegisteredHooks(hooks.onWrite,"onWrite",context)}async function runOnReadHooks(hooks,context){return executeRegisteredHooks(hooks.onRead,"onRead",context)}async function runOnIndexHooks(hooks,context){return executeRegisteredHooks(hooks.onIndex,"onIndex",context)}function describeHandlerError(error){let raw="";error instanceof Error&&typeof error.message=="string"?raw=error.message:typeof error=="string"?raw=error:typeof error=="object"&&error!==null&&typeof error.message=="string"&&(raw=error.message);const normalized=raw.replace(/\s+/gu," ").trim();if(normalized.length===0)return"";const maxLength=300;return normalized.length>maxLength?`${unicodeSafePrefix(normalized,maxLength-1)}\u2026`:normalized}function readHandlerStringField(value,field){if(typeof value!="object"||value===null||typeof value[field]!="string")return;const normalized=String(value[field]).replace(/\s+/gu," ").trim();return normalized.length>0?unicodeSafePrefix(normalized,300):void 0}function readHandlerResultExitCode(result){if(typeof result!="object"||result===null||!Object.hasOwn(result,"exit_code"))return;const exitCode=result.exit_code;if(typeof exitCode!="number"||!Number.isInteger(exitCode)||exitCode<1||exitCode>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return exitCode}async function runCommandHandler(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{handled:!1,result:null,warnings:[]};const matched=[...commands.handlers].reverse().find(entry=>entry.command===command);if(!matched)return{handled:!1,result:null,warnings:[]};try{const result=await matched.run({command,args:cloneContextSnapshot(context.args),options:cloneContextSnapshot(context.options),global:cloneContextSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,...context.sdk===void 0?{}:{sdk:context.sdk}});return{handled:!0,result,warnings:[],...Object.fromEntries([["exitCode",readHandlerResultExitCode(result)],["errorCode",readHandlerStringField(result,"code")],["remediation",readHandlerStringField(result,"remediation")]].filter(entry=>entry[1]!==void 0))}}catch(error){const exitCode=typeof error=="object"&&error!==null&&"exitCode"in error?error.exitCode:void 0;if(typeof exitCode=="number"&&Number.isFinite(exitCode))throw error;return Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${matched.layer}:${matched.name}:${matched.command}`],errorMessage:describeHandlerError(error),...Object.fromEntries([["errorCode",readHandlerStringField(error,"code")],["remediation",readHandlerStringField(error,"remediation")]].filter(entry=>entry[1]!==void 0))},"cause",{value:error,configurable:!0})}}async function runParserOverride(parsers,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};const matched=[...parsers.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};try{const delta=await Promise.resolve(matched.run({command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel}))??{},nextArgs=Array.isArray(delta.args)?cloneContextSnapshot(delta.args):cloneContextSnapshot(context.args),nextOptions=delta.options?cloneCommandOptionsSnapshot(delta.options):cloneCommandOptionsSnapshot(context.options),nextGlobal=delta.global?cloneGlobalOptionsSnapshot(delta.global):cloneGlobalOptionsSnapshot(context.global);return{overridden:!0,context:{command,args:nextArgs,options:nextOptions,global:nextGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[`extension_parser_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}async function runPreflightOverride(preflight,context){const baseContext={command:normalizeCommandName(context.command),args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},baseDecision=cloneContextSnapshot(context.decision),matched=[...preflight.overrides].reverse().find(entry=>!entry.commands?.length||entry.commands.includes(baseContext.command));if(!matched)return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[]};try{const delta=await Promise.resolve(matched.run({command:baseContext.command,args:cloneContextSnapshot(baseContext.args),options:cloneCommandOptionsSnapshot(baseContext.options),global:cloneGlobalOptionsSnapshot(baseContext.global),pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel,decision:cloneContextSnapshot(baseDecision)}))??{},nextContext={command:baseContext.command,args:Array.isArray(delta.args)?cloneContextSnapshot(delta.args):baseContext.args,options:delta.options?cloneCommandOptionsSnapshot(delta.options):baseContext.options,global:delta.global?cloneGlobalOptionsSnapshot(delta.global):baseContext.global,pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel},nextDecision={enforce_item_format_gate:typeof delta.enforce_item_format_gate=="boolean"?delta.enforce_item_format_gate:baseDecision.enforce_item_format_gate,run_preflight_item_format_sync:typeof delta.run_preflight_item_format_sync=="boolean"?delta.run_preflight_item_format_sync:baseDecision.run_preflight_item_format_sync,run_extension_migrations:typeof delta.run_extension_migrations=="boolean"?delta.run_extension_migrations:baseDecision.run_extension_migrations,enforce_mandatory_migration_gate:typeof delta.enforce_mandatory_migration_gate=="boolean"?delta.enforce_mandatory_migration_gate:baseDecision.enforce_mandatory_migration_gate};return{overridden:!0,context:nextContext,decision:nextDecision,warnings:[]}}catch{return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[`extension_preflight_override_failed:${matched.layer}:${matched.name}`]}}}function resolveDefaultServiceResult(context){return{handled:!1,result:context.payload,warnings:[]}}function matchingServiceOverrides(services,service){return[...services.overrides].reverse().filter(entry=>entry.service===service)}function buildServiceOverrideContext(context){return{service:context.service,command:context.command?normalizeCommandName(context.command):void 0,args:context.args?cloneContextSnapshot(context.args):void 0,options:context.options?cloneCommandOptionsSnapshot(context.options):void 0,global:context.global?cloneGlobalOptionsSnapshot(context.global):void 0,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,payload:cloneContextSnapshot(context.payload)}}function isServiceOverrideDecision(value){if(typeof value!="object"||value===null||!Object.hasOwn(value,"handled"))return!1;const handled=value.handled;return handled===!0?Object.hasOwn(value,"result"):handled===!1&&Reflect.ownKeys(value).length===1}function resolveServiceOverrideValue(result,context){return isServiceOverrideDecision(result)?result.handled?{handled:!0,result:result.result}:{handled:!1,result:context.payload}:context.service==="output_format"&&result==null?{handled:!1,result:context.payload}:{handled:!0,result}}function isLegacyOutputPayloadEcho(result,context,serviceContext){return context.service==="output_format"&&typeof result=="object"&&result!==null&&stableValueEquals(result,serviceContext.payload)}function resolveMatchedServiceDecision(matched,decision,warnings){if(decision.handled){if(matched.passThrough===!0){warnings.push(`extension_service_pass_through_contract_violated:${matched.layer}:${matched.name}:${matched.service}`);return}return{handled:!0,result:decision.result,warnings}}}function runServiceOverrideSync(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=matched.run(serviceContext);if(result instanceof Promise){warnings.push(`extension_service_override_async_unsupported:${matched.layer}:${matched.name}:${matched.service}`);continue}if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}async function runServiceOverride(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=await Promise.resolve(matched.run(serviceContext));if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}function runCommandOverride(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,result:context.result,warnings:[]};const matched=[...commands.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,result:context.result,warnings:[]};try{const overrideOptions=cloneCommandOptionsSnapshot(context.options),overrideGlobal=cloneGlobalOptionsSnapshot(context.global),overrideResult=matched.run({command,args:cloneContextSnapshot(context.args),options:overrideOptions,global:overrideGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return overrideResult instanceof Promise?{overridden:!1,result:context.result,warnings:[`extension_command_override_async_unsupported:${matched.layer}:${matched.name}:${matched.command}`]}:{overridden:!0,result:overrideResult,warnings:[]}}catch{return{overridden:!1,result:context.result,warnings:[`extension_command_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}function rendererOwnsContext(entry,command,result){if((entry.commands?.length??0)>0&&!entry.commands?.includes(command))return!1;if(entry.resultDiscriminator===void 0)return!0;try{return entry.resultDiscriminator(cloneContextSnapshot(result))}catch{return!1}}function runRendererOverride(renderers,context){const rendererCommand=typeof context.command=="string"?normalizeCommandName(context.command):"",matched=[...renderers.overrides].reverse().find(entry=>entry.format===context.format&&rendererOwnsContext(entry,rendererCommand,context.result));if(!matched)return{overridden:!1,rendered:null,warnings:[]};try{const rendererArgs=Array.isArray(context.args)?cloneContextSnapshot(context.args):[],rendererOptions=cloneCommandOptionsSnapshot(context.options),rendererGlobal=cloneGlobalOptionsSnapshot(context.global),rendererPmRoot=typeof context.pm_root=="string"?context.pm_root:"",rendered=matched.run({format:context.format,command:rendererCommand,args:rendererArgs,options:rendererOptions,global:rendererGlobal,pm_root:rendererPmRoot,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return rendered==null?{overridden:!1,rendered:null,warnings:[]}:typeof rendered!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${matched.layer}:${matched.name}:${matched.format}`]}:{overridden:!0,rendered,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${matched.layer}:${matched.name}:${matched.format}`]}}}export{runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride,runServiceOverrideSync};
|
|
2
2
|
//# sourceMappingURL=extension-hook-runtime.js.map
|
|
@@ -15,7 +15,7 @@ export declare function collectRegisteredItemFieldNames(registrations:ExtensionR
|
|
|
15
15
|
* rejected input separately from legal registered keys. Parsing never writes
|
|
16
16
|
* tracker state, so a failed assignment cannot persist partial metadata.
|
|
17
17
|
*/
|
|
18
|
-
export declare function parseRegisteredItemFieldAssignments(rawFields:string[] | undefined,registrations:ExtensionRegistrationRegistry | null,resolveCoreFieldRecovery?:(field:string) => Pick<PmCliErrorContext,"recovery" | "nextSteps">):Record<string,unknown>;
|
|
18
|
+
export declare function parseRegisteredItemFieldAssignments(rawFields:string[] | undefined,registrations:ExtensionRegistrationRegistry | null,resolveCoreFieldRecovery?:(field:string) => Pick<PmCliErrorContext,"recovery" | "nextSteps">,resolveSchemaFieldRecovery?:(field:string) => Pick<PmCliErrorContext,"recovery" | "nextSteps"> | undefined):Record<string,unknown>;
|
|
19
19
|
/** Implements apply registered item field defaults and validation for the public runtime surface of this module. */
|
|
20
20
|
export declare function applyRegisteredItemFieldDefaultsAndValidation(itemMetadata:Record<string,unknown>,registrations:ExtensionRegistrationRegistry | null,options?:{
|
|
21
21
|
skipDefaultFields?:ReadonlySet<string>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4e02447f-3fb0-5f7c-9512-be2b348fd082")}catch{}})();import{normalizeItemFieldType}from"./item-field-types.js";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const reservedItemFieldNames=new Set(ITEM_METADATA_KEY_ORDER),RESERVED_ITEM_FIELD_NAMES=Object.freeze({get size(){return reservedItemFieldNames.size},has(value){return reservedItemFieldNames.has(value)},entries(){return reservedItemFieldNames.entries()},keys(){return reservedItemFieldNames.keys()},values(){return reservedItemFieldNames.values()},forEach(callback,thisArg){reservedItemFieldNames.forEach(value=>callback.call(thisArg,value,value,RESERVED_ITEM_FIELD_NAMES))},[Symbol.iterator](){return reservedItemFieldNames.values()}});function normalizeFieldName(value){if(typeof value!="string")return null;const normalized=value.trim();return normalized.length>0?normalized:null}function normalizeFieldType(value){return typeof value!="string"?null:normalizeItemFieldType(value)}function cloneFieldValue(value){try{return structuredClone(value)}catch{return value}}function parseFieldAssignment(raw){const trimmed=raw.trim(),separatorIndex=trimmed.indexOf("=");if(separatorIndex<=0)throw new PmCliError(`--field entries must use name=value syntax, received: ${raw}`,EXIT_CODE.USAGE);const key=trimmed.slice(0,separatorIndex).trim(),value=trimmed.slice(separatorIndex+1);return{key,value}}function parseJsonFieldValue(raw,fieldName,expectedType){try{const parsed=JSON.parse(raw);if(expectedType==="array"&&Array.isArray(parsed)||expectedType==="object"&&typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed))return parsed}catch{}throw new PmCliError(`--field ${fieldName}=... must be valid JSON ${expectedType}`,EXIT_CODE.USAGE)}function coerceRegisteredFieldValue(fieldName,fieldType,raw){if(fieldType==="string")return raw;if(fieldType==="number"){const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError(`--field ${fieldName}=... must be a number`,EXIT_CODE.USAGE);const parsed=Number(trimmed);if(!Number.isFinite(parsed))throw new PmCliError(`--field ${fieldName}=... must be a number`,EXIT_CODE.USAGE);return parsed}if(fieldType==="boolean"){const normalized=raw.trim().toLowerCase();if(normalized==="true"||normalized==="1"||normalized==="yes")return!0;if(normalized==="false"||normalized==="0"||normalized==="no")return!1;throw new PmCliError(`--field ${fieldName}=... must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}return fieldType==="string_array"?raw.split(/[\n,|]/u).map(value=>value.trim()).filter(value=>value.length>0):parseJsonFieldValue(raw,fieldName,fieldType)}function collectRegisteredFieldDefinitions(registrations){const definitions=new Map;if(!registrations)return definitions;for(const registration of registrations.item_fields)for(const definition of registration.fields){const fieldName=normalizeFieldName(definition.name),fieldType=normalizeFieldType(definition.type);if(!fieldName||!fieldType)continue;const existing=definitions.get(fieldName);if(existing&&existing.type!==fieldType)throw new PmCliError(`Extension item field "${fieldName}" is declared with conflicting types: ${existing.type}, ${fieldType}`,EXIT_CODE.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});definitions.set(fieldName,{name:fieldName,type:fieldType})}return definitions}function assertNotReservedItemFieldName(fieldName){if(RESERVED_ITEM_FIELD_NAMES.has(fieldName))throw new PmCliError(`Extension item field "${fieldName}" collides with built-in item metadata "${fieldName}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...RESERVED_ITEM_FIELD_NAMES].sort((left,right)=>left.localeCompare(right)).join(", ")}.`,EXIT_CODE.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function collectRegisteredItemFieldNames(registrations){return[...collectRegisteredFieldDefinitions(registrations).keys()].sort((left,right)=>left.localeCompare(right))}function parseRegisteredItemFieldAssignments(rawFields,registrations,resolveCoreFieldRecovery,resolveSchemaFieldRecovery){if(!rawFields||rawFields.length===0)return{};const definitions=collectRegisteredFieldDefinitions(registrations),values={};for(const raw of rawFields){const{key,value}=parseFieldAssignment(raw),definition=definitions.get(key);if(!definition)throw unregisteredFieldRefusal(key,definitions,resolveCoreFieldRecovery,resolveSchemaFieldRecovery);assertNotReservedItemFieldName(definition.name),values[definition.name]=coerceRegisteredFieldValue(definition.name,definition.type,value)}return values}function unregisteredFieldRefusal(key,definitions,resolveCoreFieldRecovery,resolveSchemaFieldRecovery){if(RESERVED_ITEM_FIELD_NAMES.has(key)){const guidance=resolveCoreFieldRecovery?.(key)??{recovery:{provided_fields:[key]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new PmCliError(`--field ${key} is a core item field, not an extension field`,EXIT_CODE.USAGE,{code:"core_item_field_requires_dedicated_flag",field:key,...guidance})}const schemaGuidance=resolveSchemaFieldRecovery?.(key);if(schemaGuidance!==void 0){const flag=schemaGuidance.recovery?.suggested_flags?.[0];return new PmCliError(flag===void 0?`--field ${key} is a project-schema field, not an extension field`:`--field ${key} is a project-schema field; set it with its declared flag ${flag}`,EXIT_CODE.USAGE,{code:"project_schema_field_requires_declared_flag",field:key,changed:!1,...schemaGuidance})}const known=[...definitions.keys()].sort((left,right)=>left.localeCompare(right));return new PmCliError(`--field ${key} is not declared by an active extension item-field registration`,EXIT_CODE.USAGE,{code:"extension_item_field_unknown",field:key,recovery:{provided_fields:[key]},nextSteps:known.length>0?[`Use one of the declared fields: ${known.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}function isValidFieldType(value,expectedType){return expectedType==="string"?typeof value=="string":expectedType==="number"?typeof value=="number"&&Number.isFinite(value):expectedType==="boolean"?typeof value=="boolean":expectedType==="array"?Array.isArray(value):expectedType==="string_array"?Array.isArray(value)&&value.every(entry=>typeof entry=="string"):typeof value=="object"&&value!==null&&!Array.isArray(value)}function isAllowedFieldValue(value,allowed){return!allowed||allowed.length===0?!0:allowed.some(candidate=>Object.is(candidate,value))}function applyRegisteredItemFieldDefaultsAndValidation(itemMetadata,registrations,options={}){if(registrations){collectRegisteredFieldDefinitions(registrations);for(const registration of registrations.item_fields)for(const definition of registration.fields){const fieldName=normalizeFieldName(definition.name);if(!fieldName)continue;assertNotReservedItemFieldName(fieldName),!(fieldName in itemMetadata)&&!options.skipDefaultFields?.has(fieldName)&&Object.prototype.hasOwnProperty.call(definition,"default")&&(itemMetadata[fieldName]=cloneFieldValue(definition.default));const currentValue=itemMetadata[fieldName];if(currentValue===void 0)continue;const expectedType=normalizeFieldType(definition.type);if(expectedType&&!isValidFieldType(currentValue,expectedType))throw new TypeError(`Item field "${fieldName}" must be of type ${expectedType}`);const allowedValues=Array.isArray(definition.values)?definition.values:void 0;if(!isAllowedFieldValue(currentValue,allowedValues))throw new TypeError(`Item field "${fieldName}" must match one of the configured allowed values`)}}}export{RESERVED_ITEM_FIELD_NAMES,applyRegisteredItemFieldDefaultsAndValidation,collectRegisteredItemFieldNames,parseRegisteredItemFieldAssignments};
|
|
2
2
|
//# sourceMappingURL=item-fields.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="32b0a81e-6a21-528a-8cf8-3e764f382044")}catch{}})();const RESERVED_EXTENSION_HOST_FLAGS=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"},{flag:"--expect-hash",value_name:"revision"}]),RESERVED_EXTENSION_HOST_FLAG_NAMES=new Set(RESERVED_EXTENSION_HOST_FLAGS.flatMap(definition=>[definition.flag,...definition.aliases??[]]));export{RESERVED_EXTENSION_HOST_FLAGS,RESERVED_EXTENSION_HOST_FLAG_NAMES};
|
|
2
2
|
//# sourceMappingURL=reserved-host-flags.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5f3ae68b-2ae8-505c-bfc8-10e605c39a9e")}catch{}})();import fs from"node:fs/promises";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{locateItem,readLocatedItem}from"../store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,hasActiveItemRevisionScope}from"../store/item-mutation-precondition.js";import{resolveGovernanceKnobs}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";function checkHistoryRewriteOwnership(params){if(!params.itemDocument)return[];const assigned=params.itemDocument.metadata?.assignee?.trim();if(!assigned||assigned===params.author||params.force)return[];const governance=resolveGovernanceKnobs(params.settings);if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return governance.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`]:[]}async function assertDeclaredRevisionOnDrift(params){if(!hasActiveItemRevisionScope(params.pmRoot))return;const located=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),document=located===null?EMPTY_CANONICAL_DOCUMENT:(await readLocatedItem(located,{schema:params.settings.schema}).catch(()=>null))?.document;document!==void 0&&assertItemMutationPreconditions(params.pmRoot,document,params.subject.id)}async function verifyHistoryRewriteNoDrift(params){const historyRawUnderLock=await readFileIfExists(params.subject.historyPath);if(historyRawUnderLock!==params.historyRawBeforeLock)throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);const locatedUnderLock=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),loadedItemUnderLock=locatedUnderLock?params.readItem?await params.readItem(locatedUnderLock):await readLocatedItem(locatedUnderLock,{schema:params.settings.schema}):null;if((loadedItemUnderLock?.raw??null)!==(params.currentItemRawBeforeLock??null))throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);return{historyRawUnderLock,locatedUnderLock,loadedItemUnderLock}}async function writeHistoryRawWithRollback(params){const writeHistoryRaw=params.writeHistoryRaw??writeFileAtomic;try{await writeHistoryRaw(params.historyPath,params.nextHistoryRaw),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(error){try{params.historyRawUnderLock===null?await fs.rm(params.historyPath,{force:!0}):await writeHistoryRaw(params.historyPath,params.historyRawUnderLock),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(rollbackError){throw new AggregateError([error,rollbackError],`History rewrite failed and rollback also failed: ${String(error)}`)}throw error}}async function executeHistoryRewrite(params){const warnings=[...checkHistoryRewriteOwnership({itemDocument:params.itemDocument,subjectId:params.subject.id,author:params.author,force:params.force,settings:params.settings})],releaseLock=await acquireLock(params.pmRoot,params.subject.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:params.operation}),tombstone=EMPTY_CANONICAL_DOCUMENT;if(assertItemMutationPreconditions(params.pmRoot,verified.loadedItemUnderLock?.document??tombstone,params.subject.id),await params.applyRewrite(verified),hasActiveItemRevisionScope(params.pmRoot)){const relocated=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),rewritten=relocated===null?tombstone:(await readLocatedItem(relocated,{schema:params.settings.schema})).document;advanceItemMutationPreconditions(params.pmRoot,rewritten,params.subject.id)}return params.applyPostRewrite&&warnings.push(...await params.applyPostRewrite(verified)),warnings}finally{await releaseLock()}}export{checkHistoryRewriteOwnership,executeHistoryRewrite,verifyHistoryRewriteNoDrift,writeHistoryRawWithRollback};
|
|
2
2
|
//# sourceMappingURL=history-rewrite.js.map
|
|
@@ -1,4 +1,34 @@
|
|
|
1
1
|
import { type RuntimeFieldDefinitionResolved,type RuntimeFieldRegistry } from "./runtime-schema.js";
|
|
2
|
+
import type { RuntimeFieldCommand } from "../../types/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* The option name an SDK caller passes to set exactly this runtime field: the
|
|
5
|
+
* first name {@link readRuntimeFieldOptionValue} reads for it (preferring the
|
|
6
|
+
* camelCase of its CLI flag, as Commander derives it) that no other declared
|
|
7
|
+
* field also reads. Undefined when every name is shared, because following
|
|
8
|
+
* such a hint would also set the other field.
|
|
9
|
+
*/
|
|
10
|
+
export declare function runtimeFieldSdkOptionName(definition:RuntimeFieldDefinitionResolved,registry:Pick<RuntimeFieldRegistry,"definitions">,reservedOptions?:ReadonlySet<string>,command?:RuntimeFieldCommand):string | undefined;
|
|
11
|
+
/** The command-line token for a declared spelling: a short alias keeps its single dash. */
|
|
12
|
+
export declare function runtimeFieldFlagToken(flag:string):string;
|
|
13
|
+
/**
|
|
14
|
+
* A declared spelling that sets exactly this runtime field: the declared flag
|
|
15
|
+
* or an alias that is not a host flag, is not a negation (its value would
|
|
16
|
+
* land under another key that this field never reads), whose parsed option
|
|
17
|
+
* name no other active field and no host option reads, and which no
|
|
18
|
+
* earlier-read key of this field can shadow. Undefined when no spelling
|
|
19
|
+
* qualifies. Render it with {@link runtimeFieldFlagToken}.
|
|
20
|
+
*/
|
|
21
|
+
export declare function runtimeFieldCliFlagRoute(definition:RuntimeFieldDefinitionResolved,registry:Pick<RuntimeFieldRegistry,"definitions">,reserved:{
|
|
22
|
+
options:ReadonlySet<string>;
|
|
23
|
+
flags:ReadonlySet<string>;
|
|
24
|
+
},command?:RuntimeFieldCommand):string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* The option key Commander stores for a long flag (without dashes): it strips
|
|
27
|
+
* a negating `no-` prefix and camel-cases across hyphens only, so
|
|
28
|
+
* `--review-url` parses to `reviewUrl`, `--no-title` to `title`, and
|
|
29
|
+
* `--review.url` keeps the literal key `review.url`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function commanderOptionAttribute(flag:string):string;
|
|
2
32
|
/** Implements read runtime field option value for the public runtime surface of this module. */
|
|
3
33
|
export declare function readRuntimeFieldOptionValue(options:Record<string,unknown>,definition:RuntimeFieldDefinitionResolved):unknown;
|
|
4
34
|
/** Validate a declared field; option arrays represent repeated flags, while metadata containers retain their exact shape. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4d5692ce-ec33-5eb4-bd9b-7497ffe25b0e")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{isRfc3339DateTime}from"../shared/time.js";import{runtimeFieldOptionTarget}from"./runtime-schema.js";const MAX_VALUE_SCHEMA_DEPTH=16;function toCamelToken(value){const segments=value.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(segment=>segment.length>0).map(segment=>segment.toLowerCase());if(segments.length===0)return value;const[first,...rest]=segments;return`${first}${rest.map(segment=>`${segment.slice(0,1).toUpperCase()}${segment.slice(1)}`).join("")}`}function resolveCandidateOptionKeys(definition){return[...new Set([runtimeFieldOptionTarget(definition),toCamelToken(definition.key),toCamelToken(definition.cli_flag),...definition.cli_aliases.map(alias=>toCamelToken(alias))])]}function readRuntimeFieldOptionValue(options,definition){for(const candidateKey of resolveCandidateOptionKeys(definition)){if(!Object.hasOwn(options,candidateKey))continue;const value=options[candidateKey];if(value!==void 0)return value}}function normalizeStringArrayValue(value){return Array.isArray(value)?value.flatMap(entry=>normalizeStringArrayValue(entry)).map(entry=>entry.trim()).filter(entry=>entry.length>0):typeof value=="string"?value.split(/[,\n|]/).map(entry=>entry.trim()).filter(entry=>entry.length>0):value==null?[]:[String(value).trim()].filter(entry=>entry.length>0)}function parseBooleanValue(raw,label){if(typeof raw=="boolean")return raw;if(typeof raw=="number"){if(raw===1)return!0;if(raw===0)return!1}if(typeof raw=="string"){const normalized=raw.trim().toLowerCase();if(normalized==="true"||normalized==="1"||normalized==="yes")return!0;if(normalized==="false"||normalized==="0"||normalized==="no")return!1}throw new PmCliError(`${label} must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}function parseNumberValue(raw,label){if(typeof raw=="number"&&Number.isFinite(raw))return raw;const candidate=typeof raw=="string"?raw.trim():String(raw),parsed=Number(candidate);if(!Number.isFinite(parsed))throw new PmCliError(`${label} must be a number`,EXIT_CODE.USAGE);return parsed}function parseJsonContainerValue(raw,label,expectedType){const parsed=typeof raw=="string"?(()=>{try{return JSON.parse(raw)}catch{return}})():raw;if(expectedType==="array"&&Array.isArray(parsed)||expectedType==="object"&&typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed))return parsed;throw new PmCliError(`${label} must be valid JSON ${expectedType}`,EXIT_CODE.USAGE)}function valueMatchesSchemaType(value,type){return type===void 0?!0:type==="array"?Array.isArray(value):type==="object"?typeof value=="object"&&value!==null&&!Array.isArray(value):typeof value===type}function runtimeFieldPrimitiveSchemaError(value,schema,path){if(schema.const!==void 0&&stableStringify(value)!==stableStringify(schema.const))return`${path} must equal ${stableStringify(schema.const)}`;if(schema.enum!==void 0&&!schema.enum.some(candidate=>stableStringify(candidate)===stableStringify(value)))return`${path} must be one of ${schema.enum.map(entry=>stableStringify(entry)).join("|")}`;if(!valueMatchesSchemaType(value,schema.type))return`${path} must match configured type ${String(schema.type)}`;if(typeof value=="string"){if(schema.min_length!==void 0&&value.length<schema.min_length)return`${path} must contain at least ${schema.min_length} characters`;if(schema.format==="date-time"&&!isRfc3339DateTime(value))return`${path} must be an RFC 3339 date-time`}}function runtimeFieldArraySchemaError(value,schema,path,depth){if(Array.isArray(value)){if(schema.min_items!==void 0&&value.length<schema.min_items)return`${path} must contain at least ${schema.min_items} items`;if(schema.items)for(const[index,entry]of value.entries()){const error=runtimeFieldSchemaError(entry,schema.items,`${path}[${index}]`,depth+1);if(error)return error}}}function runtimeFieldObjectSchemaError(value,schema,path,depth){if(typeof value!="object"||value===null||Array.isArray(value))return;const record=value;for(const key of schema.required??[])if(!Object.hasOwn(record,key))return`${path}.${key} is required`;for(const[key,entry]of Object.entries(record)){const propertySchema=schema.properties?.[key];if(!propertySchema){if(schema.additional_properties===!1)return`${path}.${key} is not allowed`;continue}const error=runtimeFieldSchemaError(entry,propertySchema,`${path}.${key}`,depth+1);if(error)return error}}function runtimeFieldSchemaError(value,schema,path,depth=0){if(depth>MAX_VALUE_SCHEMA_DEPTH)return`${path} value schema exceeds maximum depth`;const directError=runtimeFieldPrimitiveSchemaError(value,schema,path);if(directError)return directError;const arrayError=runtimeFieldArraySchemaError(value,schema,path,depth);if(arrayError)return arrayError;const objectError=runtimeFieldObjectSchemaError(value,schema,path,depth);if(objectError)return objectError;if(!schema.one_of)return;let matches=0;for(const candidate of schema.one_of)if(runtimeFieldSchemaError(value,candidate,path,depth+1)===void 0&&(matches+=1,matches>1))break;return matches===1?void 0:`${path} must match exactly one configured schema variant`}function validateRuntimeFieldValue(definition,value,label){if(!definition.value_schema||value===void 0)return value;const error=runtimeFieldSchemaError(value,definition.value_schema,label);if(error)throw new PmCliError(error,EXIT_CODE.USAGE);return value}function coerceRuntimeContainerValue(definition,rawValue,label,inputKind){const raw=inputKind==="option"&&Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(raw!==void 0)return validateRuntimeFieldValue(definition,parseJsonContainerValue(raw,label,definition.type),label)}function coerceRuntimeFieldValue(definition,rawValue,labelOverride,inputKind="option"){const label=labelOverride??`--${definition.cli_flag}`;if(definition.type==="array"||definition.type==="object")return coerceRuntimeContainerValue(definition,rawValue,label,inputKind);if(definition.repeatable||definition.type==="string_array"){const values=normalizeStringArrayValue(rawValue);return definition.type==="number"?validateRuntimeFieldValue(definition,values.map(value=>parseNumberValue(value,label)),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,values.map(value=>parseBooleanValue(value,label)),label):validateRuntimeFieldValue(definition,values,label)}const scalarRaw=Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(scalarRaw!==void 0)return definition.type==="number"?validateRuntimeFieldValue(definition,parseNumberValue(scalarRaw,label),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,parseBooleanValue(scalarRaw,label),label):validateRuntimeFieldValue(definition,typeof scalarRaw=="string"?scalarRaw:String(scalarRaw),label)}function shouldRequireFieldOnCreate(definition,itemTypeName){return!definition.required&&!definition.required_on_create?!1:definition.required_types.length===0?!0:itemTypeName?definition.required_types.map(value=>value.toLowerCase()).includes(itemTypeName.trim().toLowerCase()):!1}function collectRuntimeCreateFieldValues(options,fieldRegistry,itemTypeName){const values={},missingRequiredFlags=[];for(const definition of fieldRegistry.command_to_fields.get("create")??[]){const rawValue=readRuntimeFieldOptionValue(options,definition);if(rawValue===void 0){shouldRequireFieldOnCreate(definition,itemTypeName)&&missingRequiredFlags.push(`--${definition.cli_flag}`);continue}values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)}return{values,missing_required_flags:[...new Set(missingRequiredFlags)].sort((left,right)=>left.localeCompare(right))}}function collectRuntimeUpdateFieldValues(options,fieldRegistry,commands=["update"]){const values={},definitions=(commands??["update"]).flatMap(command=>fieldRegistry.command_to_fields.get(command)??[]),seen=new Set;for(const definition of definitions){const rawValue=readRuntimeFieldOptionValue(options,definition);rawValue!==void 0&&(seen.has(definition.metadata_key)||(seen.add(definition.metadata_key),values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)))}return values}export{coerceRuntimeFieldValue,collectRuntimeCreateFieldValues,collectRuntimeUpdateFieldValues,readRuntimeFieldOptionValue};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6635e694-c788-5805-adb8-ed93cc931946")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{isRfc3339DateTime}from"../shared/time.js";import{runtimeFieldOptionTarget}from"./runtime-schema.js";const MAX_VALUE_SCHEMA_DEPTH=16;function toCamelToken(value){const segments=value.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(segment=>segment.length>0).map(segment=>segment.toLowerCase());if(segments.length===0)return value;const[first,...rest]=segments;return`${first}${rest.map(segment=>`${segment.slice(0,1).toUpperCase()}${segment.slice(1)}`).join("")}`}function runtimeFieldSdkOptionName(definition,registry,reservedOptions=new Set,command){if(hasStorageTwin(definition,registry,command))return;const taken=foreignRuntimeFieldOptionNames(definition,registry,reservedOptions,command),readOrder=resolveCandidateOptionKeys(definition);return[toCamelToken(definition.cli_flag),...readOrder].find(name=>!taken.has(name)&&isUnshadowedOptionKey(name,readOrder,taken))}function isUnshadowedOptionKey(key,readOrder,taken){for(const earlier of readOrder){if(earlier===key)break;if(taken.has(earlier))return!1}return!0}function hasStorageTwin(definition,registry,command){return registry.definitions.some(candidate=>candidate!==definition&&candidate.metadata_key===definition.metadata_key&&(command===void 0||candidate.commands.includes(command)))}function foreignRuntimeFieldOptionNames(definition,registry,reservedOptions,command){return new Set([...reservedOptions,...registry.definitions.filter(candidate=>candidate!==definition&&(command===void 0||candidate.commands.includes(command))).flatMap(candidate=>resolveCandidateOptionKeys(candidate))])}function isNegatingFlag(flag){return flag.replace(/^-+/u,"").startsWith("no-")}function runtimeFieldFlagToken(flag){return flag.startsWith("-")?flag:`--${flag}`}function runtimeFieldCliFlagRoute(definition,registry,reserved,command){if(hasStorageTwin(definition,registry,command))return;const taken=foreignRuntimeFieldOptionNames(definition,registry,reserved.options,command),readOrder=resolveCandidateOptionKeys(definition);return[definition.cli_flag,...definition.cli_aliases].find(flag=>{const key=commanderOptionAttribute(flag);return isNegatingFlag(flag)||reserved.flags.has(runtimeFieldFlagToken(flag))||taken.has(key)?!1:isUnshadowedOptionKey(key,readOrder,taken)})}function commanderOptionAttribute(flag){return flag.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((name,word)=>`${name}${word.charAt(0).toUpperCase()}${word.slice(1)}`)}function resolveCandidateOptionKeys(definition){return[...new Set([runtimeFieldOptionTarget(definition),toCamelToken(definition.key),toCamelToken(definition.cli_flag),...definition.cli_aliases.map(alias=>toCamelToken(alias)),...[definition.cli_flag,...definition.cli_aliases].filter(flag=>!isNegatingFlag(flag)).map(flag=>commanderOptionAttribute(flag))])]}function readRuntimeFieldOptionValue(options,definition){for(const candidateKey of resolveCandidateOptionKeys(definition)){if(!Object.hasOwn(options,candidateKey))continue;const value=options[candidateKey];if(value!==void 0)return value}}function normalizeStringArrayValue(value){return Array.isArray(value)?value.flatMap(entry=>normalizeStringArrayValue(entry)).map(entry=>entry.trim()).filter(entry=>entry.length>0):typeof value=="string"?value.split(/[,\n|]/).map(entry=>entry.trim()).filter(entry=>entry.length>0):value==null?[]:[String(value).trim()].filter(entry=>entry.length>0)}function parseBooleanValue(raw,label){if(typeof raw=="boolean")return raw;if(typeof raw=="number"){if(raw===1)return!0;if(raw===0)return!1}if(typeof raw=="string"){const normalized=raw.trim().toLowerCase();if(normalized==="true"||normalized==="1"||normalized==="yes")return!0;if(normalized==="false"||normalized==="0"||normalized==="no")return!1}throw new PmCliError(`${label} must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}function parseNumberValue(raw,label){if(typeof raw=="number"&&Number.isFinite(raw))return raw;const candidate=typeof raw=="string"?raw.trim():String(raw),parsed=Number(candidate);if(!Number.isFinite(parsed))throw new PmCliError(`${label} must be a number`,EXIT_CODE.USAGE);return parsed}function parseJsonContainerValue(raw,label,expectedType){const parsed=typeof raw=="string"?(()=>{try{return JSON.parse(raw)}catch{return}})():raw;if(expectedType==="array"&&Array.isArray(parsed)||expectedType==="object"&&typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed))return parsed;throw new PmCliError(`${label} must be valid JSON ${expectedType}`,EXIT_CODE.USAGE)}function valueMatchesSchemaType(value,type){return type===void 0?!0:type==="array"?Array.isArray(value):type==="object"?typeof value=="object"&&value!==null&&!Array.isArray(value):typeof value===type}function runtimeFieldPrimitiveSchemaError(value,schema,path){if(schema.const!==void 0&&stableStringify(value)!==stableStringify(schema.const))return`${path} must equal ${stableStringify(schema.const)}`;if(schema.enum!==void 0&&!schema.enum.some(candidate=>stableStringify(candidate)===stableStringify(value)))return`${path} must be one of ${schema.enum.map(entry=>stableStringify(entry)).join("|")}`;if(!valueMatchesSchemaType(value,schema.type))return`${path} must match configured type ${String(schema.type)}`;if(typeof value=="string"){if(schema.min_length!==void 0&&value.length<schema.min_length)return`${path} must contain at least ${schema.min_length} characters`;if(schema.format==="date-time"&&!isRfc3339DateTime(value))return`${path} must be an RFC 3339 date-time`}}function runtimeFieldArraySchemaError(value,schema,path,depth){if(Array.isArray(value)){if(schema.min_items!==void 0&&value.length<schema.min_items)return`${path} must contain at least ${schema.min_items} items`;if(schema.items)for(const[index,entry]of value.entries()){const error=runtimeFieldSchemaError(entry,schema.items,`${path}[${index}]`,depth+1);if(error)return error}}}function runtimeFieldObjectSchemaError(value,schema,path,depth){if(typeof value!="object"||value===null||Array.isArray(value))return;const record=value;for(const key of schema.required??[])if(!Object.hasOwn(record,key))return`${path}.${key} is required`;for(const[key,entry]of Object.entries(record)){const propertySchema=schema.properties?.[key];if(!propertySchema){if(schema.additional_properties===!1)return`${path}.${key} is not allowed`;continue}const error=runtimeFieldSchemaError(entry,propertySchema,`${path}.${key}`,depth+1);if(error)return error}}function runtimeFieldSchemaError(value,schema,path,depth=0){if(depth>MAX_VALUE_SCHEMA_DEPTH)return`${path} value schema exceeds maximum depth`;const directError=runtimeFieldPrimitiveSchemaError(value,schema,path);if(directError)return directError;const arrayError=runtimeFieldArraySchemaError(value,schema,path,depth);if(arrayError)return arrayError;const objectError=runtimeFieldObjectSchemaError(value,schema,path,depth);if(objectError)return objectError;if(!schema.one_of)return;let matches=0;for(const candidate of schema.one_of)if(runtimeFieldSchemaError(value,candidate,path,depth+1)===void 0&&(matches+=1,matches>1))break;return matches===1?void 0:`${path} must match exactly one configured schema variant`}function validateRuntimeFieldValue(definition,value,label){if(!definition.value_schema||value===void 0)return value;const error=runtimeFieldSchemaError(value,definition.value_schema,label);if(error)throw new PmCliError(error,EXIT_CODE.USAGE);return value}function coerceRuntimeContainerValue(definition,rawValue,label,inputKind){const raw=inputKind==="option"&&Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(raw!==void 0)return validateRuntimeFieldValue(definition,parseJsonContainerValue(raw,label,definition.type),label)}function coerceRuntimeFieldValue(definition,rawValue,labelOverride,inputKind="option"){const label=labelOverride??`--${definition.cli_flag}`;if(definition.type==="array"||definition.type==="object")return coerceRuntimeContainerValue(definition,rawValue,label,inputKind);if(definition.repeatable||definition.type==="string_array"){const values=normalizeStringArrayValue(rawValue);return definition.type==="number"?validateRuntimeFieldValue(definition,values.map(value=>parseNumberValue(value,label)),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,values.map(value=>parseBooleanValue(value,label)),label):validateRuntimeFieldValue(definition,values,label)}const scalarRaw=Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(scalarRaw!==void 0)return definition.type==="number"?validateRuntimeFieldValue(definition,parseNumberValue(scalarRaw,label),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,parseBooleanValue(scalarRaw,label),label):validateRuntimeFieldValue(definition,typeof scalarRaw=="string"?scalarRaw:String(scalarRaw),label)}function shouldRequireFieldOnCreate(definition,itemTypeName){return!definition.required&&!definition.required_on_create?!1:definition.required_types.length===0?!0:itemTypeName?definition.required_types.map(value=>value.toLowerCase()).includes(itemTypeName.trim().toLowerCase()):!1}function collectRuntimeCreateFieldValues(options,fieldRegistry,itemTypeName){const values={},missingRequiredFlags=[];for(const definition of fieldRegistry.command_to_fields.get("create")??[]){const rawValue=readRuntimeFieldOptionValue(options,definition);if(rawValue===void 0){shouldRequireFieldOnCreate(definition,itemTypeName)&&missingRequiredFlags.push(`--${definition.cli_flag}`);continue}values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)}return{values,missing_required_flags:[...new Set(missingRequiredFlags)].sort((left,right)=>left.localeCompare(right))}}function collectRuntimeUpdateFieldValues(options,fieldRegistry,commands=["update"]){const values={},definitions=(commands??["update"]).flatMap(command=>fieldRegistry.command_to_fields.get(command)??[]),seen=new Set;for(const definition of definitions){const rawValue=readRuntimeFieldOptionValue(options,definition);rawValue!==void 0&&(seen.has(definition.metadata_key)||(seen.add(definition.metadata_key),values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)))}return values}export{coerceRuntimeFieldValue,collectRuntimeCreateFieldValues,collectRuntimeUpdateFieldValues,commanderOptionAttribute,readRuntimeFieldOptionValue,runtimeFieldCliFlagRoute,runtimeFieldFlagToken,runtimeFieldSdkOptionName};
|
|
2
2
|
//# sourceMappingURL=runtime-field-values.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="10325dfb-128f-5d83-9163-061d8d8b29b6")}catch{}})();import{getSentry}from"./instrument.js";import{PmCliError}from"../shared/errors.js";import{crashReportErrorContext}from"../shared/error-details.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{ExtensionCommandError}from"../../sdk/error-runtime.js";import{EXIT_CODE}from"../shared/constants.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy}from"../telemetry/observability.js";let activeCommandSpan;function setSpanAttribute(span,key,value){if(value===void 0)return;const attributeTarget=span;typeof attributeTarget.setAttribute=="function"&&attributeTarget.setAttribute(key,value)}function setSentryTagIfPresent(Sentry,key,value){typeof value=="string"&&value.trim().length>0&&Sentry.setTag(key,value)}function setSentryCommandFinishTags(Sentry,normalizedOk,metadata){Sentry.setTag("pm.ok",normalizedOk),Sentry.setTag("pm.command_ok",normalizedOk),typeof metadata?.exit_code=="number"&&(Sentry.setTag("pm.exit_code",String(metadata.exit_code)),Sentry.setTag("pm.command_exit_code",String(metadata.exit_code))),setSentryTagIfPresent(Sentry,"pm.error_code",metadata?.error_code),setSentryTagIfPresent(Sentry,"pm.error_category",metadata?.error_category),setSentryTagIfPresent(Sentry,"pm.command_resolution",metadata?.command_resolution),setSentryTagIfPresent(Sentry,"pm.resolution_stage",metadata?.resolution_stage)}function setCommandSpanFinishAttributes(span,normalizedOk,normalizedExitCode,metadata){setSpanAttribute(span,"pm.ok",normalizedOk),setSpanAttribute(span,"pm.command_ok",normalizedOk),setSpanAttribute(span,"pm.exit_code",normalizedExitCode),setSpanAttribute(span,"pm.command_exit_code",normalizedExitCode),setSpanAttribute(span,"pm.error_code",metadata?.error_code),setSpanAttribute(span,"pm.error_category",metadata?.error_category),setSpanAttribute(span,"pm.command_resolution",metadata?.command_resolution),setSpanAttribute(span,"pm.resolution_stage",metadata?.resolution_stage)}function sentrySetCommandContext(command,args,options,metadata){const Sentry=getSentry();if(!Sentry)return;const taxonomy=deriveTelemetryCommandTaxonomy(command);Sentry.setTag("pm.command",command),Sentry.setTag("pm.command_root",taxonomy.command_root),Sentry.setTag("pm.command_family",taxonomy.command_family),setSentryTagIfPresent(Sentry,"pm.version",metadata?.pm_version),setSentryTagIfPresent(Sentry,"pm.source_context_source",metadata?.source_context_source),Sentry.setTag("pm.extension.name",metadata?.extension?.name),Sentry.setTag("pm.extension.version",metadata?.extension?.version),Sentry.setTag("pm.extension.layer",metadata?.extension?.layer),typeof metadata?.source_context=="string"&&metadata.source_context.trim().length>0&&(Sentry.setTag("pm.source_context",metadata.source_context),Sentry.setAttribute("pm.source_context",metadata.source_context));const safeArgs=args.map(()=>"[redacted]");Sentry.setContext("pm.command",{name:command,root:taxonomy.command_root,leaf:taxonomy.command_leaf,family:taxonomy.command_family,args:safeArgs,option_keys:Object.keys(options).sort(),source_context:metadata?.source_context,source_context_source:metadata?.source_context_source}),Sentry.addBreadcrumb({category:"pm.command",message:`pm ${command}`,level:"info",data:{args:safeArgs,command_root:taxonomy.command_root,command_family:taxonomy.command_family,source_context:metadata?.source_context}})}function sentryStartCommandSpan(command){const Sentry=getSentry();if(!Sentry)return;const taxonomy=deriveTelemetryCommandTaxonomy(command);activeCommandSpan=Sentry.startInactiveSpan({op:"pm.command",name:`pm ${command}`,forceTransaction:!0,attributes:{"pm.command":command,"pm.command_root":taxonomy.command_root,"pm.command_family":taxonomy.command_family}})}function sentryDiscardCommandSpan(){activeCommandSpan=void 0}function sentryFinishCommandSpan(ok,error,metadata){if(!activeCommandSpan)return;const normalizedOk=ok?"true":"false",normalizedExitCode=typeof metadata?.exit_code=="number"?String(metadata.exit_code):void 0,Sentry=getSentry();Sentry&&setSentryCommandFinishTags(Sentry,normalizedOk,metadata),setCommandSpanFinishAttributes(activeCommandSpan,normalizedOk,normalizedExitCode,metadata),activeCommandSpan.setStatus(ok?{code:1}:{code:2,message:error??"command_failed"}),activeCommandSpan.end(),activeCommandSpan=void 0}const UNCLASSIFIED_CAPTURED_ERROR_CODE="unclassified_runtime_error";function readCapturedErrorContract(error){const candidate=typeof error=="object"&&error!==null?error:void 0,hasDeclaredExitCode=typeof candidate?.exitCode=="number",exitCode=hasDeclaredExitCode?Math.trunc(candidate?.exitCode):EXIT_CODE.GENERIC_FAILURE;return{error_code:typeof candidate?.code=="string"&&candidate.code.length>0&&hasDeclaredExitCode?candidate?.code:UNCLASSIFIED_CAPTURED_ERROR_CODE,exit_code:exitCode}}function buildCapturedErrorTags(error){const contract=readCapturedErrorContract(error);return{"pm.error_code":contract.error_code,"pm.exit_code":String(contract.exit_code)}}function sentryCaptureCliError(error){if(!shouldCaptureCliError(error))return;const Sentry=getSentry();if(!Sentry)return;const tags=buildCapturedErrorTags(error);if(error instanceof Error){const extras={};"exitCode"in error&&typeof error.exitCode=="number"&&(extras.exit_code=error.exitCode),"context"in error&&typeof error.context=="object"&&(extras.error_context=crashReportErrorContext(error.context)),Sentry.captureException(error,{extra:extras,tags})}else Sentry.captureException(new Error(String(error)),{tags})}function sentryLogCliUsageError(params){const Sentry=getSentry();if(!Sentry)return;const resolvedCommandResolution=params.command_resolution??deriveTelemetryCommandResolution({ok:!1,errorCode:params.error_code,errorCategory:params.error_category}),resolvedResolutionStage=params.resolution_stage??"unknown",payload={"pm.command":params.command,"pm.error_code":params.error_code,"pm.error_category":params.error_category,"pm.exit_code":params.exit_code,"pm.error_message":params.error_message,"pm.command_resolution":resolvedCommandResolution,"pm.resolution_stage":resolvedResolutionStage,"pm.source_context":params.source_context??""},loggerCandidate=Sentry.logger;if(loggerCandidate&&typeof loggerCandidate.warn=="function"){loggerCandidate.warn("pm_cli_usage_error",payload);return}Sentry.captureMessage(`pm_cli_usage_error:${params.error_code}`,{level:"warning",tags:{"pm.command":params.command,"pm.error_code":params.error_code,"pm.error_category":params.error_category,"pm.exit_code":String(params.exit_code),"pm.command_resolution":resolvedCommandResolution,"pm.resolution_stage":resolvedResolutionStage,"pm.source_context":params.source_context??"unknown"},extra:payload})}function shouldCaptureCliError(error){if(error instanceof ExtensionCommandError)return!0;if(error instanceof PmCliError||isPmCliExpectedError(error)||error instanceof Error&&error.name==="AbortError"&&/(?:ctrl\+[cd]|sigint|user[- ]initiated)/i.test(error.message))return!1;if(typeof error=="object"&&error!==null&&"exitCode"in error&&typeof error.exitCode=="number"){if(error instanceof Error&&error.name==="CommandError")return!1;const exitCode=Math.trunc(error.exitCode);return!new Set([EXIT_CODE.SUCCESS,EXIT_CODE.USAGE,EXIT_CODE.NOT_FOUND,EXIT_CODE.CONFLICT]).has(exitCode)}return!0}async function sentryFlush(timeoutMs=3e3){const Sentry=getSentry();if(Sentry)try{await Sentry.flush(timeoutMs)}catch{}}export{UNCLASSIFIED_CAPTURED_ERROR_CODE,sentryCaptureCliError,sentryDiscardCommandSpan,sentryFinishCommandSpan,sentryFlush,sentryLogCliUsageError,sentrySetCommandContext,sentryStartCommandSpan,shouldCaptureCliError};
|
|
2
2
|
//# sourceMappingURL=helpers.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="16379104-dc20-5034-95ab-ebeb63f54952")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}from"../telemetry/policy.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event,originalException){return originalException instanceof Error?isPmCliExpectedError(originalException):!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();if(explicit&&explicit.length>0)return explicit;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";const source=resolveTelemetrySourceAttribution().source_context;return source==="user"?"production":source}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}function sourceContextEnvironment(source){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(source==="automation"||source==="test"||source==="dogfood"||source==="user"))return source==="user"?"production":source}function applySourceContextEnvironment(event){const environment=sourceContextEnvironment(event.tags?.["pm.source_context"]);environment&&(event.environment=environment)}const beforeSend=(event,hint)=>{if(isExpectedCliErrorEvent(event,hint?.originalException)||isKnownNoisyConsoleEvent(event))return null;applySourceContextEnvironment(event),isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(applySourceContextEnvironment(event),event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>{if(log.message=scrubString(log.message),log.attributes){const environment=sourceContextEnvironment(log.attributes["pm.source_context"]);environment&&(log.attributes["sentry.environment"]=environment),log.attributes=scrubEventData(log.attributes)}return log};function applySerializedLogEnvironment(attributes){const environment=sourceContextEnvironment(attributes["pm.source_context"]?.value);environment&&(attributes["sentry.environment"]={type:"string",value:environment})}function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes){applySerializedLogEnvironment(attributes);for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(!client)return;const attribution=resolveTelemetrySourceAttribution();return SentryModule.setTags({"pm.version":release,"pm.source_context":attribution.source_context,"pm.source_context_source":attribution.source_context_source}),SentryModule.setAttribute("pm.source_context",attribution.source_context),client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="93725298-6091-543b-969d-bac38d70be89")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}from"../telemetry/policy.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{crashReportErrorContext,omitEmbeddedPmCliErrorDetails}from"../shared/error-details.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event,originalException){return originalException instanceof Error?isPmCliExpectedError(originalException):!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();if(explicit&&explicit.length>0)return explicit;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";const source=resolveTelemetrySourceAttribution().source_context;return source==="user"?"production":source}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}function sourceContextEnvironment(source){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(source==="automation"||source==="test"||source==="dogfood"||source==="user"))return source==="user"?"production":source}function applySourceContextEnvironment(event){const environment=sourceContextEnvironment(event.tags?.["pm.source_context"]);environment&&(event.environment=environment)}function omitProducerDiagnostics(event,originalException){const ownErrorContext=readOwnErrorContextExtra(event.extra);omitEmbeddedPmCliErrorDetails([event.contexts,event.extra,event.breadcrumbs]),rebuildErrorDataContexts(event.contexts,originalException),ownErrorContext!==void 0&&(event.extra.error_context=crashReportErrorContext(ownErrorContext))}function readOwnErrorContextExtra(extra){if(!(typeof extra!="object"||extra===null||!Object.hasOwn(extra,"error_context")))return extra.error_context}function rebuildErrorDataContexts(contexts,originalException){if(typeof contexts!="object"||contexts===null||typeof originalException!="object"||originalException===null)return;const record=contexts,keys=new Set(errorDataContextKeys(originalException)),rebuilt=safeErrorDataEntry(originalException);for(const[key,entry]of Object.entries(record))(keys.has(key)||typeof entry=="object"&&entry!==null&&Object.hasOwn(entry,"context"))&&(record[key]=rebuilt??{})}function errorDataContextKeys(error){try{return[error.name,error.constructor?.name].filter(candidate=>typeof candidate=="string"&&candidate.length>0)}catch{return[]}}function safeErrorDataEntry(error){try{const entry=crashReportErrorContext(error),context=Object.getOwnPropertyDescriptor(error,"context");return context!==void 0&&"value"in context&&(entry.context=crashReportErrorContext(context.value)),entry}catch{return}}const beforeSend=(event,hint)=>{if(isExpectedCliErrorEvent(event,hint?.originalException)||isKnownNoisyConsoleEvent(event))return null;omitProducerDiagnostics(event,hint?.originalException),applySourceContextEnvironment(event),isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(omitProducerDiagnostics(event),applySourceContextEnvironment(event),event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>{if(log.message=scrubString(log.message),log.attributes){const environment=sourceContextEnvironment(log.attributes["pm.source_context"]);environment&&(log.attributes["sentry.environment"]=environment),log.attributes=scrubEventData(log.attributes)}return log};function applySerializedLogEnvironment(attributes){const environment=sourceContextEnvironment(attributes["pm.source_context"]?.value);environment&&(attributes["sentry.environment"]={type:"string",value:environment})}function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes){applySerializedLogEnvironment(attributes);for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(!client)return;const attribution=resolveTelemetrySourceAttribution();return SentryModule.setTags({"pm.version":release,"pm.source_context":attribution.source_context,"pm.source_context_source":attribution.source_context_source}),SentryModule.setAttribute("pm.source_context",attribution.source_context),client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
|
|
2
2
|
//# sourceMappingURL=instrument.js.map
|
|
@@ -43,6 +43,13 @@ noPager?:boolean;
|
|
|
43
43
|
profile?:boolean;
|
|
44
44
|
/** Invocation-wide mutation author override. */
|
|
45
45
|
author?:string;
|
|
46
|
+
/**
|
|
47
|
+
* CLI-parsed `--expect-hash` tokens (`<item_hash>` or `<id>=<item_hash>`).
|
|
48
|
+
* Only the CLI invocation scope enforces them; direct `run*` SDK calls do not
|
|
49
|
+
* read this field. SDK callers guard writes with `withExpectedItemRevisions`,
|
|
50
|
+
* `PmClient.withExpectedItemRevisions`, or `runAction`/MCP `expectHash`.
|
|
51
|
+
*/
|
|
52
|
+
expectHash?:string[];
|
|
46
53
|
/** Fallback output format used when callers do not provide an override. */
|
|
47
54
|
defaultOutputFormat?:"toon" | "json";
|
|
48
55
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module core/shared/error-details
|
|
3
|
+
*
|
|
4
|
+
* Admits and bounds producer-owned structured diagnostics carried on an
|
|
5
|
+
* expected error (`PmCliErrorContext.details`, GH-1631). The host never
|
|
6
|
+
* interprets these values: it checks that they are plain, well-formed JSON,
|
|
7
|
+
* renders them whole within a declared byte ceiling, and otherwise replaces
|
|
8
|
+
* them with an omission receipt. Telemetry and crash reporting never read
|
|
9
|
+
* them.
|
|
10
|
+
*
|
|
11
|
+
* Every traversal reads own data properties only (accessors are refused, never
|
|
12
|
+
* invoked) and counts the compact JSON encoding as it walks, so a shared or
|
|
13
|
+
* deeply repeated structure is abandoned as soon as it crosses the ceiling
|
|
14
|
+
* instead of being expanded first.
|
|
15
|
+
*/
|
|
16
|
+
import type { PmCliErrorDetails,PmCliErrorDetailsOmission } from "./errors.js";
|
|
17
|
+
export type { PmCliErrorDetailsOmission,PmCliErrorDetailsRejection } from "./errors.js";
|
|
18
|
+
/** Declared ceilings for producer-owned error diagnostics. */
|
|
19
|
+
export declare const PM_CLI_ERROR_DETAILS_LIMITS:Readonly<{
|
|
20
|
+
/** Largest compact UTF-8 JSON encoding rendered; larger diagnostics are omitted whole. */
|
|
21
|
+
max_bytes:4096;
|
|
22
|
+
/** Deepest container nesting accepted below the `details` object itself. */
|
|
23
|
+
max_depth:8;
|
|
24
|
+
}>;
|
|
25
|
+
/** Outcome of admitting one diagnostics value. */
|
|
26
|
+
export type PmCliErrorDetailsAdmission = {
|
|
27
|
+
ok:true;
|
|
28
|
+
details:PmCliErrorDetails;
|
|
29
|
+
byte_length:number;
|
|
30
|
+
} | {
|
|
31
|
+
ok:false;
|
|
32
|
+
omission:PmCliErrorDetailsOmission;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Admit a diagnostics value: a plain object whose leaves are null, booleans,
|
|
36
|
+
* finite numbers and well-formed strings, nested at most
|
|
37
|
+
* {@link PM_CLI_ERROR_DETAILS_LIMITS}.max_depth containers deep and encoding
|
|
38
|
+
* to at most `max_bytes` of compact UTF-8 JSON. Returns a detached copy so
|
|
39
|
+
* later mutation of the producer's object cannot change a raised refusal.
|
|
40
|
+
* Accessor properties are refused without being invoked, and the walk stops
|
|
41
|
+
* at the byte ceiling, so admission cost is bounded by the ceiling.
|
|
42
|
+
*/
|
|
43
|
+
export declare function admitPmCliErrorDetails(value:unknown):PmCliErrorDetailsAdmission;
|
|
44
|
+
/** Check the diagnostics shape and byte ceiling. */
|
|
45
|
+
export declare function isPmCliErrorDetails(value:unknown):value is PmCliErrorDetails;
|
|
46
|
+
/**
|
|
47
|
+
* Project diagnostics for a structured error envelope: render them whole when
|
|
48
|
+
* they are well-formed and fit the byte ceiling, otherwise return only the
|
|
49
|
+
* omission receipt. Partial structures are never emitted.
|
|
50
|
+
*/
|
|
51
|
+
export declare function projectPmCliErrorDetails(value:unknown):{
|
|
52
|
+
details:PmCliErrorDetails;
|
|
53
|
+
} | {
|
|
54
|
+
details_omitted:PmCliErrorDetailsOmission;
|
|
55
|
+
} | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Plain snapshot of a foreign error context, taken once at a host boundary:
|
|
58
|
+
* own enumerable data properties are copied, accessors are never run, a
|
|
59
|
+
* `details` accessor becomes an `unsupported_value` receipt, and a context the
|
|
60
|
+
* host cannot inspect at all (a hostile proxy) becomes an empty object.
|
|
61
|
+
*/
|
|
62
|
+
export declare function snapshotPmCliErrorContext(context:unknown):Record<string,unknown>;
|
|
63
|
+
/**
|
|
64
|
+
* Project the diagnostics of an error context: `details` rendered through
|
|
65
|
+
* {@link projectPmCliErrorDetails}, otherwise a valid host-recorded
|
|
66
|
+
* `details_omitted` receipt. Accessors are reported, never run, and an
|
|
67
|
+
* uninspectable context yields an `unsupported_value` receipt.
|
|
68
|
+
*/
|
|
69
|
+
export declare function projectPmCliErrorContextDetailsSlot(context:unknown):ReturnType<typeof projectPmCliErrorDetails>;
|
|
70
|
+
/**
|
|
71
|
+
* Bound an error context for a transport that forwards the context as-is
|
|
72
|
+
* (MCP): diagnostics are rendered through {@link projectPmCliErrorContextDetailsSlot},
|
|
73
|
+
* every other host field is left untouched.
|
|
74
|
+
*/
|
|
75
|
+
export declare function projectPmCliErrorContextDetails(context:unknown):unknown;
|
|
76
|
+
/**
|
|
77
|
+
* Remove producer diagnostics, and the receipt describing them (its path can
|
|
78
|
+
* echo producer keys), from a context bound for telemetry or crash reporting.
|
|
79
|
+
*/
|
|
80
|
+
export declare function omitPmCliErrorDetails(context:unknown):unknown;
|
|
81
|
+
/**
|
|
82
|
+
* The only form of an error context a crash report may carry: a getter-free
|
|
83
|
+
* snapshot reduced to its top-level primitive fields, without producer
|
|
84
|
+
* diagnostics, their receipt or a serializer. Nested values are dropped,
|
|
85
|
+
* because a custom toJSON or a shared reference could carry diagnostics
|
|
86
|
+
* under any other key.
|
|
87
|
+
*/
|
|
88
|
+
export declare function crashReportErrorContext(context:unknown):Record<string,unknown>;
|
|
89
|
+
/**
|
|
90
|
+
* Discard every embedded error context (`*.context` and `*.error_context`
|
|
91
|
+
* objects) inside a serialized crash-report payload, in place, replacing each
|
|
92
|
+
* with an empty object. These copies were produced by the reporter's own
|
|
93
|
+
* serializer (which runs custom toJSON hooks) and their originals cannot be
|
|
94
|
+
* recovered, so no projection of them can be proven free of diagnostics.
|
|
95
|
+
* Console captures and breadcrumbs carry them at arbitrary positions, so a
|
|
96
|
+
* shallow scrub is not enough.
|
|
97
|
+
*/
|
|
98
|
+
export declare function omitEmbeddedPmCliErrorDetails(payload:unknown):void;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();const PM_CLI_ERROR_DETAILS_LIMITS=Object.freeze({max_bytes:4096,max_depth:8}),MAX_OMISSION_PATH_BYTES=160,DETAILS_REJECTIONS=new Set(["not_plain_object","unsupported_value","non_finite_number","malformed_unicode","reserved_key","depth_limit","byte_limit","diagnostic_budget"]),LONE_SURROGATE=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,RESERVED_KEYS=new Set(["__proto__"]);class DetailsShapeError extends Error{reason;path;constructor(reason,path){super(reason),this.reason=reason,this.path=path}}function isPlainObject(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function childPath(path,key){return/^[A-Za-z_$][\w$]*$/u.test(key)?`${path}.${key}`:`${path}[${JSON.stringify(key)}]`}function boundPath(path){if(Buffer.byteLength(path,"utf8")<=MAX_OMISSION_PATH_BYTES)return path;let bounded="",bytes=Buffer.byteLength("\u2026","utf8");for(const character of path){if(bytes+=Buffer.byteLength(character,"utf8"),bytes>MAX_OMISSION_PATH_BYTES)break;bounded+=character}return`${bounded}\u2026`}function charge(budget,bytes,path){if(budget.bytes+=bytes,!(budget.bytes<=PM_CLI_ERROR_DETAILS_LIMITS.max_bytes))throw new DetailsShapeError("byte_limit",path)}function assertCanFit(budget,minimumBytes,path){if(budget.bytes+minimumBytes>PM_CLI_ERROR_DETAILS_LIMITS.max_bytes)throw new DetailsShapeError("byte_limit",path)}function readOwnDataValue(container,key,path){const descriptor=Object.getOwnPropertyDescriptor(container,key);if(descriptor===void 0||!("value"in descriptor))throw new DetailsShapeError("unsupported_value",path);return descriptor.value}function copyDetailLeaf(value,path,budget){if(typeof value=="number"&&!Number.isFinite(value))throw new DetailsShapeError("non_finite_number",path);if(typeof value=="string"&&(assertCanFit(budget,value.length+2,path),LONE_SURROGATE.test(value)))throw new DetailsShapeError("malformed_unicode",path);if(value!==null&&!["boolean","number","string"].includes(typeof value))throw new DetailsShapeError("unsupported_value",path);return charge(budget,Buffer.byteLength(JSON.stringify(value),"utf8"),path),value}function copyDetailValue(value,path,depth,budget){if(typeof value!="object"||value===null)return copyDetailLeaf(value,path,budget);if(depth>=PM_CLI_ERROR_DETAILS_LIMITS.max_depth)throw new DetailsShapeError("depth_limit",path);if(Array.isArray(value)){const length=readOwnDataValue(value,"length",path);if(typeof length!="number"||!Number.isSafeInteger(length)||length<0)throw new DetailsShapeError("unsupported_value",path);charge(budget,length>0?length+1:2,path);const copy=[];for(let index=0;index<length;index+=1){const entryPath=`${path}[${index}]`;copy.push(copyDetailValue(readOwnDataValue(value,String(index),entryPath),entryPath,depth+1,budget))}return copy}if(!isPlainObject(value))throw new DetailsShapeError("unsupported_value",path);return copyDetailObject(value,path,depth+1,budget)}function copyDetailObject(value,path,depth,budget){const keys=Object.keys(value);charge(budget,keys.length>0?keys.length+1:2,path);const copy={};for(const key of keys){assertCanFit(budget,key.length+3,path);const keyPath=childPath(path,key);if(RESERVED_KEYS.has(key))throw new DetailsShapeError("reserved_key",keyPath);if(LONE_SURROGATE.test(key))throw new DetailsShapeError("malformed_unicode",keyPath);charge(budget,Buffer.byteLength(JSON.stringify(key),"utf8")+1,keyPath),copy[key]=copyDetailValue(readOwnDataValue(value,key,keyPath),keyPath,depth,budget)}return copy}function classifyAdmissionFault(error){try{if(error instanceof DetailsShapeError)return error}catch{}return new DetailsShapeError("unsupported_value","details")}function admitPmCliErrorDetails(value){const byteLimit=PM_CLI_ERROR_DETAILS_LIMITS.max_bytes,budget={bytes:0};try{if(!isPlainObject(value))throw new DetailsShapeError("not_plain_object","details");return{ok:!0,details:copyDetailObject(value,"details",0,budget),byte_length:budget.bytes}}catch(error){const refusal=classifyAdmissionFault(error);return{ok:!1,omission:refusal.reason==="byte_limit"?{reason:"byte_limit",byte_limit:byteLimit}:{reason:refusal.reason,path:boundPath(refusal.path),byte_limit:byteLimit}}}}function isPmCliErrorDetails(value){return admitPmCliErrorDetails(value).ok}function projectPmCliErrorDetails(value){if(value===void 0)return;const admission=admitPmCliErrorDetails(value);return admission.ok?{details:admission.details}:{details_omitted:admission.omission}}function unsupportedDetailsReceipt(){return{reason:"unsupported_value",path:"details",byte_limit:PM_CLI_ERROR_DETAILS_LIMITS.max_bytes}}function ownDataValue(container,key){const descriptor=Object.getOwnPropertyDescriptor(container,key);return descriptor!==void 0&&"value"in descriptor?descriptor.value:void 0}function readRecordedOmission(value){if(!isPlainObject(value))return;const reason=ownDataValue(value,"reason");if(typeof reason!="string"||!DETAILS_REJECTIONS.has(reason))return;const recordedPath=ownDataValue(value,"path"),path=typeof recordedPath=="string"?boundPath(recordedPath):void 0;return{reason,...path===void 0?{}:{path},byte_limit:PM_CLI_ERROR_DETAILS_LIMITS.max_bytes}}function snapshotPmCliErrorContext(context){const snapshot={};try{if(typeof context!="object"||context===null||Array.isArray(context))return snapshot;for(const[key,descriptor]of Object.entries(Object.getOwnPropertyDescriptors(context)))descriptor.enumerable&&("value"in descriptor?Object.defineProperty(snapshot,key,{value:descriptor.value,enumerable:!0,writable:!0,configurable:!0}):key==="details"&&(snapshot.details_omitted=unsupportedDetailsReceipt()));return snapshot}catch{return{}}}function projectPmCliErrorContextDetailsSlot(context){if(!(typeof context!="object"||context===null))try{const descriptor=Object.getOwnPropertyDescriptor(context,"details");if(descriptor!==void 0&&!("value"in descriptor))return{details_omitted:unsupportedDetailsReceipt()};if(descriptor!==void 0&&descriptor.value!==void 0)return projectPmCliErrorDetails(descriptor.value);const recorded=Object.getOwnPropertyDescriptor(context,"details_omitted"),omission=recorded!==void 0&&"value"in recorded?readRecordedOmission(recorded.value):void 0;return omission===void 0?void 0:{details_omitted:omission}}catch{return{details_omitted:unsupportedDetailsReceipt()}}}const DIAGNOSTIC_KEYS=new Set(["details","details_omitted"]);function contextWithoutDiagnostics(context){const rest={};for(const key of Object.keys(context)){if(DIAGNOSTIC_KEYS.has(key)||key==="toJSON")continue;const descriptor=Object.getOwnPropertyDescriptor(context,key);descriptor!==void 0&&"value"in descriptor&&Object.defineProperty(rest,key,{value:descriptor.value,enumerable:!0,writable:!0,configurable:!0})}return rest}function projectPmCliErrorContextDetails(context){if(typeof context!="object"||context===null)return context;try{return Array.isArray(context)?context:{...contextWithoutDiagnostics(context),...projectPmCliErrorContextDetailsSlot(context)}}catch{return{details_omitted:unsupportedDetailsReceipt()}}}function omitPmCliErrorDetails(context){if(typeof context!="object"||context===null)return context;try{return Array.isArray(context)?context:contextWithoutDiagnostics(context)}catch{return{}}}function crashReportErrorContext(context){const safe={};for(const[key,value]of Object.entries(snapshotPmCliErrorContext(context)))DIAGNOSTIC_KEYS.has(key)||key==="toJSON"||(value===null||typeof value=="string"||typeof value=="number"||typeof value=="boolean")&&Object.defineProperty(safe,key,{value,enumerable:!0,writable:!0,configurable:!0});return safe}const MAX_EMBEDDED_CONTEXT_DEPTH=12,EMBEDDED_CONTEXT_KEYS=new Set(["context","error_context"]),SERIALIZED_ARGUMENT_KEYS=new Set(["arguments"]);function omitEmbeddedPmCliErrorDetails(payload){const seen=new WeakSet,visit=(value,depth)=>{if(typeof value!="object"||value===null||depth>MAX_EMBEDDED_CONTEXT_DEPTH||seen.has(value))return;seen.add(value);const record=value;let keys;try{keys=Object.keys(record)}catch{return}for(const key of keys){const descriptor=Object.getOwnPropertyDescriptor(record,key);if(descriptor===void 0||!("value"in descriptor))continue;const entry=descriptor.value,scrubbed=EMBEDDED_CONTEXT_KEYS.has(key)?{}:SERIALIZED_ARGUMENT_KEYS.has(key)?[]:entry;scrubbed!==entry&&(record[key]=scrubbed),visit(scrubbed,depth+1)}};visit(payload,0)}export{PM_CLI_ERROR_DETAILS_LIMITS,admitPmCliErrorDetails,crashReportErrorContext,isPmCliErrorDetails,omitEmbeddedPmCliErrorDetails,omitPmCliErrorDetails,projectPmCliErrorContextDetails,projectPmCliErrorContextDetailsSlot,projectPmCliErrorDetails,snapshotPmCliErrorContext};
|
|
2
|
+
//# sourceMappingURL=error-details.js.map
|