@unbrained/pm-cli 2026.11.19 → 2026.11.21
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/.agents/skills/pm-sdk/SKILL.md +1 -1
- package/.agents/skills/pm-test-audit/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +1 -1
- package/CONTRIBUTING.md +2 -1
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +21 -0
- package/dist/cli-bundle/chunks/{chunk-AGPFANRX.js → chunk-5647LU3A.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-CR5GC3VO.js → chunk-6QLEXRUG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XPBPGDFW.js → chunk-AHQB7W2H.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4FNMPZ7Y.js → chunk-BKSVHOWI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GQCMICAL.js → chunk-CASX6SFI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NMVPQTZI.js → chunk-CIKGG34F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-IQKCRLQP.js → chunk-D6ILFXZY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AOV5HG3Y.js → chunk-IUIOTAF6.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-PRVT7ITI.js → chunk-JVGRFU5H.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-IUTN67EB.js → chunk-KVBIMFUG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-AMHD7WIV.js → chunk-NCFCBKIP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-M76BEWTT.js → chunk-NT5AKFE5.js} +30 -30
- package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-2UTJ5QIE.js → chunk-RMIRNYRG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CNMGGAZO.js → chunk-RULHZRFN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O7IFAJ76.js → chunk-S6HB3WL2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CTOE26W4.js → chunk-SA4BNP3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Z5LHCEXG.js → chunk-SRVTCYAU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-N2CPCFSN.js → chunk-WELSVDPU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-P4A5RFLX.js → chunk-XHJ3H5PL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q32Q3LRH.js → chunk-XWHJIRNV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +8 -0
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-YJKGOYBR.js → item-revision-R5SZPJZ5.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-DDYJW5B4.js → mutation-actor-3TG636XG.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-JLMQJ2M5.js → mutation-admission-LICSDNNO.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-4AXLLXK7.js → register-list-query-SPGPS3OS.js} +10 -10
- package/dist/cli-bundle/chunks/{register-mutation-FJIXGGF4.js → register-mutation-WWVECKFQ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-W4E2KEMA.js → register-operations-L6HFJNWD.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-RYRIBNSN.js → register-setup-K7UFG5TD.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-XGWW3T64.js → stage-57KH3KAC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2XULTI5B.js → chunk-532WZV65.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZFUZ4YYN.js → chunk-7A4QWNZX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7RF2YPZ5.js → chunk-CWWKRI5P.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ICEHI4SN.js → chunk-HGFNL5XI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +13 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OF4UM5B6.js → chunk-J63D6QST.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OAIAZHRG.js → chunk-JMQJBZQ5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4S7I342K.js → chunk-LNHUE4VV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MTBC32ZR.js → chunk-MKM5NKD7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EZXLY6S4.js → chunk-NP72ZDXE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +102 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OPY43DNJ.js → chunk-QGKLRXP7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-77CDWGBW.js → chunk-QSJW6NSQ.js} +53 -53
- package/dist/cli-bundle/focused-chunks/{chunk-7Z2NYAK4.js → chunk-RPE6IX26.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-D72EQN7Z.js → chunk-UOC6257J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FPPYE6CY.js → chunk-URJ2E6AS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-N64BUB63.js → chunk-XCJSHNXK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GAOWBALE.js → chunk-XQQSSKJI.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-XS2YZCT5.js → chunk-YOAYY3HE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-32HFGFYG.js → item-revision-3V3UIP5X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-C4VW3SHX.js → item-transaction-HLBW7B3J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-2SVBO324.js → mutation-actor-62HKR5IO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-PNK6ORZR.js → mutation-admission-X4PF2SG3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-LVAGKCEE.js → stage-O7T7CXBB.js} +2 -2
- package/dist/cli-bundle/main.js +25 -25
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- 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 +58 -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/extensions/index.d.ts +2 -0
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.d.ts +3 -1
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/read.d.ts +11 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/stream-summary.d.ts +129 -0
- package/dist/core/history/stream-summary.js +3 -0
- package/dist/core/shared/errors.d.ts +8 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/text-normalization.d.ts +9 -0
- package/dist/core/shared/text-normalization.js +1 -1
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workspace-position.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/merge/index.d.ts +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.d.ts +20 -6
- package/dist/sdk/merge/install.js +3 -3
- package/dist/sdk/merge/worktree-config.js +2 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.d.ts +67 -5
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/context.d.ts +13 -3
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query.d.ts +1 -1
- package/dist/sdk/query.js +1 -1
- package/dist/sdk/read-output/continuation.d.ts +9 -3
- package/dist/sdk/read-output/continuation.js +1 -1
- package/dist/sdk/read-output-budget.d.ts +44 -3
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/docs/COMMANDS.md +56 -2
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/MUTATION_INTEGRITY.md +3 -1
- package/docs/PERFORMANCE.md +17 -2
- package/docs/README.md +6 -4
- package/docs/READ_OUTPUT_CONTRACTS.md +16 -1
- package/docs/SDK.md +25 -1
- package/docs/TESTING.md +8 -697
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
- package/marketplace.json +1 -1
- package/package.json +6 -2
- 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-5OFMWP3Q.js +0 -3
- package/dist/cli-bundle/chunks/chunk-723PMYNX.js +0 -125
- package/dist/cli-bundle/chunks/chunk-7UUPLMCU.js +0 -115
- package/dist/cli-bundle/chunks/chunk-H64BNM4A.js +0 -8
- package/dist/cli-bundle/chunks/chunk-OESI2ETD.js +0 -20
- package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-K4YZ7GWR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5JVB42Z7.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-7A4VIRIU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-A2CLYPDA.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HO2YUD4P.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-P4TG4VMJ.js +0 -12
- package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
- package/docs/QUALITY_EVIDENCE.md +0 -130
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
- package/docs/performance/cli-transport-overhead.md +0 -51
- package/docs/performance/runner-qualification.md +0 -36
- package/docs/performance/sdk-entrypoint-import-costs.md +0 -32
|
@@ -82,6 +82,8 @@ export declare function getActiveExtensionHooks():ExtensionHookRegistry|null;
|
|
|
82
82
|
export declare function runActiveBeforeMutationHooks(input:BeforeMutationHookInput):Promise<void>;
|
|
83
83
|
/** Implements run active on read hooks for the public runtime surface of this module. */
|
|
84
84
|
export declare function runActiveOnReadHooks(context:OnReadHookContext):Promise<string[]>;
|
|
85
|
+
/** Synchronous predicate: true only when at least one onWrite hook is registered, so a bulk writer can keep per-path ordering for hooks that may touch later paths. */
|
|
86
|
+
export declare function hasActiveOnWriteHooks():boolean;
|
|
85
87
|
/** Synchronous fast-path predicate: true only when at least one onRead hook is registered. Bulk readers (e.g. the metadata cache scanning hundreds of files) use this to skip per-file `await runActiveOnReadHooks(...)` calls entirely when no extension observes reads, avoiding hundreds of needless microtasks. */
|
|
86
88
|
export declare function hasActiveOnReadHooks():boolean;
|
|
87
89
|
/** Implements run active on index hooks for the public runtime surface of this module. */
|
|
@@ -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]="1ee579e0-2d07-5519-b071-bac39d3ec594")}catch{}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{ownedTransactionCompensation}from"../store/item-mutation-precondition.js";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult,activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);for(;;){if(existsSync(path.join(cursor,".git")))return cursor;const parent=path.dirname(cursor);if(parent===cursor)return;cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate),repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot)return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}};const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot)),contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=null,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null,state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState(),context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function isActiveCommandUnextended(command){const state=runtimeState()??{commandContext:activeCommandContext,hooks:activeExtensionHooks,commands:activeExtensionCommands,parsers:activeExtensionParsers,preflight:activeExtensionPreflight,services:activeExtensionServices,renderers:activeExtensionRenderers,registrations:activeExtensionRegistrations};return state.commandContext?.command!==command||[state.hooks,state.preflight,state.services,state.renderers].some(registry=>Object.values(registry??{}).some(entries=>entries.length>0))||[state.commands,state.parsers].some(registry=>Object.values(registry??{}).some(entries=>entries.some(entry=>entry.command===command)))?!1:!Object.entries(state.registrations??{}).some(([key,entries])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(key)&&entries.length>0)}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item)return;const state=runtimeState();state?state.affectedItems.push(item):activeAfterCommandAffectedItems.push(item)}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id)return{};const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields))return snapshot;const source=metadata;for(const field of changedFields){if(typeof field!="string")continue;const actualField=field.startsWith("unset:")?field.slice(6):field;actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)||Object.hasOwn(source,actualField)&&source[actualField]!==void 0&&(snapshot[actualField]=source[actualField])}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState(),affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0)return;const affected=affectedItems;return state?state.affectedItems=[]:activeAfterCommandAffectedItems=[],affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=void 0,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=void 0,activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnWriteHooks(hooks,context):[]}const previewMutationGuards=new AsyncLocalStorage;function runWithPreviewMutationGuards(hooks,run){return!hooks||(hooks.beforeMutation?.length??0)===0?run():previewMutationGuards.run(hooks,run)}function getActiveExtensionHooks(){const state=runtimeState();return state?state.hooks:activeExtensionHooks}async function runActiveBeforeMutationHooks(input){const preview=previewMutationGuards.getStore(),hooks=preview??getActiveExtensionHooks();if(!hooks)return;const{resolveMutationActor}=await import("./mutation-actor.js"),isDryRun=preview!==void 0||input.dry_run===!0,compensation=isDryRun?void 0:ownedTransactionCompensation(input.pm_root,[input.before?.metadata.id,input.after?.metadata.id],input.operation),overrides=await runBeforeMutationHooks(hooks,{pm_root:input.pm_root,operation:input.operation,before:input.before,after:input.after,changed_fields:input.changed_fields,sdk:input.sdk,actor:resolveMutationActor(input.author),dry_run:isDryRun,...compensation===void 0?{}:{compensation:{transaction_id:compensation.transaction_id,step_id:compensation.step_id}}});compensation?.overrides.push(...overrides.map(override=>({source:"mutation_guard",...override})))}async function runActiveOnReadHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnReadHooks(hooks,context):[]}function hasActiveOnReadHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnIndexHooks(hooks,context):[]}function runActiveCommandOverride(result){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands,commandContext=state?state.commandContext:activeCommandContext;return!commands||!commandContext?{overridden:!1,result,warnings:[]}:runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands;return commands?runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{handled:!1,result:null,warnings:[]}}async function runActiveParserOverride(context){const state=runtimeState(),parsers=state?state.parsers:activeExtensionParsers;return parsers?runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}async function runActivePreflightOverride(context){const state=runtimeState(),preflight=state?state.preflight:activeExtensionPreflight;return preflight?runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}function runActiveRendererOverride(format,result){const state=runtimeState(),renderers=state?state.renderers:activeExtensionRenderers,commandContext=state?state.commandContext:activeCommandContext;return renderers?runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result}):{overridden:!1,rendered:null,warnings:[]}}function buildServiceContext(service,payload){const state=runtimeState(),commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverride(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}function runActiveServiceOverrideSync(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverrideSync(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionHooks,getActiveExtensionRegistrations,hasActiveOnReadHooks,isActiveCommandUnextended,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,runWithPreviewMutationGuards,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
|
|
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]="67666bab-2e73-549c-bf95-ba505143a9b5")}catch{}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{ownedTransactionCompensation}from"../store/item-mutation-precondition.js";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult,activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);for(;;){if(existsSync(path.join(cursor,".git")))return cursor;const parent=path.dirname(cursor);if(parent===cursor)return;cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate),repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot)return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}};const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot)),contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=null,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null,state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState(),context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function isActiveCommandUnextended(command){const state=runtimeState()??{commandContext:activeCommandContext,hooks:activeExtensionHooks,commands:activeExtensionCommands,parsers:activeExtensionParsers,preflight:activeExtensionPreflight,services:activeExtensionServices,renderers:activeExtensionRenderers,registrations:activeExtensionRegistrations};return state.commandContext?.command!==command||[state.hooks,state.preflight,state.services,state.renderers].some(registry=>Object.values(registry??{}).some(entries=>entries.length>0))||[state.commands,state.parsers].some(registry=>Object.values(registry??{}).some(entries=>entries.some(entry=>entry.command===command)))?!1:!Object.entries(state.registrations??{}).some(([key,entries])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(key)&&entries.length>0)}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item)return;const state=runtimeState();state?state.affectedItems.push(item):activeAfterCommandAffectedItems.push(item)}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id)return{};const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields))return snapshot;const source=metadata;for(const field of changedFields){if(typeof field!="string")continue;const actualField=field.startsWith("unset:")?field.slice(6):field;actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)||Object.hasOwn(source,actualField)&&source[actualField]!==void 0&&(snapshot[actualField]=source[actualField])}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState(),affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0)return;const affected=affectedItems;return state?state.affectedItems=[]:activeAfterCommandAffectedItems=[],affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=void 0,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=void 0,activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnWriteHooks(hooks,context):[]}const previewMutationGuards=new AsyncLocalStorage;function runWithPreviewMutationGuards(hooks,run){return!hooks||(hooks.beforeMutation?.length??0)===0?run():previewMutationGuards.run(hooks,run)}function getActiveExtensionHooks(){const state=runtimeState();return state?state.hooks:activeExtensionHooks}async function runActiveBeforeMutationHooks(input){const preview=previewMutationGuards.getStore(),hooks=preview??getActiveExtensionHooks();if(!hooks)return;const{resolveMutationActor}=await import("./mutation-actor.js"),isDryRun=preview!==void 0||input.dry_run===!0,compensation=isDryRun?void 0:ownedTransactionCompensation(input.pm_root,[input.before?.metadata.id,input.after?.metadata.id],input.operation),overrides=await runBeforeMutationHooks(hooks,{pm_root:input.pm_root,operation:input.operation,before:input.before,after:input.after,changed_fields:input.changed_fields,sdk:input.sdk,actor:resolveMutationActor(input.author),dry_run:isDryRun,...compensation===void 0?{}:{compensation:{transaction_id:compensation.transaction_id,step_id:compensation.step_id}}});compensation?.overrides.push(...overrides.map(override=>({source:"mutation_guard",...override})))}async function runActiveOnReadHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnReadHooks(hooks,context):[]}function hasActiveOnWriteHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onWrite?.length??0)>0}function hasActiveOnReadHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnIndexHooks(hooks,context):[]}function runActiveCommandOverride(result){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands,commandContext=state?state.commandContext:activeCommandContext;return!commands||!commandContext?{overridden:!1,result,warnings:[]}:runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands;return commands?runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{handled:!1,result:null,warnings:[]}}async function runActiveParserOverride(context){const state=runtimeState(),parsers=state?state.parsers:activeExtensionParsers;return parsers?runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}async function runActivePreflightOverride(context){const state=runtimeState(),preflight=state?state.preflight:activeExtensionPreflight;return preflight?runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}function runActiveRendererOverride(format,result){const state=runtimeState(),renderers=state?state.renderers:activeExtensionRenderers,commandContext=state?state.commandContext:activeCommandContext;return renderers?runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result}):{overridden:!1,rendered:null,warnings:[]}}function buildServiceContext(service,payload){const state=runtimeState(),commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverride(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}function runActiveServiceOverrideSync(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverrideSync(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionHooks,getActiveExtensionRegistrations,hasActiveOnReadHooks,hasActiveOnWriteHooks,isActiveCommandUnextended,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,runWithPreviewMutationGuards,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
|
|
2
2
|
//# sourceMappingURL=index.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]="fa27dff5-0270-505f-bd5f-bc1eb0fe5ad8")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=path.isAbsolute(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(path.isAbsolute(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
|
|
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]="30379998-be47-5176-bfd4-a02bca99bd16")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}function isAbsolutePattern(text,platform=process.platform){return text.startsWith("/")||platform==="win32"&&/^[A-Za-z]:\//u.test(text)}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=isAbsolutePattern(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(isAbsolutePattern(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,isAbsolutePattern,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
|
|
2
2
|
//# sourceMappingURL=file-glob.js.map
|
|
@@ -40,8 +40,10 @@ export declare function transactionPreviewNonRegularFileError(relativePath?:stri
|
|
|
40
40
|
* Parent directories are created by default. Background consumers can disable
|
|
41
41
|
* that behavior to respect removal of their storage while work is in flight;
|
|
42
42
|
* missing parents then produce the native filesystem error without recreation.
|
|
43
|
+
* `mode` creates the temporary file, and so the result, with those permission
|
|
44
|
+
* bits (subject to the umask), for derived state that must stay private.
|
|
43
45
|
*/
|
|
44
|
-
export declare function writeFileAtomic(targetPath:string,contents:string,options?:{createParentDirectories?:boolean;}):Promise<void>;
|
|
46
|
+
export declare function writeFileAtomic(targetPath:string,contents:string,options?:{createParentDirectories?:boolean;mode?:number;}):Promise<void>;
|
|
45
47
|
/**
|
|
46
48
|
* Append a single newline-terminated line to a file, opened with `O_APPEND`.
|
|
47
49
|
*
|
package/dist/core/fs/fs-utils.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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]="af07b34f-9e45-561f-aa8c-2415ee4a46b9")}catch{}})();import*as fs from"node:fs/promises";import{constants}from"node:fs";import path from"node:path";import crypto from"node:crypto";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const WINDOWS_RENAME_RETRY_DELAYS_MS=[10,25,50,100];async function ensureDir(dirPath){await fs.mkdir(dirPath,{recursive:!0})}async function pathExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isFileAbsentError(error){return isFileMissingError(error)||isErrno(error,"ENOTDIR")}function isFileMissingError(error){return isErrno(error,"ENOENT")}async function readFileIfExists(targetPath){try{return await fs.readFile(targetPath,"utf8")}catch(error){if(isFileAbsentError(error))return null;throw error}}async function readRegularFile(targetPath,rejectionError){const handle=await fs.open(targetPath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{if(!(await handle.stat()).isFile())throw rejectionError;return await handle.readFile("utf8")}finally{await handle.close()}}function transactionPreviewNonRegularFileError(relativePath){const relative=relativePath?.replaceAll(path.sep,"/"),contained=relative!==void 0&&!path.posix.isAbsolute(relative)&&!path.win32.isAbsolute(relative)&&!relative.split("/").includes(".."),first=contained?relative.split("/")[0]:void 0,areas={"settings.json":"settings",runtime:"runtime",schema:"schema",history:"history",transactions:"transactions"},area=first===void 0?"tracker_storage":Object.hasOwn(areas,first)?areas[first]:"tracker_storage",safe=contained&&relative.length>0&&relative.length<=160&&relative.split("/").every(part=>part!=="."&&/^[a-zA-Z0-9_.-]+$/u.test(part)),location=safe?relative:`${area} (entry name redacted)`;return new PmCliError(`Transaction preview requires regular files and directories. Inspect ${location} relative to the selected tracker root.`,EXIT_CODE.USAGE,{code:"transaction_preview_non_regular_file",preview_storage:{storage_area:area,...safe?{relative_entry:relative}:{},entry_redacted:!safe},required:"regular files and directories within the configured tracker storage",why:"Preview does not follow linked entries or read special files.",nextSteps:[`Inspect ${location} within the selected tracker for links, directories used as files, or special files; do not follow link targets.`,"Restore the intended regular files and directories, then retry the original dry-run command."]})}async function unlinkQuietly(filePath){try{await fs.unlink(filePath)}catch{}}async function writeFileAtomic(targetPath,contents,options={}){const dirPath=path.dirname(targetPath);options.createParentDirectories!==!1&&await ensureDir(dirPath);const tempPath=path.join(dirPath,`.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`);try{await fs.writeFile(tempPath,contents,options.mode===void 0?"utf8":{encoding:"utf8",mode:options.mode})}catch(error){throw await unlinkQuietly(tempPath),error}try{await fs.rename(tempPath,targetPath)}catch(error){if(process.platform==="win32"&&(isErrno(error,"EPERM")||isErrno(error,"EBUSY"))){let lastError=error;for(const delayMs of WINDOWS_RENAME_RETRY_DELAYS_MS){await new Promise(resolve=>setTimeout(resolve,delayMs));try{await fs.rename(tempPath,targetPath);return}catch(retryError){if(lastError=retryError,!isErrno(retryError,"EPERM")&&!isErrno(retryError,"EBUSY"))break}}throw await unlinkQuietly(tempPath),lastError}if(isErrno(error,"EXDEV")){try{await fs.copyFile(tempPath,targetPath)}finally{await unlinkQuietly(tempPath)}return}throw await unlinkQuietly(tempPath),error}}async function appendLineAtomic(targetPath,line){const dirPath=path.dirname(targetPath);await ensureDir(dirPath);const handle=await fs.open(targetPath,"a");try{await handle.writeFile(`${line}
|
|
2
2
|
`,"utf8")}finally{await handle.close()}}async function removeFileIfExists(targetPath){try{await fs.unlink(targetPath)}catch(error){if(!isFileAbsentError(error))throw error}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}export{appendLineAtomic,ensureDir,isFileAbsentError,isFileMissingError,pathExists,readFileIfExists,readRegularFile,removeFileIfExists,transactionPreviewNonRegularFileError,writeFileAtomic};
|
|
3
3
|
//# sourceMappingURL=fs-utils.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]="2e67dcb3-0d34-5884-8b79-5e98458f8c57")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{hasActiveOnWriteHooks,runActiveOnWriteHooks}from"../extensions/index.js";import{ensureDir,pathExists}from"../fs/fs-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{getHistoryPath}from"../store/paths.js";const EXISTENCE_PROBE_CONCURRENCY=64;function toSortedUniqueItemIds(itemIds){return[...new Set(itemIds.filter(value=>value.trim().length>0))].sort((left,right)=>left.localeCompare(right))}function strictMissingStreamError(itemId,commandLabel){return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,EXIT_CODE.NOT_FOUND)}async function createStream(historyPath,commandLabel){return await ensureDir(path.dirname(historyPath)),await(await fs.open(historyPath,"a")).close(),runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${commandLabel}:history:auto_create`})}async function probeMissingStreams(pmRoot,ids,stopAtFirstMissing){const missing=[];for(let start=0;start<ids.length;start+=EXISTENCE_PROBE_CONCURRENCY){const chunk=ids.slice(start,start+EXISTENCE_PROBE_CONCURRENCY),present=await Promise.all(chunk.map(itemId=>{let historyPath;try{historyPath=getHistoryPath(pmRoot,itemId)}catch{return!1}return pathExists(historyPath)}));if(chunk.forEach((itemId,index)=>{present[index]||missing.push(itemId)}),stopAtFirstMissing&&missing.length>0)break}return missing}async function enforceHistoryStreamPolicyForItem(params){return enforceHistoryStreamPolicyForItems({pmRoot:params.pmRoot,settings:params.settings,itemIds:[params.itemId],commandLabel:params.commandLabel})}async function enforceHistoryStreamPolicyForItems(params){const ids=toSortedUniqueItemIds(params.itemIds),autoCreated=[],warnings=[],sequential=hasActiveOnWriteHooks(),strict=params.settings.history.missing_stream==="strict_error",candidates=sequential?ids:await probeMissingStreams(params.pmRoot,ids,strict);for(const itemId of candidates.length===0?[]:ids){const historyPath=getHistoryPath(params.pmRoot,itemId);if(!await pathExists(historyPath)){if(strict)throw strictMissingStreamError(itemId,params.commandLabel);warnings.push(...await createStream(historyPath,params.commandLabel)),warnings.push(`history_stream_auto_created:${itemId}`),autoCreated.push(itemId)}}return{auto_created_ids:autoCreated,warnings}}export{enforceHistoryStreamPolicyForItem,enforceHistoryStreamPolicyForItems};
|
|
2
2
|
//# sourceMappingURL=history-stream-policy.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type{HistoryEntry}from "../../types/index.js";
|
|
1
|
+
import type{BigIntStats}from "node:fs";import type{HistoryEntry}from "../../types/index.js";
|
|
2
2
|
/** Exact bytes and decoded entries from one read, suitable for optimistic concurrency checks. */
|
|
3
3
|
export interface HistoryStreamSnapshot{
|
|
4
4
|
/** Null means the stream did not exist; an empty string means it existed without entries. */
|
|
@@ -9,5 +9,15 @@ raw_bytes:Uint8Array|null;
|
|
|
9
9
|
entries:HistoryEntry[];}
|
|
10
10
|
/** Read one history stream once so replay input and the concurrency snapshot cannot disagree. */
|
|
11
11
|
export declare function readHistorySnapshot(historyPath:string,itemId:string):Promise<HistoryStreamSnapshot>;
|
|
12
|
+
/** A snapshot plus the identity of the open file that supplied its bytes. */
|
|
13
|
+
export interface IdentifiedHistoryStreamSnapshot extends HistoryStreamSnapshot{
|
|
14
|
+
/** Stat of the open handle the bytes were read from; null when the stream was absent. */
|
|
15
|
+
source:BigIntStats|null;}
|
|
16
|
+
/**
|
|
17
|
+
* Read one history stream through a single open handle and report that
|
|
18
|
+
* handle's stat, so derived state can be bound to the exact file revision
|
|
19
|
+
* that supplied the bytes, whatever happens to the path meanwhile.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readIdentifiedHistorySnapshot(historyPath:string,itemId:string):Promise<IdentifiedHistoryStreamSnapshot>;
|
|
12
22
|
/** Read and validate one item's JSONL history stream without mutating it. */
|
|
13
23
|
export declare function readHistoryEntries(historyPath:string,itemId:string):Promise<HistoryEntry[]>;
|
|
@@ -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]="72d9ef42-50f7-5a57-8210-f4e514197598")}catch{}})();import fs from"node:fs/promises";import{isFileAbsentError}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const rawBytes=await fs.readFile(historyPath).catch(error=>{if(isFileAbsentError(error))return null;throw error});return decodeHistorySnapshot(historyPath,itemId,rawBytes)}async function readIdentifiedHistorySnapshot(historyPath,itemId){const handle=await fs.open(historyPath,"r").catch(error=>{if(isFileAbsentError(error))return null;throw error});if(handle===null)return{...await decodeHistorySnapshot(historyPath,itemId,null),source:null};try{const source=await handle.stat({bigint:!0}),rawBytes=await handle.readFile();return{...await decodeHistorySnapshot(historyPath,itemId,rawBytes),source}}finally{await handle.close()}}async function decodeHistorySnapshot(historyPath,itemId,rawBytes){const raw=rawBytes?.toString("utf8")??null;if(raw===null)return{raw,raw_bytes:rawBytes,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,raw_bytes:rawBytes,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{entries.push(JSON.parse(line))}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw,raw_bytes:rawBytes,entries}}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{readHistoryEntries,readHistorySnapshot,readIdentifiedHistorySnapshot};
|
|
2
2
|
//# sourceMappingURL=read.js.map
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import{type FileHandle}from "node:fs/promises";import type{BigIntStats,Stats}from "node:fs";import type{HistoryEntry}from "../../types/index.js";import type{IdentifiedHistoryStreamSnapshot}from "./read.js";
|
|
2
|
+
/** Tracker-relative location of the derived summary, for cleanup registries. */
|
|
3
|
+
export declare const HISTORY_STREAM_SUMMARY_RELATIVE_PATH="runtime/history-stream-summary.json";
|
|
4
|
+
/**
|
|
5
|
+
* Smallest stream count at which bounded readers consult the summary. Below it
|
|
6
|
+
* a full read is already cheap, so no summary file is written; this mirrors
|
|
7
|
+
* the metadata cache's derived-index minimum.
|
|
8
|
+
*/
|
|
9
|
+
export declare const HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS=500;
|
|
10
|
+
/**
|
|
11
|
+
* A fixed-length digest of the reader identity, so every record stays small
|
|
12
|
+
* however many supplementary groups the account has.
|
|
13
|
+
*/
|
|
14
|
+
declare function readerDigest(identity:string|undefined):string|undefined;
|
|
15
|
+
/** The credential sources readerIdentityOf consults; process and os in production. */
|
|
16
|
+
interface ReaderCredentials{geteuid?:()=> number;getegid?:()=> number;getgroups?:()=> number[];}
|
|
17
|
+
/**
|
|
18
|
+
* The credentials this process opens files with: on POSIX the effective user
|
|
19
|
+
* id, effective group id and sorted supplementary groups (sessions of one
|
|
20
|
+
* user can differ in groups), elsewhere (Windows) the account name.
|
|
21
|
+
* Undefined when the platform reports neither, and then no stream earns
|
|
22
|
+
* trust.
|
|
23
|
+
*/
|
|
24
|
+
declare function readerIdentityOf(credentials:ReaderCredentials,userInfo:()=>{username:string;}):string|undefined;
|
|
25
|
+
/** Timestamp bounds of every entry one history stream held when it was read. */
|
|
26
|
+
export interface HistoryStreamBounds{
|
|
27
|
+
/** Number of parsed entries in the stream. */
|
|
28
|
+
count:number;
|
|
29
|
+
/** Oldest canonical entry timestamp; null when no entry has one. */
|
|
30
|
+
oldest:string|null;
|
|
31
|
+
/** Newest canonical entry timestamp; null when no entry has one. */
|
|
32
|
+
newest:string|null;
|
|
33
|
+
/**
|
|
34
|
+
* True when any entry timestamp is not a canonical millisecond UTC string
|
|
35
|
+
* (`YYYY-MM-DDTHH:mm:ss.sssZ`), so the bounds cannot prove the stream is
|
|
36
|
+
* outside a window and readers must read it.
|
|
37
|
+
*/
|
|
38
|
+
irregular:boolean;}
|
|
39
|
+
/** Why a bounded read could not use trusted bounds for a stream population. */
|
|
40
|
+
export type HistoryStreamSummaryFallback="summary_missing"|"summary_invalid"|"summary_stale"|"irregular_timestamps"|"read_hooks_active";
|
|
41
|
+
/** One read's view of the persisted summary, bound to stats taken before any stream read. */
|
|
42
|
+
export interface HistoryStreamSummarySession{
|
|
43
|
+
/** Whether trusted bounds may be used to skip streams. */
|
|
44
|
+
readonly enabled:boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Set when the summary could not serve most of this read: it is absent or
|
|
47
|
+
* unreadable, more than half of the streams lack usable regular bounds, or
|
|
48
|
+
* read hooks require every stream to be read.
|
|
49
|
+
*/
|
|
50
|
+
readonly fallback:HistoryStreamSummaryFallback|undefined;
|
|
51
|
+
/** Streams without current bounds when the session opened (stale or never recorded). */
|
|
52
|
+
readonly staleAtOpen:number;
|
|
53
|
+
/** Bounds recorded for the stream's unchanged signature, or undefined when it must be read. */
|
|
54
|
+
trusted(file:string):HistoryStreamBounds|undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Record the bounds of a stream this read parsed completely, under the
|
|
57
|
+
* identity of the open file that supplied the bytes (`snapshot.source`, the
|
|
58
|
+
* stat of that handle; null when the stream was absent). Bounds are kept
|
|
59
|
+
* only when the bytes read are the whole of that file, so they always
|
|
60
|
+
* describe the exact revision their signature names, whatever happened to
|
|
61
|
+
* the path.
|
|
62
|
+
*/
|
|
63
|
+
record(file:string,snapshot:Pick<IdentifiedHistoryStreamSnapshot,"entries"|"raw_bytes"|"source">):void;
|
|
64
|
+
/**
|
|
65
|
+
* Re-stat streams this read skipped on trusted bounds, just before the read
|
|
66
|
+
* finishes, and return those whose signature changed since the session
|
|
67
|
+
* opened (they are no longer trusted). Reading them keeps a change that
|
|
68
|
+
* completed while the read ran from being dropped; a change after this
|
|
69
|
+
* check is one a complete read could also have missed.
|
|
70
|
+
*/
|
|
71
|
+
revalidate(files:readonly string[]):Promise<string[]>;
|
|
72
|
+
/** Persist changed bounds best-effort; a failure leaves the next read to rebuild. */
|
|
73
|
+
commit():Promise<void>;}
|
|
74
|
+
interface StoredStream{signature:string;bounds:HistoryStreamBounds;}
|
|
75
|
+
interface ObservedStream{signature:string;
|
|
76
|
+
/** Byte size the stat reported; bytes of any other length are not recorded. */
|
|
77
|
+
size:bigint;
|
|
78
|
+
/** Latest of mtime and ctime, in nanoseconds since the epoch. */
|
|
79
|
+
changedAtNs:bigint;}
|
|
80
|
+
/**
|
|
81
|
+
* Whether a value is a canonical millisecond UTC timestamp whose string order
|
|
82
|
+
* is its time order: exactly what `new Date(Date.parse(v)).toISOString() === v`
|
|
83
|
+
* accepts for the fixed `YYYY-MM-DDTHH:mm:ss.sssZ` shape, checked on the
|
|
84
|
+
* calendar fields instead of a Date round trip, which dominated summary
|
|
85
|
+
* rebuilds (about 256 ms per 200,000 entries).
|
|
86
|
+
*/
|
|
87
|
+
export declare function isCanonicalHistoryTimestamp(value:unknown):value is string;
|
|
88
|
+
/** Derive the bounds a full read of one stream observed. */
|
|
89
|
+
export declare function summarizeHistoryStreamBounds(entries:readonly HistoryEntry[]):HistoryStreamBounds;
|
|
90
|
+
/** Lower the engagement threshold for specs that cannot afford 500 streams. */
|
|
91
|
+
declare function setMinimumStreams(value:number):()=> void;
|
|
92
|
+
/** Replace the reader identity so specs can model another user on a shared tracker. */
|
|
93
|
+
declare function setReaderIdentity(identity:()=> string|undefined):()=> void;
|
|
94
|
+
/** Move the racy-window clock so specs can treat just-written streams as settled. */
|
|
95
|
+
declare function setWallClock(clock:()=> number):()=> void;declare function signatureOf(stats:BigIntStats,reader:string|undefined):ObservedStream|undefined;
|
|
96
|
+
/**
|
|
97
|
+
* Whether bounds could have been produced by summarizeHistoryStreamBounds:
|
|
98
|
+
* an empty stream has no timestamps and is regular, a regular non-empty
|
|
99
|
+
* stream has both, timestamps appear together and in order. A record that
|
|
100
|
+
* fails this is damaged, and trusting it could hide a non-empty stream.
|
|
101
|
+
*/
|
|
102
|
+
declare function areConsistentBounds(bounds:HistoryStreamBounds):boolean;declare function parseStoredStream(value:unknown):StoredStream|undefined;
|
|
103
|
+
/** Generous per-record allowance plus envelope; a larger file is not a summary of these streams. */
|
|
104
|
+
declare function summaryByteCap(streamCount:number):number;
|
|
105
|
+
/**
|
|
106
|
+
* Whether an opened summary can be evidence for this reader: an unshared
|
|
107
|
+
* regular file of plausible size and, on POSIX, owned by the effective user
|
|
108
|
+
* and writable by no one else, so another account that can write runtime/
|
|
109
|
+
* cannot author bounds that suppress history it may not alter.
|
|
110
|
+
*/
|
|
111
|
+
declare function isTrustedSummaryFile(stats:Stats,streamCount:number,euid:number|undefined):boolean;
|
|
112
|
+
/**
|
|
113
|
+
* Read the whole file, refusing one that grew past the cap after its stat.
|
|
114
|
+
* The buffer starts at the stat'ed size (plus one byte to notice growth) and
|
|
115
|
+
* doubles only while the file keeps growing, never past the cap, so a warm
|
|
116
|
+
* read allocates what the summary holds rather than the whole allowance.
|
|
117
|
+
*/
|
|
118
|
+
declare function readAtMost(handle:FileHandle,cap:number,expectedSize:number):Promise<string>;declare function serializeSummary(streams:ReadonlyMap<string,StoredStream>):string;
|
|
119
|
+
/** Hash the canonical serialization the writer produced; JSON round-trips it exactly. */
|
|
120
|
+
declare function checksumOf(streams:unknown):string;
|
|
121
|
+
/**
|
|
122
|
+
* Open the summary for one bounded read of `files` (stream file names in
|
|
123
|
+
* `historyDir`). Stats are captured here, before the caller reads any stream,
|
|
124
|
+
* so a stream changed after this call can never be recorded under its new
|
|
125
|
+
* signature.
|
|
126
|
+
*/
|
|
127
|
+
export declare function openHistoryStreamSummary(params:{pmRoot:string;historyDir:string;files:readonly string[];}):Promise<HistoryStreamSummarySession>;
|
|
128
|
+
/** Test-only seams for the engagement threshold and racy window. */
|
|
129
|
+
export declare const _testOnly:{areConsistentBounds:typeof areConsistentBounds;readAtMost:typeof readAtMost;readerDigest:typeof readerDigest;isTrustedSummaryFile:typeof isTrustedSummaryFile;summaryByteCap:typeof summaryByteCap;readerIdentityOf:typeof readerIdentityOf;checksumOf:typeof checksumOf;setMinimumStreams:typeof setMinimumStreams;setReaderIdentity:typeof setReaderIdentity;setWallClock:typeof setWallClock;signatureOf:typeof signatureOf;RACY_WINDOW_NS:bigint;SUMMARY_VERSION:number;serializeSummary:typeof serializeSummary;parseStoredStream:typeof parseStoredStream;};export{};
|
|
@@ -0,0 +1,3 @@
|
|
|
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]="0a7f878e-2354-5f40-9217-81b86d7b5423")}catch{}})();import{createHash}from"node:crypto";import fs from"node:fs/promises";import os from"node:os";import path from"node:path";import{hasActiveOnReadHooks}from"../extensions/index.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";const HISTORY_STREAM_SUMMARY_RELATIVE_PATH="runtime/history-stream-summary.json",SUMMARY_VERSION=1,STAT_CONCURRENCY=64,RACY_WINDOW_NS=2000000000n,HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS=500;let minimumStreams=HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS,wallClockMs=()=>Date.now(),readerIdentity=()=>readerDigest(readerIdentityOf(process,os.userInfo));function readerDigest(identity){return identity===void 0?void 0:createHash("sha256").update(identity).digest("hex").slice(0,16)}function readerIdentityOf(credentials,userInfo){try{if(credentials.geteuid&&credentials.getegid&&credentials.getgroups){const groups=[...new Set(credentials.getgroups())].sort((left,right)=>left-right);return`uid:${credentials.geteuid()}:gid:${credentials.getegid()}:groups:${groups.join(",")}`}const{username}=userInfo();return username.length>0?`user:${username}`:void 0}catch{return}}const CANONICAL_TIMESTAMP=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;function daysInMonth(year,month){return month===2?year%4===0&&year%100!==0||year%400===0?29:28:month===4||month===6||month===9||month===11?30:31}function isCanonicalHistoryTimestamp(value){if(typeof value!="string"||!CANONICAL_TIMESTAMP.test(value))return!1;const year=Number(value.slice(0,4)),month=Number(value.slice(5,7)),day=Number(value.slice(8,10));return month>=1&&month<=12&&day>=1&&day<=daysInMonth(year,month)&&Number(value.slice(11,13))<24&&Number(value.slice(14,16))<60&&Number(value.slice(17,19))<60}function summarizeHistoryStreamBounds(entries){let oldest=null,newest=null,irregular=!1;for(const entry of entries){const timestamp=typeof entry=="object"&&entry!==null?entry.ts:void 0;if(!isCanonicalHistoryTimestamp(timestamp)){irregular=!0;continue}(oldest===null||timestamp<oldest)&&(oldest=timestamp),(newest===null||timestamp>newest)&&(newest=timestamp)}return{count:entries.length,oldest,newest,irregular}}function setMinimumStreams(value){const previous=minimumStreams;return minimumStreams=value,()=>{minimumStreams=previous}}function setReaderIdentity(identity){const previous=readerIdentity;return readerIdentity=identity,()=>{readerIdentity=previous}}function setWallClock(clock){const previous=wallClockMs;return wallClockMs=clock,()=>{wallClockMs=previous}}function isFileExistsError(error){return typeof error=="object"&&error!==null&&"code"in error&&error.code==="EEXIST"}function summaryPath(pmRoot){return path.join(pmRoot,...HISTORY_STREAM_SUMMARY_RELATIVE_PATH.split("/"))}function signatureOf(stats,reader){if(!(!stats.isFile()||stats.ino===0n||reader===void 0))return{size:stats.size,signature:[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs,reader].join(":"),changedAtNs:stats.mtimeNs>stats.ctimeNs?stats.mtimeNs:stats.ctimeNs}}async function observeStreams(historyDir,files,reader){const observed=new Map;for(let start=0;start<files.length;start+=STAT_CONCURRENCY){const chunk=files.slice(start,start+STAT_CONCURRENCY);(await Promise.all(chunk.map(file=>fs.stat(path.join(historyDir,file),{bigint:!0}).catch(()=>{})))).forEach((stat,index)=>{const signature=stat===void 0?void 0:signatureOf(stat,reader);signature!==void 0&&observed.set(chunk[index],signature)})}return observed}function isNullableCanonical(value){return value===null||isCanonicalHistoryTimestamp(value)}function areConsistentBounds(bounds){return bounds.oldest===null!=(bounds.newest===null)?!1:bounds.count===0?bounds.oldest===null&&!bounds.irregular:bounds.oldest===null?bounds.irregular:bounds.oldest<=bounds.newest}function parseStoredStream(value){if(!Array.isArray(value)||value.length!==5)return;const[signature,count,oldest,newest,irregular]=value;if(typeof signature!="string"||!Number.isSafeInteger(count)||count<0||!isNullableCanonical(oldest)||!isNullableCanonical(newest)||typeof irregular!="boolean")return;const bounds={count,oldest,newest,irregular};return areConsistentBounds(bounds)?{signature,bounds}:void 0}function summaryByteCap(streamCount){return 4096+streamCount*1024}function isTrustedSummaryFile(stats,streamCount,euid){return!stats.isFile()||stats.nlink!==1||stats.size>summaryByteCap(streamCount)?!1:euid===void 0||stats.uid===euid&&(stats.mode&18)===0}async function hasRealRuntimeDirectory(pmRoot){return(await fs.lstat(path.join(pmRoot,"runtime"))).isDirectory()}async function hasNonRegularSummaryEntry(pmRoot){try{return!(await fs.lstat(summaryPath(pmRoot))).isFile()}catch{return!1}}async function isSummaryUnwritable(pmRoot){try{if(!await hasRealRuntimeDirectory(pmRoot))return!0}catch{return!1}return hasNonRegularSummaryEntry(pmRoot)}async function readSummaryText(pmRoot,streamCount){if(!await hasRealRuntimeDirectory(pmRoot))throw new Error("runtime directory is redirected");if((await fs.lstat(summaryPath(pmRoot))).isSymbolicLink())throw new Error("history stream summary is a link");const handle=await fs.open(summaryPath(pmRoot),fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);try{const stats=await handle.stat();if(!isTrustedSummaryFile(stats,streamCount,process.geteuid?.()))throw new Error("history stream summary is not a trusted file");return await readAtMost(handle,summaryByteCap(streamCount),stats.size)}finally{await handle.close()}}async function readAtMost(handle,cap,expectedSize){let buffer=Buffer.alloc(Math.min(Math.max(expectedSize,0),cap)+1),length=0;for(;;){if(length===buffer.length){const grown=Buffer.alloc(Math.min(buffer.length*2,cap+1));buffer.copy(grown,0,0,length),buffer=grown}const{bytesRead}=await handle.read(buffer,length,buffer.length-length,length);if(bytesRead===0)break;if(length+=bytesRead,length>cap)throw new Error("history stream summary grew past its size cap")}return buffer.subarray(0,length).toString("utf8")}async function readStoredSummary(pmRoot,streamCount){let raw;try{raw=await readSummaryText(pmRoot,streamCount)}catch(error){return{state:isFileMissingError(error)?"missing":"invalid",streams:new Map}}try{const parsed=JSON.parse(raw);if(parsed.version!==SUMMARY_VERSION||typeof parsed.streams!="object"||parsed.streams===null||Array.isArray(parsed.streams)||parsed.checksum!==checksumOf(parsed.streams))return{state:"invalid",streams:new Map};const streams=new Map;for(const[file,value]of Object.entries(parsed.streams)){const stream=parseStoredStream(value);if(stream===void 0)return{state:"invalid",streams:new Map};streams.set(file,stream)}return{state:"loaded",streams}}catch{return{state:"invalid",streams:new Map}}}function serializeSummary(streams){const ordered=[...streams.entries()].sort(([left],[right])=>left<right?-1:1),encoded={};for(const[file,{signature,bounds}]of ordered)encoded[file]=[signature,bounds.count,bounds.oldest,bounds.newest,bounds.irregular];return`${JSON.stringify({version:SUMMARY_VERSION,checksum:checksumOf(encoded),streams:encoded})}
|
|
2
|
+
`}function checksumOf(streams){return createHash("sha256").update(JSON.stringify(streams)).digest("hex")}function summaryFallback(state,current,streamCount){if(state==="missing")return"summary_missing";if(state==="invalid")return"summary_invalid";const stale=streamCount-current.size;let irregular=0;for(const{bounds}of current.values())bounds.irregular&&(irregular+=1);if(!((stale+irregular)*2<=streamCount))return stale>=irregular?"summary_stale":"irregular_timestamps"}function disabledSession(fallback){return{enabled:!1,staleAtOpen:0,fallback,trusted:()=>{},record:()=>{},revalidate:async()=>[],commit:async()=>{}}}async function openHistoryStreamSummary(params){if(params.files.length<minimumStreams)return disabledSession(void 0);if(hasActiveOnReadHooks())return disabledSession("read_hooks_active");if(await isSummaryUnwritable(params.pmRoot))return disabledSession("summary_invalid");const observedAtNs=BigInt(Math.floor(wallClockMs()))*1000000n,reader=readerIdentity(),[stored,observed]=await Promise.all([readStoredSummary(params.pmRoot,params.files.length),observeStreams(params.historyDir,params.files,reader)]);if(hasActiveOnReadHooks())return disabledSession("read_hooks_active");const next=new Map;for(const[file,stream]of stored.streams)observed.get(file)?.signature===stream.signature&&next.set(file,stream);let dirty=!1;return{enabled:!0,staleAtOpen:params.files.length-next.size,fallback:summaryFallback(stored.state,next,params.files.length),trusted:file=>next.get(file)?.bounds,record:(file,{entries,raw_bytes:rawBytes,source})=>{const observation=source===null||rawBytes===null?void 0:signatureOf(source,reader);observation===void 0||BigInt(rawBytes.length)!==observation.size||observation.changedAtNs+RACY_WINDOW_NS>=observedAtNs||next.get(file)?.signature===observation.signature||(next.set(file,{signature:observation.signature,bounds:summarizeHistoryStreamBounds(entries)}),dirty=!0)},revalidate:async files=>{const current=await observeStreams(params.historyDir,files,reader),changed=files.filter(file=>current.get(file)?.signature!==next.get(file)?.signature);for(const file of changed)next.delete(file);return changed},commit:async()=>{dirty&&(dirty=!1,await persistSummary(params.pmRoot,next))}}}async function persistSummary(pmRoot,streams){try{if(await fs.mkdir(path.join(pmRoot,"runtime")).catch(error=>{if(!isFileExistsError(error))throw error}),!await hasRealRuntimeDirectory(pmRoot)||await hasNonRegularSummaryEntry(pmRoot))return;await writeFileAtomic(summaryPath(pmRoot),serializeSummary(streams),{createParentDirectories:!1,mode:384})}catch{}}const _testOnly={areConsistentBounds,readAtMost,readerDigest,isTrustedSummaryFile,summaryByteCap,readerIdentityOf,checksumOf,setMinimumStreams,setReaderIdentity,setWallClock,signatureOf,RACY_WINDOW_NS,SUMMARY_VERSION,serializeSummary,parseStoredStream};export{HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS,HISTORY_STREAM_SUMMARY_RELATIVE_PATH,_testOnly,isCanonicalHistoryTimestamp,openHistoryStreamSummary,summarizeHistoryStreamBounds};
|
|
3
|
+
//# sourceMappingURL=stream-summary.js.map
|
|
@@ -238,6 +238,14 @@ suggested_path?:string;
|
|
|
238
238
|
examples?:string[];
|
|
239
239
|
/** Value that configures or reports next steps for this contract. */
|
|
240
240
|
nextSteps?:string[];
|
|
241
|
+
/**
|
|
242
|
+
* The refusal rejects the URL credentials carried by `source` (an option,
|
|
243
|
+
* environment variable or field name), such as an identity with userinfo,
|
|
244
|
+
* so recovery never advises restoring those redacted credentials: replaying
|
|
245
|
+
* with them reproduces this refusal (GH-1757). `source` is a code-defined
|
|
246
|
+
* label, never caller input: guidance prints it unredacted.
|
|
247
|
+
*/
|
|
248
|
+
url_credentials_rejected?:{source:string;};
|
|
241
249
|
/** Exact selectors that could not be matched by a lossless removal. */
|
|
242
250
|
unmatched?:string[];
|
|
243
251
|
/** Dependency selectors that matched no stored edge. */
|
|
@@ -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]="745f8a29-e1f9-574c-bf67-70f564b0415b")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
|
|
2
2
|
//# sourceMappingURL=errors.js.map
|
|
@@ -26,6 +26,15 @@ export declare function readCompactionMarker(text:string):number|undefined;
|
|
|
26
26
|
* next call, so compaction never shortens it (GH-1710).
|
|
27
27
|
*/
|
|
28
28
|
export declare function isContinuationTokenKey(key:string):boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Whether an envelope key of a read surface holds tracker item documents: the
|
|
31
|
+
* item `get` returns, or the rows of a `list` or `search` page. An item's
|
|
32
|
+
* fields are content, not continuation tokens, so a custom field named like
|
|
33
|
+
* one (`next_cursor`, `sync_cursor`) compacts like any other string
|
|
34
|
+
* (GH-1754). Any other surface, an extension's included, keeps the exemption
|
|
35
|
+
* for every key: its rows may carry genuine tokens.
|
|
36
|
+
*/
|
|
37
|
+
export declare function isTrackerItemDocumentKey(surface:string|undefined,key:string):boolean;
|
|
29
38
|
/**
|
|
30
39
|
* Whether a cursor argument carries an ellipsis, which no encoder emits: the
|
|
31
40
|
* caller pasted a value a compacted read shortened (GH-1710).
|
|
@@ -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]="f74cf2ed-6219-57c6-98a3-4b4c7496a17c")}catch{}})();function normalizeLowercaseWhitespace(value){return value.trim().toLowerCase().replace(/\s+/g," ")}function unicodeSafePrefix(value,end){const prefix=value.slice(0,end),last=prefix.charCodeAt(prefix.length-1),next=value.charCodeAt(prefix.length);return last>=55296&&last<=56319&&next>=56320&&next<=57343?prefix.slice(0,-1):prefix}const COMPACTED_STRING_LENGTH=240,COMPACTION_MARKER_PATTERN=/\u2026\[\+([1-9]\d*) chars\]$/u;function compactExplanatoryString(value){if(value.length<=COMPACTED_STRING_LENGTH)return value;const marker=COMPACTION_MARKER_PATTERN.exec(value);if(marker!==null&&marker.index<=COMPACTED_STRING_LENGTH)return value;const prefix=unicodeSafePrefix(value,COMPACTED_STRING_LENGTH);return`${prefix}\u2026[+${value.length-prefix.length} chars]`}function readCompactionMarker(text){const match=COMPACTION_MARKER_PATTERN.exec(text.trimEnd());return match?Number(match[1]):void 0}function isContinuationTokenKey(key){return key==="cursor"||key.endsWith("_cursor")}const TRACKER_ITEM_READ_SURFACES=new Set(["get","list","search"]);function isTrackerItemDocumentKey(surface,key){return(key==="item"||key==="items")&&surface!==void 0&&TRACKER_ITEM_READ_SURFACES.has(surface)}function isCompactedCursorArgument(value){return value.includes("\u2026")}function tokenizeAlphaNumeric(value){return normalizeLowercaseWhitespace(value).split(/[^a-z0-9]+/).filter(token=>token.length>0)}function jaccardSimilarity(leftTokens,rightTokens){if(leftTokens.length===0&&rightTokens.length===0)return 1;if(leftTokens.length===0||rightTokens.length===0)return 0;const leftSet=new Set(leftTokens),rightSet=new Set(rightTokens);let intersection=0;for(const token of leftSet)rightSet.has(token)&&(intersection+=1);const union=new Set([...leftSet,...rightSet]).size;return intersection/union}export{COMPACTED_STRING_LENGTH,compactExplanatoryString,isCompactedCursorArgument,isContinuationTokenKey,isTrackerItemDocumentKey,jaccardSimilarity,normalizeLowercaseWhitespace,readCompactionMarker,tokenizeAlphaNumeric,unicodeSafePrefix};
|
|
2
2
|
//# sourceMappingURL=text-normalization.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]="a6bebd48-2722-5784-b69b-cf18321ea2c0")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{quoteWindowsCommandArg}from"./command-line.js";import{EXIT_CODE}from"./constants.js";import{PmCliError}from"./errors.js";const URL_CREDENTIAL_PLACEHOLDER="[redacted]";function provablyWithoutUserinfo(token,colon){if(/[\t\n\r]/u.test(token)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(token.slice(0,colon)))return!1;let authority=colon+1;for(;token[authority]==="/"||token[authority]==="\\";)authority+=1;const delimiter=token.indexOf("/",authority)-authority;if(delimiter<0)return!1;const authorityEnd=authority+delimiter;return!/[:@%]/u.test(token.slice(authority,authorityEnd))&&!/[:%]|[/\\][/\\]/u.test(token.slice(authorityEnd))}function userinfoBounds(token){const at=Math.max(token.lastIndexOf("@"),token.toLowerCase().lastIndexOf("%40")),colon=token.indexOf(":");if(at<0||colon<0||colon>at)return;let start=colon+1;for(;start<at&&start<colon+3&&(token[start]==="/"||token[start]==="\\");)start+=1;return start===at||provablyWithoutUserinfo(token,colon)?void 0:[start,at]}function redactUrlCredentialsInToken(token){const bounds=userinfoBounds(token);return bounds?`${token.slice(0,bounds[0])}${URL_CREDENTIAL_PLACEHOLDER}${token.slice(bounds[1])}`:token}function redactIdentityCredentials(identity){return redactUrlCredentialsInToken(identity)}const IDENTITY_FIELDS=["author","assignee","claim_principal"];function redactIdentityFields(values){const redacted={...values};for(const field of IDENTITY_FIELDS)typeof redacted[field]=="string"&&(redacted[field]=redactIdentityCredentials(redacted[field]));return redacted}function assertIdentityWithoutUrlCredentials(identity,source){if(!(typeof identity!="string"||userinfoBounds(identity.trim())===void 0))throw new PmCliError(`${source} must not carry URL credentials: an identity is a name, never a credential.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:source,required:`Set ${source} to a plain name such as agent-a, with no URL userinfo (no user, password or token before the host).`,nextSteps:[`Rerun with ${source} set to a plain name.`],url_credentials_rejected:{source}})}function parseIdentityOption(value,source){return assertIdentityWithoutUrlCredentials(value,source),value}const NESTED_IDENTITY_PATHS=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["plan_steps","owner"],["tests","provenance","author"],["tests","updated_by"]],IDENTITY_VALUE_DEPTH=4;function assertIdentityValueWithoutUrlCredentials(value,source,depth=0){if(typeof value=="string"){assertIdentityWithoutUrlCredentials(value,source);return}if(!(depth>=IDENTITY_VALUE_DEPTH||typeof value!="object"||value===null))for(const entry of Object.values(value))assertIdentityValueWithoutUrlCredentials(entry,source,depth+1)}function readEntryPath(entry,path){let node=entry;for(const key of path){if(typeof node!="object"||node===null||Array.isArray(node))return;node=node[key]}return node}function assertIdentityFieldsWithoutUrlCredentials(values){const record=values;for(const field of IDENTITY_FIELDS)assertIdentityValueWithoutUrlCredentials(record[field],field);for(const[collection,...path]of NESTED_IDENTITY_PATHS){const entries=record[collection];Array.isArray(entries)&&entries.forEach((entry,index)=>{assertIdentityValueWithoutUrlCredentials(readEntryPath(entry,path),`${collection}[${index}].${path.join(".")}`)})}}function redactOptionalIdentityCredentials(value){return typeof value=="string"?redactIdentityCredentials(value):value}const MIN_FRAGMENT_LENGTH=6,MAX_REGISTERED_FRAGMENTS=65536,NO_INVOCATION={carried:!1,fragments:new Set,fragmentLength:MIN_FRAGMENT_LENGTH,shortSpellings:[]},invocations=new AsyncLocalStorage;function lowerPreservingLength(text){const lowered=text.toLowerCase();if(lowered.length===text.length)return lowered;let result="";for(const unit of text){const lower=unit.toLowerCase();result+=lower.length===unit.length?lower:unit}return result}function spanSpellings(span){return[span,span.replaceAll(/(["\\$`])/gu,"\\$1"),quoteWindowsCommandArg(`${span}@`).slice(1,-2),JSON.stringify(span).slice(1,-1)]}function userinfoSecret(userinfo){const colon=userinfo.indexOf(":");return colon>=0&&colon<userinfo.length-1?userinfo.slice(colon+1):userinfo}function describeInvocation(argv){const unique=new Set;let carried=!1;for(const token of argv){const bounds=userinfoBounds(token);if(bounds){carried=!0;for(const spelling of spanSpellings(userinfoSecret(token.slice(bounds[0],bounds[1]))))unique.add(lowerPreservingLength(spelling))}}const spellings=[...unique],positions=spellings.reduce((total,spelling)=>total+Math.max(0,spelling.length-MIN_FRAGMENT_LENGTH+1)+1,0),stride=Math.max(1,Math.ceil(positions/MAX_REGISTERED_FRAGMENTS)),fragmentLength=Math.max(MIN_FRAGMENT_LENGTH,stride),fragments=new Set,shortSpellings=new Set;for(const spelling of spellings){if(spelling.length<fragmentLength){(spelling.length>=MIN_FRAGMENT_LENGTH||/\s/u.test(spelling))&&shortSpellings.add(spelling);continue}for(let index=0;index+fragmentLength<=spelling.length;index+=stride)fragments.add(spelling.slice(index,index+fragmentLength));fragments.add(spelling.slice(-fragmentLength))}return{carried,fragments,fragmentLength,shortSpellings:[...shortSpellings]}}function removeRegisteredFragments(text,invocation){const lowered=lowerPreservingLength(text),covered=new Uint8Array(text.length);let found=!1;const width=invocation.fragmentLength;for(let index=0;index+width<=lowered.length;index+=1)invocation.fragments.has(lowered.slice(index,index+width))&&(covered.fill(1,index,index+width),found=!0);for(const spelling of invocation.shortSpellings)for(let index=lowered.indexOf(spelling);index>=0;index=lowered.indexOf(spelling,index+1))covered.fill(1,index,index+spelling.length),found=!0;if(!found)return text;let result="";for(let index=0;index<text.length;index+=1)covered[index]?(index===0||!covered[index-1])&&(result+=URL_CREDENTIAL_PLACEHOLDER):result+=text[index];return result}function runWithUrlCredentialInvocation(argv,run){return invocations.run(describeInvocation(argv),run)}function invocationCarriesUrlCredentials(){return(invocations.getStore()??NO_INVOCATION).carried}function redactUrlCredentialsInText(text){const invocation=invocations.getStore()??NO_INVOCATION,redacted=invocation.carried?removeRegisteredFragments(text,invocation):text;return/@|%40/iu.test(redacted)?redacted.replaceAll(/\S+/gu,redactUrlCredentialsInToken):redacted}export{URL_CREDENTIAL_PLACEHOLDER,assertIdentityFieldsWithoutUrlCredentials,assertIdentityWithoutUrlCredentials,invocationCarriesUrlCredentials,parseIdentityOption,redactIdentityCredentials,redactIdentityFields,redactOptionalIdentityCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation};
|
|
2
2
|
//# sourceMappingURL=url-credentials.js.map
|