@ppdostudio/ppdo-cli 0.0.0-stage → 1.0.0-beta.1
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/CHANGELOG.md +66 -0
- package/LICENSE +114 -0
- package/README.md +362 -3
- package/THIRD-PARTY-NOTICES +25 -0
- package/dist/bin.js +5 -0
- package/dist/chunks/ado-XAHQWYNQ.js +103 -0
- package/dist/chunks/api-7RAWLIQV.js +2 -0
- package/dist/chunks/api-KN24TLH6.js +2 -0
- package/dist/chunks/auth-VZSJMSMF.js +6 -0
- package/dist/chunks/azCli-AEZK2RBQ.js +2 -0
- package/dist/chunks/batch-EZPKLWEI.js +4 -0
- package/dist/chunks/build-LSQEAEFK.js +4 -0
- package/dist/chunks/bulk-7FZCDH5U.js +2 -0
- package/dist/chunks/chunk-4KP27OCL.js +2 -0
- package/dist/chunks/chunk-5SBBTR3Y.js +2 -0
- package/dist/chunks/chunk-B4FPKDMH.js +2 -0
- package/dist/chunks/chunk-BALEFXOL.js +29 -0
- package/dist/chunks/chunk-BCAXUZIO.js +2 -0
- package/dist/chunks/chunk-BODUSF3V.js +2 -0
- package/dist/chunks/chunk-C42MGXRN.js +2 -0
- package/dist/chunks/chunk-DVQ7OYIJ.js +2 -0
- package/dist/chunks/chunk-GE3XBV3K.js +2 -0
- package/dist/chunks/chunk-H4OY4EFC.js +3 -0
- package/dist/chunks/chunk-HIW2K6OP.js +4 -0
- package/dist/chunks/chunk-I3TMFYRJ.js +194 -0
- package/dist/chunks/chunk-J4R6QXW7.js +2 -0
- package/dist/chunks/chunk-JAGU2NM5.js +2 -0
- package/dist/chunks/chunk-JEAIFLEN.js +51 -0
- package/dist/chunks/chunk-KBQYSAJX.js +2 -0
- package/dist/chunks/chunk-LB7WNZVK.js +5 -0
- package/dist/chunks/chunk-LL4XQ3L7.js +4 -0
- package/dist/chunks/chunk-MBNUMAAZ.js +2 -0
- package/dist/chunks/chunk-MGZDEW3X.js +8 -0
- package/dist/chunks/chunk-MK6QZ4ES.js +2 -0
- package/dist/chunks/chunk-MTF66YXU.js +2 -0
- package/dist/chunks/chunk-MZEUD7ET.js +6 -0
- package/dist/chunks/chunk-OXZG44O5.js +2 -0
- package/dist/chunks/chunk-PYTSDUPY.js +2 -0
- package/dist/chunks/chunk-QMTPHZLQ.js +2 -0
- package/dist/chunks/chunk-RC5VPVGC.js +2 -0
- package/dist/chunks/chunk-S4KF5Z3S.js +10 -0
- package/dist/chunks/chunk-STWQDANK.js +5 -0
- package/dist/chunks/chunk-TADCW6ZI.js +2 -0
- package/dist/chunks/chunk-TM3M633T.js +3 -0
- package/dist/chunks/chunk-TQLZ3TRU.js +2 -0
- package/dist/chunks/chunk-TXVNEV3M.js +3 -0
- package/dist/chunks/chunk-TZSB4PR7.js +4 -0
- package/dist/chunks/chunk-UCTMKA2J.js +4 -0
- package/dist/chunks/chunk-WIA546AL.js +13 -0
- package/dist/chunks/chunk-WMDKJRDC.js +2 -0
- package/dist/chunks/chunk-WNQERCOO.js +2 -0
- package/dist/chunks/chunk-WXOTXJNG.js +3 -0
- package/dist/chunks/chunk-ZHHVG47C.js +2 -0
- package/dist/chunks/chunk-ZNJ4DRCA.js +2 -0
- package/dist/chunks/chunk-ZUXLC5VX.js +2 -0
- package/dist/chunks/commands-GRWX32IX.js +2 -0
- package/dist/chunks/component-TCL43QXZ.js +2 -0
- package/dist/chunks/components-LRHXR5HR.js +2 -0
- package/dist/chunks/config-UKI5TBH5.js +2 -0
- package/dist/chunks/connection-QNXMJGHZ.js +2 -0
- package/dist/chunks/connref-U3CMQ64O.js +2 -0
- package/dist/chunks/customizations-VNEASPWI.js +7 -0
- package/dist/chunks/dependency-U6OQA5PS.js +3 -0
- package/dist/chunks/discovery-IWAWXXWF.js +2 -0
- package/dist/chunks/dist-ILNYGTM2.js +136 -0
- package/dist/chunks/dv-C45WDXRG.js +192 -0
- package/dist/chunks/env-GL5ZPAZI.js +5 -0
- package/dist/chunks/environment-FPS4AFM5.js +2 -0
- package/dist/chunks/environments-VZWNFJYE.js +2 -0
- package/dist/chunks/envvar-52V6K6LF.js +2 -0
- package/dist/chunks/esm-Z4QMBGAD.js +2 -0
- package/dist/chunks/fanout-Q3656CCP.js +2 -0
- package/dist/chunks/fetchxml-FWUQZP4M.js +6 -0
- package/dist/chunks/functions-SNCK2IYV.js +2 -0
- package/dist/chunks/graph-OK24IOUV.js +5 -0
- package/dist/chunks/group-TLGLTTUG.js +6 -0
- package/dist/chunks/history-67SQS54S.js +2 -0
- package/dist/chunks/identity-SRTOEQVC.js +2 -0
- package/dist/chunks/jobs-2ZPBDDHT.js +2 -0
- package/dist/chunks/lifecycle-OJRM7K2I.js +2 -0
- package/dist/chunks/main-HOYSLMHZ.js +4 -0
- package/dist/chunks/metadata-WYVJ7NP7.js +2 -0
- package/dist/chunks/metadataCreate-PBA3KH3A.js +2 -0
- package/dist/chunks/msalUser-3PBGT655.js +2 -0
- package/dist/chunks/names-ZRM6SAYU.js +2 -0
- package/dist/chunks/pack-3OYGV36R.js +2 -0
- package/dist/chunks/pat-KGOBISLG.js +2 -0
- package/dist/chunks/pipelines-62CVDRXV.js +4 -0
- package/dist/chunks/plan-ALLKT2QZ.js +2 -0
- package/dist/chunks/plugins-SBMDFXVA.js +4 -0
- package/dist/chunks/policies-BZR5437X.js +2 -0
- package/dist/chunks/pools-I4NVR67Z.js +2 -0
- package/dist/chunks/process-WS76WV3T.js +2 -0
- package/dist/chunks/project-HSZLY2AY.js +2 -0
- package/dist/chunks/projects-GXIQO7HV.js +4 -0
- package/dist/chunks/protect-X2J7LU7X.js +2 -0
- package/dist/chunks/provider-FN7TXWRE.js +2 -0
- package/dist/chunks/prs-F2EVQJRV.js +2 -0
- package/dist/chunks/records-7IQET422.js +2 -0
- package/dist/chunks/run-APD3TRCW.js +2 -0
- package/dist/chunks/run-G2MVOV3C.js +3 -0
- package/dist/chunks/run-H2OLE76P.js +2 -0
- package/dist/chunks/run-ICS4FNZA.js +3 -0
- package/dist/chunks/run-KP2SNX2A.js +3 -0
- package/dist/chunks/run-LNEOCXZA.js +2 -0
- package/dist/chunks/run-SB4QN5Q4.js +2 -0
- package/dist/chunks/run-XRPU3YZF.js +2 -0
- package/dist/chunks/runtime-MIU5CS5B.js +2 -0
- package/dist/chunks/security-RC3EI7CZ.js +2 -0
- package/dist/chunks/service-4VHAPTA6.js +2 -0
- package/dist/chunks/service-RFKOKM72.js +2 -0
- package/dist/chunks/services-4BORTJPM.js +2 -0
- package/dist/chunks/skills-6O2GSTU4.js +2 -0
- package/dist/chunks/solution-3WUUDYF3.js +2 -0
- package/dist/chunks/solutionExport-GTBTHG2D.js +2 -0
- package/dist/chunks/solutionfiles-VWZHFZZ6.js +2 -0
- package/dist/chunks/spn-2RZJLCML.js +2 -0
- package/dist/chunks/tokenCache-TQFT6LAD.js +2 -0
- package/dist/chunks/unpack-HUH7OJMP.js +2 -0
- package/dist/chunks/users-JIBQKPYA.js +2 -0
- package/dist/chunks/vargroups-Q2KG7LHR.js +2 -0
- package/dist/chunks/whoami-V54TCLT5.js +2 -0
- package/dist/chunks/workitems-UG5O3EGB.js +2 -0
- package/dist/chunks/xmldoc-B2HUNTVK.js +2 -0
- package/package.json +57 -6
- package/schema/ppdo-cli.schema.json +132 -0
- package/skills/README.md +12 -0
- package/skills/ppdo-cli/SKILL.md +84 -0
- package/skills/ppdo-cli-dataverse/SKILL.md +302 -0
- package/skills/ppdo-cli-devops/SKILL.md +150 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{d as P,e as r,i as d,j as l,k as j,l as S,n as U,o as m,q as E,r as o}from"./chunk-BALEFXOL.js";import{a as z}from"./chunk-MTF66YXU.js";import{b as O}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var N=100;function p(a){return a.addOption(new r("--limit <n>",`return at most n items (default ${N})`).argParser(d)).option("--all","no cap")}function T(a){let t=a;for(;t.parent;)t=t.parent;return t}function f(a,t,e=!1){return a.hook("preAction",(s,i)=>{let G=T(i).rawArgs??[],L=w=>G.findIndex(y=>y===w||y.startsWith(w+"=")),v=t.filter(w=>i.getOptionValueSource(E(w.replace(/^--/,"")))==="cli").sort((w,y)=>L(w)-L(y)),x=`run: ${[T(i).name(),...U(i)].join(" ")} --help`;if(v.length>1)throw new O(`argument ${v[1]}: not allowed with argument ${v[0]}`,{hint:x});if(e&&!v.length)throw new O(`one of the arguments ${t.join(" ")} is required`,{hint:x})}),a}var n=(a,t)=>async e=>t(await a())(e);var $=()=>import("./users-JIBQKPYA.js"),b=()=>import("./vargroups-Q2KG7LHR.js"),k=()=>import("./environments-VZWNFJYE.js"),q=()=>import("./pools-I4NVR67Z.js");function A(a){o(m(a,"user","users and groups in the organization"),"get","R","a user by email, UPN or full display name",{description:`a user by email, UPN or full display name ('me' for the signed-in account)
|
|
3
|
+
|
|
4
|
+
Returns id, name, upn, mail, descriptor (the subject descriptor), active, kind (User or
|
|
5
|
+
Group) and object_id (Entra). Matching is exact: part of a name finds nobody.`}).argument("<email|upn|name|me>").argKey("email|upn|name|me","who").handler(n($,i=>i.getUser));let t=m(a,"vargroup","variable groups (secret values are never shown)");p(o(t,"list","R","variable groups in the project").option("--name <pattern>","name filter; a trailing * is a wildcard")).handler(n(b,i=>i.list)),o(t,"get","R","one variable group").argument("<group>","variable group id or name").argKey("group","vargroup").handler(n(b,i=>i.getGroup)),o(t,"create","W","create a variable group",{description:`create a variable group
|
|
6
|
+
|
|
7
|
+
A value of @file is read from the file; prefer that for secrets, so they stay out of the
|
|
8
|
+
command line. Secret values are never shown, --dry-run included.`}).argument("<name>").option("--variable <k=v|k=@file>","plain variable (repeatable)",l).option("--secret <k=v|k=@file>","secret variable (repeatable)",l).option("--description <description>").handler(n(b,i=>i.create)),o(t,"set","W","add, change or remove variables (the rest are kept, secrets included)",{description:`add, change or remove variables (the rest are kept, secrets included)
|
|
9
|
+
|
|
10
|
+
Azure DevOps replaces the whole group on every write, so ppdo-cli sends back every variable
|
|
11
|
+
it doesn't change, with secrets left as they are. A secret can't be made plain or empty.`}).argument("<group>","variable group id or name").argKey("group","vargroup").option("--variable <k=v|k=@file>","set a plain variable (repeatable)",l).option("--secret <k=v|k=@file>","set a secret variable (repeatable)",l).option("--remove <name>","remove a variable (repeatable)",l).option("--description <description>").handler(n(b,i=>i.set));let e=m(a,"environment","pipeline environments (deployment targets with approvals and checks)");p(o(e,"list","R","pipeline environments in the project").option("--name <pattern>","name; a trailing * is a wildcard")).handler(n(k,i=>i.list)),o(e,"create","W","create a pipeline environment").argument("<name>").option("--description <description>").handler(n(k,i=>i.create)),o(e,"checks","R","an environment's approvals and checks, and which pipelines may use it").argument("<environment>","environment id or name").handler(n(k,i=>i.checks)),o(e,"permit","W","allow a pipeline to use an environment",{description:`allow a pipeline to use an environment
|
|
12
|
+
|
|
13
|
+
Without it, a run that deploys to the environment waits for someone to permit it.`}).argument("<environment>","environment id or name").requiredOption("--pipeline <id|name|url>").handler(n(k,i=>i.permit));let s=m(a,"pool","agent pools");p(o(s,"list","R","agent pools").option("--name <pattern>","pool name; a trailing * is a wildcard").option("--legacy","include the old retired hosted pools")).handler(n(q,i=>i.list)),o(s,"agents","R","a pool's agents: online, enabled, busy, version").argument("<pool>","pool id or name").addOption(new r("--status <status>").choices(["online","offline"])).handler(n(q,i=>i.agents)),o(s,"usage","R","how long jobs waited for an agent, and how many ran at once",{description:`how long jobs waited for an agent, and how many ran at once
|
|
14
|
+
|
|
15
|
+
From the pool's job requests: wait = queued until an agent was assigned; run = assigned
|
|
16
|
+
until finished; peak = most jobs running at the same time. --top adds the pipelines that
|
|
17
|
+
used the pool most.`}).argument("<pool>","pool id or name").option("--since <when>","30m, 12h, 7d, 2w or a date (default 7d)").addOption(new r("--limit <n>","job requests to read (default 5000)").argParser(d)).addOption(new r("--top <n>","busiest pipelines to show (default 5)").argParser(d)).handler(n(q,i=>i.usage))}var u=()=>import("./pipelines-62CVDRXV.js"),Q=["succeeded","partiallySucceeded","failed","canceled"],Y="manual, individualCI, batchedCI, schedule, scheduleForced, pullRequest, resourceTrigger, buildCompletion, triggered, userCreated, validateShelveset, checkInShelveset";function C(a){let t=m(a,"pipeline","pipelines: list, inspect, run");p(o(t,"list","R","pipelines in the project").option("--folder <path>","only pipelines in this folder")).handler(n(u,s=>s.list)),o(t,"get","R","one pipeline").argument("<pipeline>","pipeline id, name or URL").handler(n(u,s=>s.getPipeline)),f(o(t,"run","W","queue a run",{description:`--param sets YAML parameters (templateParameters); --variable sets runtime variables.
|
|
18
|
+
Example: ppdo-cli ado pipeline run deploy --branch main --param env=test --wait --logs-on-failure`}).argument("<pipeline>","pipeline id, name or URL").option("--branch <ref>","branch to run (default: the pipeline's default)").option("--param <k=v>","YAML parameter (repeatable)",l).option("--variable <k=v>","runtime variable (repeatable)",l).option("--wait","wait for the run; non-zero exit unless it succeeds").option("--logs-on-failure","with --wait: include failed steps' log tails").option("--skip-stage <stage>[,<stage>...]","stages not to run").option("--only-stage <stage>[,<stage>...]","run only these stages"),["--skip-stage","--only-stage"]).handler(n(u,s=>s.runPipeline)),o(t,"stages","R","the stages a run would have, from the expanded YAML",{description:`the stages a run would have, from the expanded YAML
|
|
19
|
+
|
|
20
|
+
Uses a preview run (nothing is queued), so templates and parameters are applied.
|
|
21
|
+
Stage names are what --skip-stage, --only-stage and run retry --stage take.`}).argument("<pipeline>","pipeline id, name or URL").option("--branch <ref>","branch to read the YAML from (default: the pipeline's default)").option("--param <k=v>","YAML parameter (repeatable)",l).handler(n(u,s=>s.stages));let e=m(a,"run","pipeline runs: list, status, logs, cancel");p(o(e,"list","R","runs of a pipeline (newest first)").argument("<pipeline>","pipeline id, name or URL").option("--branch <ref>").addOption(new r("--result <result>").choices(Q)).option("--reason <a,b>","what triggered the run: "+Y)).handler(n(u,s=>s.runs)),o(e,"get","R","run status, stages and errors").argument("<run>","run id or its dev.azure.com URL").handler(n(u,s=>s.runGet)),o(e,"logs","R","step logs (tails), optionally only failed steps",{description:`step logs (tails), optionally only failed steps
|
|
22
|
+
|
|
23
|
+
--save <dir> writes each step's log to <dir>/<job>-<step>.log as plain text (the whole log unless
|
|
24
|
+
--tail is given) and prints the files instead of the logs.`}).argument("<run>","run id or its dev.azure.com URL").option("--failed-only").option("--step <name>","steps whose name contains this text").addOption(new r("--tail <n>","last n lines per step (default 100, or all with --save; 0 = all)").argParser(d)).option("--timestamps","keep each line's timestamp").option("--save <dir>","write one .log file per step to this folder").handler(n(u,s=>s.logs)),o(e,"retry","W","re-run failed or canceled stages of a finished run",{description:`re-run failed or canceled stages of a finished run
|
|
25
|
+
|
|
26
|
+
Without --stage, every failed or canceled stage. Only the failed jobs in a stage run again
|
|
27
|
+
unless --all-jobs.`}).argument("<run>","run id or its dev.azure.com URL").option("--stage <stage>[,<stage>...]","stage names or display names").option("--all-jobs","re-run every job in the stage, not only failed ones").option("--wait","wait for the run; non-zero exit unless it succeeds").option("--logs-on-failure","with --wait: include failed steps' log tails").handler(n(u,s=>s.retry)),o(e,"cancel","W","cancel a run").argument("<run>","run id or its dev.azure.com URL").handler(n(u,s=>s.cancel))}var g=()=>import("./projects-GXIQO7HV.js"),F=()=>import("./policies-BZR5437X.js"),R=`<ref> is a branch (default: the repo's default branch), a tag as refs/tags/<name>, or a full
|
|
28
|
+
40-character commit SHA. Paths start at the repo root, with or without a leading /.`;function M(a){p(o(m(a,"project","projects"),"list","R","projects in the organization")).handler(n(g,e=>e.projects));let t=m(a,"repo","Git repositories");p(o(t,"list","R","repositories in the project")).handler(n(g,e=>e.repos)),o(t,"get","R","one repository").argument("<name>","repository name or id").handler(n(g,e=>e.repo)),o(t,"file","R","a file's content at a branch, tag or commit",{description:`a file's content at a branch, tag or commit
|
|
29
|
+
|
|
30
|
+
JSON output carries the content as text; -o table or tsv prints it raw. A binary file needs
|
|
31
|
+
--save.
|
|
32
|
+
|
|
33
|
+
${R}`}).argument("<repo>","repository name or id").argument("<path>").option("--ref <ref>").option("--save <file>","write the file here instead of printing it").handler(n(g,e=>e.file)),p(o(t,"tree","R","files and folders under a path, at a branch, tag or commit",{description:`files and folders under a path, at a branch, tag or commit
|
|
34
|
+
|
|
35
|
+
${R}`}).argument("<repo>","repository name or id").argument("[path]","folder (default: the root)","/").option("--ref <ref>").option("--one-level","only the folder's direct children")).handler(n(g,e=>e.tree)),p(o(t,"branches","R","branches with their latest commit, newest first",{description:`branches with their latest commit, newest first
|
|
36
|
+
|
|
37
|
+
Each has its name, commit, author, updated (when its latest commit was made) and message, and
|
|
38
|
+
ahead and behind: the commits it has that the base branch doesn't, and the reverse. The base
|
|
39
|
+
is the default branch (marked default) unless --base names another.`}).argument("<repo>","repository name or id").option("--name <pattern>","only these branches: * is a wildcard, a,b for several").option("--base <branch>","count ahead/behind against this branch")).handler(n(g,e=>e.branches)),p(o(t,"commits","R","commit history, newest first",{description:`commit history of a branch, tag or commit, newest first
|
|
40
|
+
|
|
41
|
+
<path> keeps the commits that changed that file or folder (renames aren't followed). --not-in
|
|
42
|
+
keeps the commits that aren't in another ref, like git log <not-in>..<ref>. --since and
|
|
43
|
+
--until go by commit date.
|
|
44
|
+
|
|
45
|
+
`+R}).argument("<repo>","repository name or id").argument("[path]","only commits that changed this file or folder").option("--ref <ref>").option("--not-in <ref>","only commits that aren't in this ref").option("--author <text>","author name or email contains this (ignoring case)").option("--since <when>","committed after: 30m, 12h, 7d, 2w or a date").option("--until <when>","committed before: 30m, 12h, 7d, 2w or a date").option("--work-items","add the work items linked to each commit")).handler(n(g,e=>e.commits)),o(t,"diff","R","changes between two branches, tags or commits (unified diff, or --stat)",{description:`changes between two branches, tags or commits (unified diff, or --stat)
|
|
46
|
+
|
|
47
|
+
Like a pull request, it shows what <target> changed since it split from <base> (git diff
|
|
48
|
+
base...target); --no-merge-base compares the two as they are. JSON output also has ahead
|
|
49
|
+
and behind (commits <target> has that <base> doesn't, and the reverse) and merge_base.
|
|
50
|
+
|
|
51
|
+
`+R}).argument("<repo>","repository name or id").argument("<base>","ref to compare from, e.g. main").argument("<target>","ref to compare, e.g. feature/x").option("--file <path>","only this file").option("--stat","list changed files only").addOption(new r("-U, --unified <n>","context lines (default 3)").argParser(d)).option("--no-merge-base","compare <base> and <target> directly").handler(n(g,e=>e.repoDiff)),o(t,"policies","R","branch policies and repository restrictions",{description:`branch policies and repository restrictions
|
|
52
|
+
|
|
53
|
+
Each has its id, type, required (blocking) or optional, enabled, branches (main, release/*,
|
|
54
|
+
or (default branch)) or none for a push restriction on the whole repository, all_repos for
|
|
55
|
+
a project-wide policy, and settings. --branch lists only the policies that apply to that
|
|
56
|
+
branch, including project-wide ones.`}).argument("<repo>","repository name or id").option("--branch <branch>","only the policies that apply to this branch").handler(n(F,e=>e.repoPolicies))}var h=()=>import("./prs-F2EVQJRV.js"),K=()=>import("./policies-BZR5437X.js"),J=["merge","squash","rebase","rebase-merge"],B=["active","pending","fixed","wont-fix","closed","by-design"];function W(a){return a.addOption(new r("--merge-strategy <strategy>","merge is a no-fast-forward merge").choices(J)).option("--delete-source-branch").option("--transition-work-items","move linked work items to their next state").option("--message <text|@file>","merge commit message").option("--conflict-authorship-commits","merge option: author conflict resolutions as their own commits").option("--no-renames","merge option: don't detect renames")}function H(a){let t=m(a,"pr","pull requests");p(o(t,"list","R","pull requests in the project (newest first)").option("--repo <name>").addOption(new r("--status <status>").choices(["active","completed","abandoned","all"]).default("active")).option("--creator <me|upn>").option("--reviewer <me|upn>").option("--source <branch>","only PRs from this branch").option("--target <branch>","only PRs into this branch")).handler(n(h,e=>e.list)),o(t,"get","R","pull request details, reviewers and status").argument("<pr>","PR id or its dev.azure.com URL").handler(n(h,e=>e.getOne)),o(t,"diff","R","changes in a pull request (unified diff, or --stat)").argument("<pr>","PR id or its dev.azure.com URL").option("--file <path>","only this file").option("--stat","list changed files only").addOption(new r("-U, --unified <n>","context lines (default 3)").argParser(d)).handler(n(h,e=>e.diff)),o(t,"checks","R","how each branch policy stands on a pull request",{description:`how each branch policy stands on a pull request
|
|
57
|
+
|
|
58
|
+
Each has its policy id (what pr auto-complete --ignore-policy takes for an optional one),
|
|
59
|
+
type, required, status (approved, queued, running, rejected or broken) and blocks: true when
|
|
60
|
+
it stops the PR from completing now. A build policy adds its run.`}).argument("<pr>","PR id or its dev.azure.com URL").option("--not-applicable","include policies that don't apply to this PR").handler(n(K,e=>e.prChecks)),o(t,"threads","R","comment threads").argument("<pr>","PR id or its dev.azure.com URL").option("--all","include system threads (votes, pushes)").handler(n(h,e=>e.threads)),o(t,"create","W","create a pull request").requiredOption("--repo <name>").requiredOption("--source <branch>").requiredOption("--target <branch>").requiredOption("--title <title>").option("--description <@file.md|text>","markdown body (max 4000 characters)").option("--draft").option("--work-item <id|url>[,...]","link work items (repeatable)",l).handler(n(h,e=>e.create)),o(t,"comment","W","add a comment, or reply to a thread").argument("<pr>","PR id or its dev.azure.com URL").requiredOption("--body <text|@file|->").addOption(new r("--thread <id>","reply to this thread").argParser(d)).option("--file <path>","comment on a file (new thread)").addOption(new r("--line <n>","line in --file").argParser(d)).addOption(new r("--end-line <n>","with --line: last line of the range").argParser(d)).addOption(new r("--status <status>","status of the new thread (default active)").choices(B)).handler(n(h,e=>e.comment)),f(o(t,"update","W","edit a pull request's title or description, or draft/publish it").argument("<pr>","PR id or its dev.azure.com URL").option("--title <title>").option("--description <@file.md|text>","markdown body (max 4000 characters)").option("--draft","make it a draft").option("--publish","publish a draft"),["--draft","--publish"]).handler(n(h,e=>e.update)),o(t,"link","W","link work items to a pull request").argument("<pr>","PR id or its dev.azure.com URL").requiredOption("--work-item <id|url>[,...]","",l).handler(n(h,e=>e.link)),o(t,"resolve","W","set a comment thread's status (default: fixed, shown as Resolved)").argument("<pr>","PR id or its dev.azure.com URL").argument("<thread>","thread id (from pr threads)",d).addOption(new r("--status <status>").choices(["fixed","wont-fix","closed","by-design"]).default("fixed")).handler(n(h,e=>e.resolve)),W(o(t,"auto-complete","W","turn auto-complete on (or --off) as the signed-in user",{description:`turn auto-complete on (or --off) as the signed-in user
|
|
61
|
+
|
|
62
|
+
Options the PR already has are kept unless given. Policies must pass first; there is no
|
|
63
|
+
bypass. --ignore-policy names optional policies (configuration ids) not to wait for.`}).argument("<pr>","PR id or its dev.azure.com URL").option("--off","turn auto-complete off")).option("--ignore-policy <id>[,<id>...]","optional policy configuration ids not to wait for").handler(n(h,e=>e.autoComplete)),W(o(t,"complete","W","complete (merge) a pull request now",{description:`complete (merge) a pull request now
|
|
64
|
+
|
|
65
|
+
Never bypasses branch policies: if a required policy isn't passing, it stops with exit 8.
|
|
66
|
+
Options the PR already has are kept unless given.`}).argument("<pr>","PR id or its dev.azure.com URL")).handler(n(h,e=>e.complete))}var c=()=>import("./workitems-UG5O3EGB.js"),_=a=>`${a}
|
|
67
|
+
|
|
68
|
+
Long-text fields (Description, Repro Steps, Acceptance Criteria, History, custom
|
|
69
|
+
HTML fields) are written as Markdown; --html writes HTML. A field takes the format
|
|
70
|
+
of the value written to it, so either one converts a field stored the other way.
|
|
71
|
+
--field Description=@desc.md reads the value from a file.`,I=["like","dislike","heart","hooray","smile","confused"];function D(a){let t=m(a,"wi","work items");o(t,"get","R","one work item").argument("<id>","work item id or its dev.azure.com URL").option("--fields <a,b>","only these fields (reference names)").option("--relations","include links").handler(n(c,e=>e.getOne)),f(p(o(t,"query","R","run WIQL (or a saved query) and fetch the items",{description:`Example: ppdo-cli ado wi query --wiql @active-bugs.wiql
|
|
72
|
+
ppdo-cli ado wi query --wiql "SELECT [System.Id] FROM WorkItems WHERE [System.State] = 'Active'"`}).option("--wiql <@file|text>").option("--saved <query id>").option("--fields <a,b>","fields to return (default: id, type, title, state, assignee, ...)")),["--wiql","--saved"],!0).handler(n(c,e=>e.query)),o(t,"create","W","create a work item",{description:_("create a work item")}).requiredOption("--type <type>","e.g. Task, Bug, 'User Story'").requiredOption("--title <title>").option("--field <name=value>","any field (repeatable); name=@file reads the value from a file",l).option("--parent <id|url>","parent work item").option("--assign <upn>").option("--html","long-text fields are HTML, not Markdown").handler(n(c,e=>e.create)),o(t,"update","W","update fields",{description:_("update fields")}).argument("<id>","work item id or its dev.azure.com URL").option("--field <name=value>","name=@file reads the value from a file",l).option("--state <state>").option("--title <title>").option("--assign <upn>").option("--add-tag <a,b>","add tags, keeping the others (repeatable)",l).option("--remove-tag <a,b>","remove tags, keeping the others (repeatable)",l).option("--html","long-text fields are HTML, not Markdown").handler(n(c,e=>e.update)),o(t,"attachments","R","a work item's attached files; --save downloads them",{description:`a work item's attached files; --save downloads them
|
|
73
|
+
|
|
74
|
+
Each has its id, name, size (bytes), added and comment. --save <dir> downloads them into
|
|
75
|
+
the folder (a second file with the same name gets ' (2)'); --name picks some.`}).argument("<id>","work item id or its dev.azure.com URL").option("--name <pattern>","only these files: * is a wildcard, a,b for several").option("--save <dir>","download into this folder").handler(n(c,e=>e.attachments)),p(o(t,"tags","R","the tags defined in the project",{description:`the tags defined in the project, by name
|
|
76
|
+
|
|
77
|
+
A tag stays listed for a while after the last work item loses it.`})).handler(n(c,e=>e.tags)),f(o(t,"comment","W","add a comment, or edit or delete one of yours",{description:`add a comment, written in Markdown (--html for HTML)
|
|
78
|
+
|
|
79
|
+
--edit <comment> replaces a comment's text; --delete <comment> deletes it, which is an HTTP
|
|
80
|
+
DELETE, so it needs mode 'full'. <comment> is an id from wi comments. Only a comment's
|
|
81
|
+
author can edit or delete it.`}).argument("<id>","work item id or its dev.azure.com URL").option("--body <text|@file|->","the comment (not with --delete)").option("--html","the comment is HTML, not Markdown").addOption(new r("--edit <comment>","replace this comment's text with --body").argParser(d)).addOption(new r("--delete <comment>","delete this comment").argParser(d)),["--edit","--delete"]).handler(n(c,e=>e.comment)),p(o(t,"queries","R","saved queries, by path",{description:`saved work item queries (Shared Queries and My Queries), by path
|
|
82
|
+
|
|
83
|
+
Each has its id (for wi query --saved), name, path, type (flat, tree or oneHop), shared and
|
|
84
|
+
modified. <folder> lists only the queries under it; --name finds queries whose name contains
|
|
85
|
+
the text, at any depth; --wiql adds each query's WIQL.`}).argument("[folder]","e.g. 'Shared Queries/Team'").option("--name <text>","names containing this (ignoring case)").option("--wiql","include each query's WIQL")).handler(n(c,e=>e.queries)),p(o(t,"comments","R","a work item's comments, newest first",{description:`a work item's comments, newest first
|
|
86
|
+
|
|
87
|
+
Each has its id, author, created (and modified, when edited), format (markdown or html)
|
|
88
|
+
and text. Deleted comments are left out. --reactions adds each comment's reaction counts
|
|
89
|
+
and the ones you've added.`}).argument("<id>","work item id or its dev.azure.com URL").option("--reactions","include reaction counts")).handler(n(c,e=>e.comments)),o(t,"fields","R","the fields a work item type has, with allowed values",{description:`the fields a work item type has, with allowed values
|
|
90
|
+
|
|
91
|
+
Each has its name, reference_name, type and whether it is required; when they apply, its
|
|
92
|
+
default, allowed_values (dropdowns), other_values_allowed (a list that takes others too),
|
|
93
|
+
long_text (written as Markdown), identity (a user) and read_only. State's values come in
|
|
94
|
+
workflow order, with each state's category under states.`}).requiredOption("--type <type>","e.g. Task, Bug, 'User Story'").option("--required","only required fields").option("--name <pattern>","only these fields: name or reference name, * is a wildcard, a,b for several (e.g. State, 'Microsoft.VSTS.*')").handler(n(c,e=>e.fields)),o(t,"react","W","add a reaction to a comment, or remove yours",{description:`add a reaction to a comment, or remove yours with --remove
|
|
95
|
+
|
|
96
|
+
<comment> is a comment id from wi comments. --remove sends a DELETE, so it needs mode 'full'.`}).argument("<id>","work item id or its dev.azure.com URL").argument("<comment>","comment id",d).addArgument(new P("<reaction>",I.join(" | ")).choices(I)).option("--remove","remove your reaction instead").handler(n(c,e=>e.react)),f(o(t,"link","W","link a work item to a pull request or a commit").argument("<id>","work item id or its dev.azure.com URL").option("--pr <id|url>","pull request").option("--commit <sha|url>","commit (a SHA needs --repo; a URL names its repo)").option("--repo <name>","with --commit <sha>: the repository"),["--pr","--commit"],!0).handler(n(c,e=>e.link))}function Se(a){let t=m(a,"ado","Azure DevOps",["devops"]);o(t,"api","M","any REST request (auth, retries, paging and errors handled)").addHelpText("after",`
|
|
97
|
+
Paths are relative to https://dev.azure.com/<org>/; {project} is replaced with the
|
|
98
|
+
environment's project. api-version defaults to 7.1 (not added for Analytics OData).
|
|
99
|
+
Examples:
|
|
100
|
+
ppdo-cli ado api GET _apis/projects
|
|
101
|
+
ppdo-cli ado api GET {project}/_apis/build/builds --param '$top=5'
|
|
102
|
+
ppdo-cli ado api GET _apis/graph/users --host vssps
|
|
103
|
+
ppdo-cli ado api POST {project}/_apis/wit/wiql --body @query.json`).addArgument(S(j)).argument("<path>").option("--body <@file|-|json>","request body: @file, - for stdin, or inline JSON").option("--header <k:v>","extra header (repeatable)",l).option("--param <k=v>","query parameter (repeatable)",l).option("--api-version <v>","default 7.1").addOption(new r("--host <host>","DevOps host (default: core = dev.azure.com)").choices(z).default("core")).option("--paginate","follow continuation tokens; items are the output").addOption(new r("--limit <n>","stop after n items (with --paginate)").argParser(d)).option("--save <file>","write the response body to a file").handler(async e=>(await import("./api-7RAWLIQV.js")).api(e)),M(t),C(t),H(t),D(t),A(t)}export{Se as register};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as V,b as j,c as P,d as R}from"./chunk-LL4XQ3L7.js";import"./chunk-UCTMKA2J.js";import{w,y as h}from"./chunk-BALEFXOL.js";import{b as k}from"./chunk-5SBBTR3Y.js";import{e as g}from"./chunk-S4KF5Z3S.js";import{a as y,b as v}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";function x(n){return/_apis\/wit\/workitems\/(\$|%24)?[^/?]+\/?(\?|$)/i.test(n)}async function C(n,e,o){let{DevOps:r}=await import("./service-4VHAPTA6.js"),s=await n.client("devops"),c=s.target.env;return s.service=new r({org:c.org,project:c.project},e,o),s}async function I(n){let e=n.args,o=String(e.method),r=String(e.path),s=typeof e.apiVersion=="string"&&e.apiVersion?e.apiVersion:null,c=typeof e.limit=="number"?e.limit:null,a=V(e.header);j(a);let m=h(typeof e.body=="string"?e.body:null);m!==null&&!Object.keys(a).some(t=>t.toLowerCase()==="content-type")&&(P(m,a),(o==="POST"||o==="PATCH")&&x(r)&&(a["Content-Type"]="application/json-patch+json"));let d=await C(n,typeof e.host=="string"?e.host:"core",s);k(n,d,o,r,m);let u=w(e.param,"--param");if(e.paginate&&o!=="GET")throw new v("--paginate only applies to GET");let f=await import("./service-4VHAPTA6.js"),l=async()=>{if(e.paginate){let i=d.paginate(r,{params:u,headers:a,limit:c,nextLink:f.nextUrl,items:f.items});return{kind:"stream",first:await i.next(),stream:i}}let t=typeof e.save=="string"?e.save:null;return{kind:"resp",resp:await d.request(o,r,{params:u,headers:a,body:m,saveTo:t})}},p;try{p=await l()}catch(t){if(!(t instanceof y)||t.code!=="VssInvalidPreviewVersionException"||s)throw t;let i=d.service;i.apiVersion=i.apiVersion+"-preview",g(`note: this endpoint needs a preview api-version; retried with ${i.apiVersion}`),p=await l()}if(p.kind==="stream"){let{first:t,stream:i}=p;async function*b(){t.done||(yield t.value),yield*i}await n.emitStream(b());return}await R(n,p.resp,!1)}export{I as api,x as isWorkItemPath};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a,b,c,d,e}from"./chunk-LL4XQ3L7.js";import"./chunk-UCTMKA2J.js";import"./chunk-BALEFXOL.js";import"./chunk-5SBBTR3Y.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";export{e as api,c as checkJsonBody,d as emitResponse,b as forbiddenHeaders,a as headerDict};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{e as o,o as a,r as t}from"./chunk-BALEFXOL.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var s=["dv","dataverse","ado","devops"];function p(d){let n=a(d,"auth","sign in, sign out, tokens"),i=()=>import("./run-ICS4FNZA.js");t(n,"login","L","interactive sign-in for an identity",{description:`ppdo-cli auth login <identity> sign in one identity
|
|
3
|
+
ppdo-cli auth login --service ado sign in the identity the default DevOps environment uses
|
|
4
|
+
ppdo-cli auth login --env <name> sign in the identity that environment's group uses
|
|
5
|
+
ppdo-cli auth login sign in every identity the default environments need that
|
|
6
|
+
has no valid session`}).argument("[identity]").argKey("identity","name").addOption(new o("--service <service>").choices(s)).option("--device-code","use the device code flow this time").option("--expires <date>","pat only: the PAT's expiry date (YYYY-MM-DD), to be warned before it ends").handler(async e=>(await i()).login(e)),t(n,"logout","L","delete an identity's token caches").argument("[identity]").argKey("identity","name").option("--all","every identity").handler(async e=>(await i()).logout(e)),t(n,"status","L","sign-in state and cached tokens per identity").argument("[identity]").argKey("identity","name").handler(async e=>(await i()).status(e)),t(n,"token","L","print an access token for scripts (curl, PowerShell)").addOption(new o("--service <service>").choices(s)).option("--scope <scope>","any other resource scope, e.g. https://graph.microsoft.com/.default").option("--show","print even when stdout is a terminal").handler(async e=>(await i()).token(e))}export{p as register};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as g}from"./chunk-BCAXUZIO.js";import"./chunk-I3TMFYRJ.js";import{a as d}from"./chunk-MK6QZ4ES.js";import"./chunk-STWQDANK.js";import{b as l}from"./chunk-MBNUMAAZ.js";import"./chunk-LB7WNZVK.js";import"./chunk-4KP27OCL.js";import"./chunk-J4R6QXW7.js";import"./chunk-5SBBTR3Y.js";import"./chunk-WMDKJRDC.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import{b as m,c as p}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{execFile as x}from"node:child_process";import{statSync as h}from"node:fs";import{delimiter as E,extname as b,join as y}from"node:path";var v=12e4;function A(t){let n=d();return t.configDir&&(n.AZURE_CONFIG_DIR=g(t.configDir)),n}function w(t){return`run: ${t.configDir?`AZURE_CONFIG_DIR=${t.configDir} `:""}az login --tenant ${t.tenant}`}function I(t){let n=process.platform==="win32"?(process.env.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(o=>o):[""];for(let o of(process.env.PATH||"").split(E))if(o)for(let i of b(t)?[""]:n){let e=y(o,t+i);try{if(h(e).isFile())return e}catch{}}return null}function _(t,n,o){let i=t,e=n,s=!1;if(process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)){for(let r of[t,...n])if(/["%\r\n]/.test(r))throw new m(`cannot pass '${r}' to az safely`);i=process.env.ComSpec||"cmd.exe",e=["/d","/s","/c",`"${[t,...n].map(r=>`"${r}"`).join(" ")}"`],s=!0}return new Promise(r=>{x(i,e,{env:o,timeout:v,windowsHide:!0,windowsVerbatimArguments:s,maxBuffer:16<<20},(c,a,u)=>{let f=c;r({code:f?typeof f.code=="number"?f.code:1:0,stdout:String(a),stderr:String(u),timedOut:!!f?.killed})})})}async function D(t,n){let o=I("az");if(!o)throw new m("method 'az_cli' needs the Azure CLI on PATH",{hint:"install it, or use --method browser"});let i=["account","get-access-token","--scope",n,"--output","json"];t.tenant&&i.push("--tenant",t.tenant);let e=await _(o,i,A(t));if(e.timedOut)throw new p("az account get-access-token timed out",{hint:w(t)});if(e.code!==0){let a=e.stderr.split(/\r?\n/).map(u=>u.trim()).find(u=>u)??"az failed";throw new p(`az could not get a token for identity '${t.name}': ${a}`,{hint:w(t)})}let s=JSON.parse(e.stdout),r=s.accessToken,c=s.expires_on;if(c==null){let a=l(r)?.exp;c=typeof a=="number"?a:Date.now()/1e3+300}return[r,Number(c),s.tenant??null]}export{v as AZ_TIMEOUT_MS,D as acquire,w as loginHint,I as which};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as R}from"./chunk-WNQERCOO.js";import"./chunk-4KP27OCL.js";import"./chunk-J4R6QXW7.js";import"./chunk-5SBBTR3Y.js";import"./chunk-WMDKJRDC.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import{j as $}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{randomUUID as x}from"node:crypto";var S=["POST","PUT","PATCH","DELETE"];function w(){return{status:0,error:"no response (stopped after an earlier error)"}}var c=`\r
|
|
3
|
+
`;function y(){return x().replace(/-/g,"")}function C(u,p,o,e){let t=[`${u} ${p} HTTP/1.1`,"Accept: application/json"];for(let[s,r]of Object.entries(e??{}))t.push(`${s}: ${r}`);if(["POST","PUT","PATCH"].includes(u)&&o!==null&&o!==void 0){let s=$(o,!1);return t.push("Content-Type: application/json",`Content-Length: ${Buffer.byteLength(s,"utf8")}`,"",s),t.join(c)}return t.join(c)+c}function T(u,p,o,e,t=null){let s=["Content-Type: application/http","Content-Transfer-Encoding: binary"];return t!==null&&s.push(`Content-ID: ${t}`),s.join(c)+c+c+C(u,p,o,e)}function H(u,p,o){let e=`batch_${y()}`,t=[],s=[],r=[],i=n=>n.includes("://")?n:p+(n.startsWith("/")?n:R+n),l=()=>{if(!r.length)return;let n=`changeset_${y()}`,g=r.map(([,a],h)=>`--${n}${c}${T(a.method,i(a.path),a.body,a.headers,h+1)}${c}`).join("");t.push(`Content-Type: multipart/mixed; boundary=${n}${c}${c}${g}--${n}--`),s.push(r.map(([a])=>a)),r=[]};u.forEach((n,g)=>{if(o&&S.includes(n.method)){r.push([g,n]);return}l(),t.push(T(n.method,i(n.path),n.body,n.headers)),s.push([g])}),l();let d=t.map(n=>`--${e}${c}${n}${c}`).join("")+`--${e}--${c}`;return[e,d,s]}function P(u){return u.replace(/^[\r\n]+|[\r\n]+$/g,"")}function j(u,p){let o=[];for(let e of u.split(`--${p}`)){if(e=P(e),!e||e==="--")continue;let t=/\r?\n\r?\n/.exec(e),s=t?e.slice(0,t.index):e,r=t?e.slice(t.index+t[0].length):"";if(s.toLowerCase().includes("multipart/mixed")){let f=/boundary=([^\s;]+)/.exec(s);f&&o.push(j(r,f[1]).flat());continue}let i=r.split(/\r?\n/),l=i.findIndex(f=>f.startsWith("HTTP/1."));if(l<0){r.trim()&&o.push([{status:0,error:"unparseable sub-response",raw:r.trim().slice(0,200)}]);continue}let d=i[l].split(" ")[1],n=d!==void 0&&/^\s*[+-]?\d+\s*$/.test(d)?parseInt(d,10):0;Number.isNaN(n)&&(n=0);let g={},a=l+1;for(;a<i.length&&i[a].trim();){let f=i[a],m=f.indexOf(":");m>=0&&(g[f.slice(0,m).trim().toLowerCase()]=f.slice(m+1).trim()),a++}let h=i.slice(a+1).join(`
|
|
4
|
+
`).trim(),b=null;if(h)try{b=JSON.parse(h)}catch{b=h}o.push([{status:n,headers:g,body:b}])}return o}function L(u,p,o){let e=Array.from({length:o},()=>w()),t=Math.min(u.length,p.length);for(let s=0;s<t;s++){let r=u[s],i=p[s];if(i.length===r.length)r.forEach((l,d)=>{e[l]=i[d]});else if(i.length){let l={...i[0]};r.length>1&&(l.rolled_back=!0);for(let d of r)e[d]=l}}return e}export{S as WRITE_METHODS,H as build,L as distribute,w as noResponse,j as parse};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as y,b as S,d as L,e as F}from"./chunk-JEAIFLEN.js";import{a as M}from"./chunk-JAGU2NM5.js";import{Y as m,ca as b}from"./chunk-TZSB4PR7.js";import{b as k,g as A}from"./chunk-ZNJ4DRCA.js";import{e as O,o as T,p as C,q as X,t as $}from"./chunk-WIA546AL.js";import{a as v}from"./chunk-MK6QZ4ES.js";import"./chunk-STWQDANK.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{spawnSync as B}from"node:child_process";import{existsSync as U,readdirSync as D,readFileSync as E,statSync as x}from"node:fs";import*as p from"node:path";function I(i){let t=C(i),o=p.dirname(i),s=[];for(let n of L(t,"ProjectReference")){let r=n.get("Include");r&&s.push(S(o,r))}let e=F(t,"SolutionPackageMapFilePath");return{package_type:F(t,"SolutionPackageType"),map_file:e?S(o,e):null,references:s}}function _(i){let t=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of(process.env.PATH??"").split(p.delimiter))if(o)for(let s of t){let e=p.join(o,i+s.toLowerCase());try{if(x(e).isFile())return e}catch{}}return null}function G(){let i=_("dotnet");if(i===null)throw new m("building the project's references needs the .NET SDK (dotnet) on PATH");return i}function H(i,t,o,s){if(!U(i))throw new m(`the referenced project ${i} doesn't exist`);let n=["msbuild",i,"-nologo",`-t:${o?"Build;GetProjectOutputPath":"GetProjectOutputPath"}`,`-p:Configuration=${t}`,"-getTargetResult:GetProjectOutputPath"];o&&n.splice(2,0,"-restore"),s(`${o?"building":"reading"} ${p.basename(i)} (${t})`);let r=B(G(),n,{encoding:"utf8",stdio:["ignore","pipe","pipe"],env:v(),maxBuffer:256*1024*1024});if(r.error)throw r.error;let c=r.stdout??"",u=r.stderr??"",l=c.trim(),f=null;try{f=l.includes("{")?JSON.parse(l.slice(l.indexOf("{"))):null}catch{f=null}let d=f?.TargetResults?.GetProjectOutputPath??{};if(r.status!==0||d.Result!=="Success"){let a=(c+`
|
|
3
|
+
`+u).split(/\r\n|\r|\n/).filter(w=>w.toLowerCase().includes("error")),g=[...new Set(a.slice(0,5).map(w=>w.trim()))].join("; ")||l.slice(-500)||"no output";throw new m(`building ${i} failed: ${g}`)}let h=[];for(let a of d.Items??[]){let g=a.FullPath||a.Identity||"",w=a.PowerAppsComponentType||"";if(!w)throw new m(`${i} gives output ${g} without a PowerAppsComponentType (only PCF and plug-in projects can be referenced)`);h.push([g,w])}return h}function R(i){let t=[],o=s=>{let e;try{e=D(s,{withFileTypes:!0})}catch{return}e.sort((n,r)=>b(n.name.toUpperCase(),r.name.toUpperCase()));for(let n of e)n.isDirectory()||t.push(y(s,n.name));for(let n of e)n.isDirectory()&&o(y(s,n.name))};return o(i),t}function z(i,t){return R(i).find(o=>p.basename(o).toLowerCase()===t.toLowerCase())??null}function N(i,t){return p.relative(t,i).split(p.sep).join("/")}var j=class{constructor(t){this.root=t}files=new Map;solution=null;sol(){return this.solution??=X(p.join(this.root,"Other","Solution.xml"))}exists(t){let o=t.toLowerCase();if([...this.files.keys()].some(s=>s.toLowerCase()===o))return!0;try{return x(p.join(this.root,...t.split("/"))).isFile()}catch{return!1}}result(){let t=new Map(this.files);return this.solution!==null&&t.set("Other/Solution.xml",$(this.solution)),t}addControls(t){let o=!1;try{o=x(t).isDirectory()}catch{o=!1}if(!o)throw new m(`the PCF project's output folder ${t} doesn't exist; build it first`);let s=null,e=this.sol().root.element("SolutionManifest"),n=e!==null?e.element("Publisher"):null;n!==null&&n.element("CustomizationPrefix")!==null&&(s=n.element("CustomizationPrefix").value);let r=[],c=D(t,{withFileTypes:!0}).sort((u,l)=>b(u.name.toUpperCase(),l.name.toUpperCase()));for(let u of c){if(!u.isDirectory())continue;let l=y(t,u.name),f=z(l,"ControlManifest.xml");if(f===null)throw new m(`ControlManifest.xml not found for the control in ${l}`);let d=C(f).element("control");if(d===null||!d.get("namespace")||!d.get("constructor"))throw new m(`${f} has no control namespace and constructor`);let h=`${d.get("namespace")}.${d.get("constructor")}`,a=s?`${s}_${h}`:h,g=`Controls/${a}`;for(let P of R(l))this.files.set(`${g}/${N(P,l)}`,new Uint8Array(E(P)));let w=`${g}/ControlManifest.xml.data.xml`;if(!this.exists(w)){let P="/"+k(g,N(f,l));this.files.set(w,$(T(Buffer.from(`<CustomControl><Name>${a}</Name><FileName>${P}</FileName></CustomControl>`,"utf8"))))}this.addRoot("66",a),r.push(a)}return r}addRoot(t,o){let s=this.sol().root.element("SolutionManifest"),e=s!==null?s.element("RootComponents"):null;if(e===null)throw new m("Other/Solution.xml has no RootComponents");let n=e.elements("RootComponent");if(n.some(a=>a.get("type")===t&&a.get("schemaName")===o))return;let r=new O("RootComponent",[["type",t],["schemaName",o],["behavior","0"]],null,{empty:!0,ns:e.ns,scope:e.scope});r.parent=e;let c=a=>{let g=(a.get("type")??"").trim();return g&&/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(g)?Number(g):NaN},u=Number(t),l=n.filter(a=>c(a)===u),f=n.filter(a=>c(a)>u),d=n.filter(a=>c(a)<u),h;l.length?h=e.kids.indexOf(l[l.length-1])+1:f.length?h=e.kids.indexOf(f[0]):d.length?h=e.kids.indexOf(d[d.length-1])+1:h=e.kids.length,e.kids.splice(h,0,r),e.empty=!1}addPlugin(t){let o=!1;try{o=x(t).isFile()}catch{o=!1}if(!o)throw new m(`the plug-in project's output ${t} doesn't exist; build it first`);let s=new Uint8Array(E(t)),e=M(s);if(e===null)throw new m(`${t} is not a .NET assembly`);let n=y(this.root,"PluginAssemblies");for(let r of R(n)){if(!r.toLowerCase().endsWith("dll.data.xml"))continue;let c=C(r);if((c.get("FullName")??"").toLowerCase()!==e.toLowerCase())continue;let u=c.element("FileName"),l=(u!==null?u.value:"")||"",f=N(r.slice(0,-9),this.root);return l&&(f=A(l.replaceAll("\\","/"))),this.files.set(f,s),f}throw new m(`no plug-in assembly in ${n} is registered as ${e}; the assembly's name, version and key must match a PluginAssemblies/**/*.dll.data.xml`)}};function tt(i,t,o,s=!0,e=n=>process.stderr.write(n+`
|
|
4
|
+
`)){let n=new j(t),r=[];for(let c of I(i).references)for(let[u,l]of H(c,o,s,e))if(l.toLowerCase()==="pcf")r.push({project:c,type:"pcf",controls:n.addControls(u)});else if(l.toLowerCase()==="plugin")r.push({project:c,type:"plugin",assembly:n.addPlugin(u)});else throw new m(`${c}: component type ${l} is not supported (only Pcf and Plugin)`);return[n.result(),r]}export{j as Overlay,tt as buildProject,H as buildReference,I as settings};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as W}from"./chunk-KBQYSAJX.js";import{p as O}from"./chunk-BODUSF3V.js";import{C as S,D as p,E as P,M as Z,O as F,P as B,Q as V,a as k,b as x,d as H,e as A,f as U,g as v,m,o as w,p as _,q as R,r as z}from"./chunk-TXVNEV3M.js";import{a as T}from"./chunk-UCTMKA2J.js";import{b as M}from"./chunk-WNQERCOO.js";import{y as J}from"./chunk-BALEFXOL.js";import"./chunk-4KP27OCL.js";import"./chunk-J4R6QXW7.js";import{b as j}from"./chunk-5SBBTR3Y.js";import"./chunk-WMDKJRDC.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import{a as E,b as f,d as G,j as D}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var K=/^([A-Za-z_][A-Za-z0-9_]*)\((.+)\)\n?$/;function tt(t){let n=F(J(t).toString("utf8")).trim(),e;if(n.startsWith("["))try{e=T(n)}catch(r){throw new f(`--body is not valid JSON: ${r.message}`)}else{let r=[];W(n).forEach((i,a)=>{if(i.trim())try{r.push(T(i))}catch(s){throw new f(`line ${a+1}: not JSON (${s.message})`)}}),e=r}let o=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);if(!Array.isArray(e)||!e.length||!e.every(o))throw new f("--body needs one JSON object per row");return e}function et(t){return typeof t=="boolean"?t?"true":"false":typeof t=="number"?String(t):A(String(t))}function nt(t,n,e,o,r){return t.map((i,a)=>{let s=a+1,l,d;if(e&&e.length){let c=e.filter(u=>i[u]===null||i[u]===void 0||i[u]==="");if(c.length)throw new f(`row ${s} has no value for ${c.join(", ")}`);l=`${n}(`+e.map(u=>`${u}=${et(i[u])}`).join(",")+")",d=Object.fromEntries(Object.entries(i).filter(([u])=>!e.includes(u)))}else{let c=i[o];if(!x(m(c)?String(c):""))throw new f(`row ${s} has no ${o}`,{hint:"pass --key <columns> to match on an alternate key"});l=`${n}(${H(String(c))})`,d=Object.fromEntries(Object.entries(i).filter(([u])=>u!==o))}return{method:"PATCH",path:`${l}?$select=${o}`,body:d,headers:{Prefer:"return=representation",...r}}})}var rt={201:"created",200:"updated",204:"updated"};async function Q(t,n,e){let o=await p(t,n,"GET",`EntityDefinitions(LogicalName='${e}')`,{params:[["$select","PrimaryIdAttribute"]]}),r=P(o).PrimaryIdAttribute;if(r===void 0)throw new E("'PrimaryIdAttribute'");return r}async function pt(t){let n=t.args,e=k(B(n.entityset),"entity set name"),o=tt(String(n.body)),r=m(n.key)?String(n.key).split(",").map(c=>c.trim()).filter(c=>c):null,i=await S(t),a=await i.lookups(async()=>Q(t,i,await O(t,i,e))),s=nt(o,e,r,a,Z(t,i)),l=[];for await(let[c,u,N]of V(t,i,s,!1,!!n.continueOnError))for(let h=0;h<u.length;h++){let q=c+h,y=N[h],C=o[q],$=w(y,"status"),b={row:q+1,key:r&&r.length?Object.fromEntries(r.map(L=>[L,C[L]??null])):w(C,a),status:m($)?$:null,action:rt[$]??null},g=w(y,"body"),I=typeof g=="object"&&g!==null&&!Array.isArray(g);I&&m(g[a])&&(b.id=g[a]),I&&"error"in g?b.error=M(w(_(g.error),"message"))??null:(m(y.error)||!m($))&&(b.error=m(y.error)?y.error:"not run (an earlier row failed)"),l.push(z(b))}await t.emit(l);let d=l.filter(c=>"error"in c||(c.status||0)>=400);if(d.length)throw new E(`${d.length} of ${l.length} rows failed or didn't run`,{service:"dataverse",hint:"see each row's error"+(n.continueOnError?"":"; --continue-on-error keeps going after a failure")})}function X(t,n){let e=K.exec(U(n));if(!e)throw new f(`'${n}' is not a record reference`,{hint:"e.g. contacts(<id>) or contacts(name=value)"});let o=e[2].replace(/=\s*'((?:[^']|'')*)'/g,(i,a)=>"="+a.split("''").join("'"));return`${t.service.origin}/api/data/v9.2/${v(e[1],o)}`}async function ot(t,n,e){let o=e.indexOf("/api/data/v9.2/"),r=e.slice(0,o),i=e.slice(o+15),a=K.exec(i);if(x(a[2]))return e;let s=a[1],l=await Q(t,n,await O(t,n,s)),d=P(await p(t,n,"GET",i,{params:[["$select",l]]}))[l];if(d===void 0)throw new E(`'${l}'`);return`${r}/api/data/v9.2/${s}(${d})`}async function Y(t,n,e,o){k(o,"navigation property");let r=await O(t,n,e),i=`EntityDefinitions(LogicalName='${r}')`,a=A(o),s=async(u,N)=>P(await p(t,n,"GET",`${i}/${u}`,{params:[["$select","SchemaName"],["$filter",N]]})),l=await s("ManyToOneRelationships",`ReferencingEntityNavigationPropertyName eq ${a}`);if(R(l.value).length)return!0;let d=await s("OneToManyRelationships",`ReferencedEntityNavigationPropertyName eq ${a}`),c=await s("ManyToManyRelationships",`Entity1NavigationPropertyName eq ${a} or Entity2NavigationPropertyName eq ${a}`);if(R(d.value).length||R(c.value).length)return!1;throw new G(`${r} has no navigation property '${o}'`,{service:"dataverse",hint:`run: ppdo-cli dv metadata get ${r} --relationships`})}async function yt(t){let n=t.args,e=await S(t),o=v(String(n.entityset),String(n.id));j(t,e,"POST",o,Buffer.from("{}"));let r=X(e,String(n.target)),i=String(n.navigation),a=await e.lookups(()=>Y(t,e,String(n.entityset),i)),s=Buffer.from(D({"@odata.id":r}),"utf8");await p(t,e,a?"PUT":"POST",`${o}/${i}/$ref`,{body:s}),await t.emit({record:o,navigation:i,target:r.slice(r.indexOf("/v9.2/")+6),linked:!0})}async function wt(t){let n=t.args,e=await S(t),o=v(String(n.entityset),String(n.id));j(t,e,"DELETE",o,null);let r=String(n.navigation),i=await e.lookups(()=>Y(t,e,String(n.entityset),r)),a=B(n.target);if(i)await p(t,e,"DELETE",`${o}/${r}/$ref`);else{if(!a)throw new f(`${r} is a collection: name the record to unlink, e.g. contacts(<id>)`);let s=X(e,a),l=await e.lookups(()=>ot(t,e,s));await p(t,e,"DELETE",`${o}/${r}/$ref`,{params:[["$id",l]]})}await t.emit({record:o,navigation:r,target:a,unlinked:!0})}export{yt as associate,wt as disassociate,et as literal,tt as readRows,X as targetUrl,pt as upsert,nt as upsertRequests};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as se,e as P}from"./chunk-J4R6QXW7.js";import{a as ne}from"./chunk-5SBBTR3Y.js";import{a as ee}from"./chunk-WMDKJRDC.js";import{i as re}from"./chunk-H4OY4EFC.js";import{a as te}from"./chunk-TQLZ3TRU.js";import{a as O,c as L,d as X,e as V,f as K,g as Z,h as Q}from"./chunk-WXOTXJNG.js";import{execFileSync as Te}from"node:child_process";import{createWriteStream as xe,mkdirSync as Se,readdirSync as ve,readFileSync as G,statSync as be}from"node:fs";import F from"node:http";import U from"node:https";import{pipeline as _e}from"node:stream/promises";import J from"node:tls";import{dirname as Ce,join as ge,resolve as Ae}from"node:path";var Oe=`ppdo-cli/${ee}`,$e=new Set([429,502,503,504]),B=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),oe=60,Le=2,I=6,Ne=300,M=class{constructor(e,t,n,s,i,o=null){this.status=e;this.reason=t;this.headers=n;this.body=s;this.url=i;this.savedTo=o}header(e){return this.headers[e.toLowerCase()]??null}get text(){return this.body.toString("utf8")}json(){return this.body.length?JSON.parse(this.body.toString("utf8")):null}get isJson(){return(this.header("content-type")??"").includes("json")}},D,H="";function ie(r){return r.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g)??[]}function ke(){let r=[],e=process.env.SSL_CERT_FILE;if(e)try{r.push(...ie(G(e,"latin1")))}catch{}let t=process.env.SSL_CERT_DIR;if(t)for(let n of t.split(process.platform==="win32"?";":":")){let s=[];try{s=ve(n)}catch{continue}for(let i of s)try{let o=ge(n,i);be(o).isFile()&&r.push(...ie(G(o,"latin1")))}catch{}}return r}function Ue(){let r=J;if(typeof r.getCACertificates!="function")return H="this Node cannot read the OS certificate store",null;let e=new Set;for(let t of["default","system"])try{for(let n of r.getCACertificates(t))e.add(n.trim())}catch(n){t==="system"&&(H=`cannot read the OS certificate store (${n.message})`)}for(let t of ke())e.add(t.trim());return[...e]}function He(){if(D===void 0){let r=Ue();try{D=r?J.createSecureContext({ca:r}):null}catch(e){H=`cannot load the certificate roots (${e.message})`,D=null}}return D??void 0}function Pe(){let r="behind TLS inspection? the proxy's root CA must be in the OS store, or set SSL_CERT_FILE";return H?`${r}; ${H}: set NODE_USE_SYSTEM_CA=1`:r}var Ie=new Set(["UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","CERT_UNTRUSTED","CERT_REVOKED","CERT_SIGNATURE_FAILURE","CERT_CHAIN_TOO_LONG","HOSTNAME_MISMATCH"]);function me(r){let e=r,t=typeof e?.code=="string"?e.code:"";return Ie.has(t)||t.startsWith("ERR_SSL_")||t.startsWith("ERR_TLS_")||e?.library==="SSL routines"}var De="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",C;function Fe(r){let e={};for(let t of r.split(/\r?\n/)){let n=/^\s+(\S(?:.*?\S)?)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/.exec(t);if(!n)continue;let[,s="",i="",o=""]=n;e[s]=i==="REG_DWORD"||i==="REG_QWORD"?String(parseInt(o.trim(),16)||0):o.trim()}return e}function Me(r){if(!Number(r.ProxyEnable??"0"))return[{},[]];let e=r.ProxyServer??"",t=r.ProxyOverride??"",n={};if(e.includes("="))for(let s of e.split(";")){let i=s.indexOf("=");i>=0&&(n[s.slice(0,i).trim().toLowerCase()]=s.slice(i+1).trim())}else e&&(n={http:e,https:e});return[n,t.split(";").map(s=>s.trim()).filter(s=>s)]}var qe=3600;function ye(){return ge(te(),"proxy-registry.json")}function Ge(){try{let r=JSON.parse(G(ye(),"utf8"));return typeof r.checked!="number"||Date.now()/1e3-r.checked>qe||r.checked>Date.now()/1e3+60||typeof r.proxies!="object"||r.proxies===null||!Array.isArray(r.override)?null:[r.proxies,r.override.map(String)]}catch{return null}}function Ee(){let r="";try{r=Te("reg.exe",["query",De],{encoding:"utf8",windowsHide:!0,timeout:5e3,stdio:["ignore","pipe","ignore"]})}catch{r=""}let e=Me(Fe(r));try{re(ye(),JSON.stringify({checked:Math.trunc(Date.now()/1e3),proxies:e[0],override:e[1]}))}catch{}return e}function Be(){if(process.platform!=="win32")return[{},[]];if(C)return C.value;let r=Ge();return C=r?{value:r,cached:!0}:{value:Ee(),cached:!1},C.value}function ze(){if(process.platform!=="win32"||!C?.cached)return!1;let r=JSON.stringify(C.value);return C={value:Ee(),cached:!1},JSON.stringify(C.value)!==r}function je(r,e){let t="";for(let n=0;n<e.length;n++){let s=e[n];if(s==="*")t+=".*";else if(s==="?")t+=".";else if(s==="["){let i=e.indexOf("]",n+2);if(i<0)t+="\\[";else{let o=e.slice(n+1,i).replace(/\\/g,"\\\\");o.startsWith("!")?o="^"+o.slice(1):o.startsWith("^")&&(o="\\"+o),t+=`[${o}]`,n=i}}else t+=s.replace(/[.+^${}()|\\/]/g,"\\$&")}return new RegExp(`^${t}$`,"s").test(r)}function ae(r,e){r=r.toLowerCase();for(let t of e)if(t=t.toLowerCase(),t==="<local>"){if(!r.includes("."))return!0}else{if(t==="*"||je(r,t))return!0;if(t.startsWith(".")&&r.endsWith(t))return!0;if(r===t||r.endsWith("."+t.replace(/^[*.]+/,"")))return!0}return!1}function ue(r,e){let t=process.env,n=t.NO_PROXY||t.no_proxy||"";if(n&&ae(e,n.split(",").map(o=>o.trim()).filter(o=>o)))return null;for(let o of[`${r.toUpperCase()}_PROXY`,`${r}_proxy`]){let a=t[o];if(a)return a}let[s,i]=Be();return!Object.keys(s).length||ae(e,i)?null:s[r]||s.http||null}function ce(r){return new URL(r.includes("://")?r:"http://"+r)}function Re(r){if(!r.username)return{};let e=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;return{"Proxy-Authorization":"Basic "+Buffer.from(e,"utf8").toString("base64")}}var z=class extends Error{code="EPROXY"},N=class extends Error{code="ETIMEDOUT"};function We(r,e,t,n,s){return new Promise((i,o)=>{let a=`${e.includes(":")?`[${e}]`:e}:${t}`,c=r.protocol==="https:",y={host:r.hostname.replace(/^\[|\]$/g,""),port:Number(r.port)||(c?443:80),method:"CONNECT",path:a,headers:{Host:a,...Re(r)},agent:!1,...c&&s?{secureContext:s}:{}},p=(c?U:F).request(y),d=!1,T=m=>{d||(d=!0,p.destroy(),o(m))};p.setTimeout(n,()=>T(new N(`proxy ${r.host} timed out`))),p.once("connect",(m,h,u)=>{if(!d){if(m.statusCode===200){d=!0,p.setTimeout(0),u.length&&h.unshift(u),i(h);return}h.destroy(),T(new z(`Tunnel connection failed: ${m.statusCode} ${m.statusMessage??""}`.trim()))}}),p.once("error",T),p.end()})}var j=class extends U.Agent{constructor(t,n){super(n);this.proxy=t}createConnection(t,n){let s=String(t.host??t.hostname??"localhost"),i=Number(t.port)||443,o=typeof t.timeout=="number"&&t.timeout>0?t.timeout:6e4;We(this.proxy,s,i,o,this.options.secureContext).then(a=>{let c=J.connect({...t,socket:a});n?.(null,c)},a=>n?.(a,void 0))}},Ye=new Set(["ECONNRESET","EPIPE","ECONNABORTED"]),W=class{timeout;agents=new Map;constructor(e=60){this.timeout=e}agent(e,t){let n=`${e} ${t?.href??""}`,s=this.agents.get(n);if(!s){let i=e==="https"||t?.protocol==="https:"?He():void 0,o={keepAlive:!0,...i?{secureContext:i}:{}};e==="https"&&t?s=new j(t,o):e==="https"||t?.protocol==="https:"?s=new U.Agent(o):s=new F.Agent({keepAlive:!0}),this.agents.set(n,s)}return s}async request(e,t,n={},s=null,i={}){let o=new URL(t),a=P(t),c=o.protocol==="http:"?"http":"https",y=o.hostname.replace(/^\[|\]$/g,""),p=Number(o.port)||(c==="https"?443:80),d=a.path||"/";a.query&&(d+="?"+a.query);let T={"User-Agent":Oe,"Accept-Encoding":"identity",...n},m=Math.max(1,Math.round((i.timeout??this.timeout)*1e3)),h=ue(c,y),u=h?ce(h):null,E=!1;for(let v=1;;v++)try{return await this.once(e,t,c,y,p,d,T,s,m,u,i.saveTo??null)}catch(R){let w=R;if(w.reused&&v===1&&Ye.has(w.code??""))continue;if(!E&&typeof w.code=="string"&&!me(w)&&(E=!0,ze())){let f=ue(c,y);if(f!==h){h=f,u=f?ce(f):null;continue}}throw R}}once(e,t,n,s,i,o,a,c,y,p,d){return new Promise((T,m)=>{let h,u;if(p&&n==="http"){let f=p.protocol==="https:";u=f?U:F,h={host:p.hostname.replace(/^\[|\]$/g,""),port:Number(p.port)||(f?443:80),path:`http://${s}:${i}${o}`,headers:{Host:i===80?s:`${s}:${i}`,...a,...Re(p)}}}else u=n==="https"?U:F,h={host:s,port:i,path:o,headers:a};h.method=e,h.agent=this.agent(n,p),h.timeout=y;let E=!1,v=!1,R=u.request(h),w=f=>{if(E)return;E=!0;let x=v?new N(`timed out after ${y} ms`):f;x.reused=R.reusedSocket,R.destroy(),m(x)};R.on("timeout",()=>{v=!0,R.destroy(new N("timeout"))}),R.on("error",w),R.on("response",f=>{let x={},$=f.rawHeaders;for(let S=0;S+1<$.length;S+=2){let _=$[S].toLowerCase(),k=$[S+1];x[_]=_ in x?`${x[_]}, ${k}`:k}let A=f.statusCode??0,g=f.statusMessage??"";if(f.on("error",w),f.on("aborted",()=>w(Object.assign(new Error("aborted"),{code:"ECONNRESET"}))),d&&A>=200&&A<300){let S=Ae(d);try{Se(Ce(S),{recursive:!0})}catch(_){w(_);return}_e(f,xe(d)).then(()=>{E||(E=!0,T(new M(A,g,x,Buffer.alloc(0),t,d)))},_=>w(_));return}let l=[];f.on("data",S=>l.push(S)),f.on("end",()=>{E||(E=!0,T(new M(A,g,x,Buffer.concat(l),t)))})}),c&&c.length?R.end(Buffer.from(c.buffer,c.byteOffset,c.byteLength)):R.end()})}close(){for(let e of this.agents.values())e.destroy();this.agents.clear()}},Je;function Xe(){return Je??=new W}function le(r,e=Date.now()){if(!r)return null;let t=r.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i.test(t))return Math.max(0,Number(t));if(!/[A-Za-z]{3}/.test(t))return null;let n=Date.parse(/GMT|UTC|[+-]\d{4}$/.test(t)?t:t+" GMT");return Number.isNaN(n)?null:Math.max(0,(n-e)/1e3)}function Ve(r,e){return $e.has(e)?e===429||B.has(r.toUpperCase()):!1}function de(r,e=30){return Math.random()*Math.min(e,2**r)}var Ke=new Set(["authorization","proxy-authorization","cookie","set-cookie"]);function Ze(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Ke.has(t.toLowerCase())?"<redacted>":n;return e}var Y=class extends O{constructor(e="dry run"){super(e,{exitCode:0})}},fe=class{defaultHeaders(){return{Accept:"application/json"}}requestId(e){return null}error(e){return Qe(this.name,e,null,null)}authTrap(e){return null}};function Qe(r,e,t,n,s=null,i=null){let o=e.status,a=n||`HTTP ${o} ${e.reason}`.trim();o===403&&i===null&&(i="signed in, but this account lacks permission for the request");let c={service:r,status:o};switch(t&&(c.code=t),s&&(c.requestId=s),i!==null&&(c.hint=i),o){case 401:return new L(a,c);case 403:return new Q(a,c);case 404:return new X(a,c);case 409:case 412:return new K(a,c);case 429:return new V(a,c);default:return new O(a,c)}}var et=["login.microsoftonline.com","login.windows.net","login.live.com"],tt="run: ppdo-cli auth login <identity>";function rt(r){return{header:async e=>"Bearer "+await r(e)}}var q=r=>new Promise(e=>setTimeout(e,Math.max(0,r*1e3))),b=()=>performance.now()/1e3,nt=":/?#[]@!$&'()*+,;=%~",he=class{service;rt;authorizer;http;target=null;identity=null;cached=null;notBefore=0;inLookups=!1;also=[];constructor(e,t,n,s=Xe()){this.service=e,this.rt=t,this.authorizer=n===null?null:typeof n=="function"?rt(n):n,this.http=s}async lookups(e,t=[]){this.inLookups=!0,this.also=t.map(n=>n.toLowerCase());try{return await e()}finally{this.inLookups=!1,this.also=[]}}async request(e,t,n={}){e=e.toUpperCase();let s=se(this.service.url(t,n.params??null),nt);if(!this.service.allowed(s)){let a="";try{a=new URL(s).hostname}catch{a=P(s).netloc}throw new Z(`refusing to send a ${this.service.name} token to ${a||"None"}`,{hint:"absolute URLs must belong to the environment's own host or organization",service:this.service.name})}let i={...this.service.defaultHeaders(),...n.headers??{}},o=n.body??null;return o!==null&&!Object.keys(i).some(a=>a.toLowerCase()==="content-type")&&(i["Content-Type"]="application/json"),this.rt.dryRun&&!(this.inLookups&&this.isRead(e,s))&&await this.dryRun(e,s,i,o),this.send(e,s,i,o,n.saveTo??null,n.check??!0)}async*paginate(e,t){let n=0,s=await this.request("GET",e,{params:t.params??null,headers:t.headers??null}),i=t.limit??null;for(;;){for(let a of t.items(s))if(yield a,n++,i!==null&&n>=i)return;let o=t.nextLink(s);if(!o)return;s=await this.request("GET",o,{headers:t.headers??null})}}isRead(e,t){if(e==="GET"||e==="HEAD")return!0;if(e!=="POST")return!1;let n=P(t).path.replace(/\/+$/,""),s=n.slice(n.lastIndexOf("/")+1).toLowerCase();return this.also.includes(s)||ne(this.service.name,t)}async dryRun(e,t,n,s){let i=null;if(s!==null){let o=Buffer.from(s).toString("utf8");try{i=JSON.parse(o)}catch{i=o}}throw await this.rt.emit({dry_run:!0,method:e,url:t,headers:Ze(n),body:i}),new Y("dry run")}async authHeader(e=!1){return this.authorizer===null?"":((e||this.cached===null||this.cached.service!==this.service)&&(this.cached={service:this.service,header:await this.authorizer.header(e,this.service)}),this.cached.header)}async send(e,t,n,s,i,o){let a=this.service.name,c=this.authorizer?.hint??tt,y=b()+(this.rt.timeout||Ne),p=!1,d=0,T=0,m=t,h=!0,u;for(;;){d++;let E=this.notBefore-b();E>0&&(this.rt.log(`throttle: waiting ${E.toFixed(1)}s (Retry-After from an earlier response)`),await q(E));let v={...n};h&&this.authorizer!==null&&(v.Authorization=await this.authHeader(),Object.assign(v,this.authorizer.extraHeaders?.()??{}));let R=b();this.rt.log(`-> ${e} ${m}`);let w=pe(m);try{u=await this.http.request(e,m,v,s,{timeout:Math.min(120,Math.max(5,y-b())),saveTo:i})}catch(g){let l=g;if(l instanceof O)throw l;if(l instanceof N||l.code==="ETIMEDOUT"){if(B.has(e)&&d<I&&b()<y){this.rt.log(` timeout (${l.message}); retrying`);continue}throw new O(`request timed out: ${e} ${m}`,{service:a})}if(me(l))throw new O(`TLS error talking to ${w}: ${l.message}`,{service:a,hint:Pe()});if(typeof l.code!="string")throw g;let S=l.code==="ENOTFOUND"||l.code==="EAI_AGAIN"||l.code==="EAI_FAIL";if((l.code==="ECONNREFUSED"||B.has(e))&&!S&&d<I&&b()<y){let k=de(d);this.rt.log(` connection error (${l.message}); retrying in ${k.toFixed(1)}s`),await q(k);continue}throw new O(`cannot reach ${w}: ${l.message}`,{service:a,hint:"check the network, proxy (HTTPS_PROXY) and the URL"})}let f=(b()-R)*1e3,x=this.service.requestId(u);this.rt.log(`<- ${u.status} ${u.reason} (${f.toFixed(0)} ms)`+(x?` request-id=${x}`:""));let $=le(u.header("retry-after"));$&&u.status<400&&(this.notBefore=b()+Math.min($,oe));let A=this.service.authTrap(u);if(A)throw new L(A,{service:a,status:u.status,hint:c});if(u.status===401&&h&&this.authorizer!==null){let g=u.header("www-authenticate")??"";if(g.includes("insufficient_claims")||g.includes("claims="))throw new L("the service requires a fresh sign-in (claims challenge)",{service:a,status:401,hint:c});if(!p){p=!0,this.rt.log(" 401: refreshing the token once"),await this.authHeader(!0);continue}if(this.authorizer.hint)throw new L(`${a} rejected the credential (401)`,{service:a,status:401,hint:c})}if(u.status>=300&&u.status<400&&u.status!==304){let g=u.header("location");if(!g)break;try{g=new URL(g,m).toString()}catch{break}let l=pe(g);if(et.includes(l)||g.includes("_signin"))throw new L("the service redirected to a sign-in page (token rejected)",{service:a,status:u.status,hint:c});if(T++,T>5||e!=="GET"&&e!=="HEAD")break;m=g,h=!1,this.rt.log(` redirect to ${l} (without Authorization)`);continue}if(Ve(e,u.status)&&d<I){let g=le(u.header("retry-after")),l=g!==null?Math.min(g,oe):u.status===429?Le:de(d);if(b()+l<y){this.rt.log(` ${u.status}: retrying in ${l.toFixed(1)}s (attempt ${d}/${I})`),await q(l);continue}}break}if(o&&u.status>=400)throw this.service.error(u);return u}};function pe(r){try{return new URL(r).hostname}catch{return""}}export{Xe as a,fe as b,Qe as c,he as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{g as u}from"./chunk-WXOTXJNG.js";var c=["GET","HEAD"],d={dataverse:["exportsolution","exportsolutionasync","downloadsolutionexportdata"],devops:["_apis/wit/wiql","_apis/wit/workitemsbatch"]},E=/_apis\/pipelines\/\d+\/preview$/,m=/^(GET|HEAD|POST|PATCH|PUT|DELETE|MERGE)[ \t\n\r\f\v]+[^ \t\n\r\f\v]+[ \t\n\r\f\v]+HTTP\/1\.[01][ \t\n\r\f\v]*$/gim;function f(e){return!e||!e.length?[]:[...(typeof e=="string"?e:Buffer.from(e).toString("latin1")).matchAll(m)].map(r=>r[1].toUpperCase())}function g(e){let t;if(e.includes("://")){let r=/^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*([^?#]*)/.exec(e);t=r?r[1]??"":""}else t=e.split("?",1)[0]??"";return t.replace(/^\/+|\/+$/g,"").toLowerCase()}function p(e){return g(e).endsWith("$batch")}function h(e,t){let r=g(t);if(e==="dataverse"){let n=r.slice(r.lastIndexOf("/")+1);return n=n.replace(/\(.*\)$/,""),n=n.slice(n.lastIndexOf(".")+1),(d.dataverse??[]).includes(n)}return e==="devops"&&E.test(r)?!0:(d[e]??[]).some(n=>r.endsWith(n))}function v(e,t,r,n,s,o){if(n=n.toUpperCase(),t==="D"&&e!=="full")return`this command deletes; mode is '${e}' (needs 'full')`;if(t==="W"&&e==="read-only")return"this command writes; mode is 'read-only'";if(e==="full"||c.includes(n))return null;if(e==="read-write")return n==="DELETE"?"DELETE needs mode 'full' (current: 'read-write')":p(s)&&f(o).includes("DELETE")?"this $batch contains a DELETE part; needs mode 'full'":null;if(n==="POST"){if(p(s)){let l=f(o),i=l.filter(a=>!c.includes(a));return l.length&&!i.length?null:i.length?`this $batch contains a ${i[0]} part; mode is 'read-only'`:"cannot read the $batch parts; mode is 'read-only'"}if(h(r,s))return null}return`${n} is not allowed in mode 'read-only'`}function $(e,t,r,n,s,o){let l=o||(typeof e.args._cls=="string"?e.args._cls:"M"),i=t.target,a=v(i.mode,l,t.service.name,r,n,s);if(a)throw new u(`blocked: ${a}`,{service:t.service.name,hint:w(i)})}function w(e){if(e.app){let t=e.mode==="read-write"?"full":"read-write (full to delete)";return`this runs as an app with --mode ${e.mode}; pass --mode ${t} if the change is intended`}return`stop and ask the user: environment '${e.env.name}' is in group '${e.group.name}' (${e.mode}); only they can change that`}export{h as a,$ as b,w as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as b,b as k}from"./chunk-MTF66YXU.js";import{b as j,c as x}from"./chunk-4KP27OCL.js";import{a as l,b as p,c as h,d as g,e as u,f as m,g as f}from"./chunk-J4R6QXW7.js";import{b as v,h as w}from"./chunk-WXOTXJNG.js";var A="499b84ac-1321-427f-aa17-267ca6975798",C="7.1";function y(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}var S=class extends j{name="devops";org;project;hostKey;apiVersion;constructor(e,n="core",t){super(),this.org=e.org??"",this.project=e.project??null,this.hostKey=n,this.apiVersion=t||C}scope(){return A+"/.default"}base(){return`https://${this.hostKey==="core"?"dev.azure.com":`${this.hostKey}.dev.azure.com`}/${l(this.org)}/`}expand(e){if(e.includes("{project}")){if(!this.project)throw new v("the path uses {project} but the environment has no DevOps project",{hint:"ask the user to set one: ppdo-cli env update <name> --devops-project <project>"});e=e.split("{project}").join(l(this.project))}return e}url(e,n){e=this.expand(e);let t=e.includes("://")?e:this.base()+e.replace(/^\/+/,""),r=u(t),i=[...g(r.query),...n??[]],s=f(t).host||r.netloc.toLowerCase();return!(r.path.includes("/_odata/")||s==="analytics.dev.azure.com")&&!i.some(([d])=>d.toLowerCase()==="api-version")&&i.push(["api-version",this.apiVersion]),m({...r,query:h(i,"$'(),/:@*"),fragment:""})}allowed(e){let n=f(e);if(n.scheme!=="https"||!n.host)return!1;let t=this.org.toLowerCase();if(!t)return!1;if(new Set(["dev.azure.com",...b.filter(s=>s!=="core").map(s=>`${s}.dev.azure.com`)]).has(n.host)){let s=(n.path.replace(/^\/+/,"").split("/",1)[0]??"").toLowerCase();if(s!==t&&s!==l(t).toLowerCase())return!1;let c=u(e).path.replace(/^\/+/,"").split("/");for(let d of c){let a=p(d);if(a==="."||a===".."||a.includes("/")||a.includes("\\"))return!1}return p(c[0]??"").toLowerCase()===t}return new Set([`${t}.visualstudio.com`,...k.map(s=>`${t}.${s}.visualstudio.com`)]).has(n.host)}requestId(e){return e.header("activityid")||e.header("x-vss-e2eid")}authTrap(e){let n=e.header("content-type")??"";return e.status===203||e.status>=200&&e.status<300&&n.includes("text/html")&&e.body.subarray(0,2e3).toString("latin1").toLowerCase().includes("<html")?"Azure DevOps returned a sign-in page instead of data (the token was rejected)":null}error(e){let n=null,t=null,r=null;if(e.body.length)try{let i=e.json(),s=y(i)?i:{};t=typeof s.message=="string"?s.message:null,n=typeof s.typeKey=="string"&&s.typeKey||(s.errorCode?String(s.errorCode):null)||null}catch{t=e.text.trim().slice(0,300)||null}if(t&&t.includes("TF401444"))r="a service principal must be added to the organization first: Organization settings > Users > Add users, with an access level and project permissions";else if(e.status===401||t&&t.includes("TF400813"))r="this account isn't a member of the organization, or the token is for another tenant";else if(e.status===404)r="404 also means 'no permission to see it' in Azure DevOps";else if(n==="WorkItemTrackingFieldDefinitionNotFoundException")r="use the field's reference name (e.g. Microsoft.VSTS.Common.Priority) or a System field name";else if(n==="GitPullRequestUpdateRejectedByPolicyException")r="a branch policy isn't passing yet (approvals, builds, linked work items): ppdo-cli ado pr checks <pr> shows which; get it passing, don't bypass it";else if(n==="TestPatchOperationFailedException")r="the work item changed after ppdo-cli read it; run the command again";else if(n==="VssInvalidPreviewVersionException")r="this endpoint is preview-only: pass --api-version <version>-preview";else if(t&&t.includes("VS403664")){let i=this.requestId(e);return new w(t,{service:this.name,status:e.status,...n?{code:n}:{},...i?{requestId:i}:{},hint:"only a comment's author can edit or delete it"})}return x(this.name,e,n,t,this.requestId(e),r)}};function O(o){let e=o.header("x-ms-continuationtoken");if(e){let t=u(o.url),r=g(t.query).filter(([i])=>i!=="continuationToken");return r.push(["continuationToken",e]),m({...t,query:h(r),fragment:""})}let n=o.isJson?o.json():null;return y(n)&&n["@odata.nextLink"]?String(n["@odata.nextLink"]):null}function T(o){let e=o.isJson?o.json():null;return y(e)&&Array.isArray(e.value)?e.value:Array.isArray(e)?e:e!=null?[e]:[]}export{A as a,C as b,S as c,O as d,T as e};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{b as O}from"./chunk-WXOTXJNG.js";import{a as A,b as C,d as Ot}from"./chunk-ZHHVG47C.js";var b=C(S=>{var w=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},$=class extends w{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};S.CommanderError=w;S.InvalidArgumentError=$});var y=C(T=>{var{InvalidArgumentError:At}=b(),H=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new At(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function bt(o){let t=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+t+">":"["+t+"]"}T.Argument=H;T.humanReadableArgName=bt});var P=C(k=>{var{humanReadableArgName:wt}=y(),V=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description))}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>wt(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let r=i(s);n.has(r)||n.set(r,[])}),e.forEach(s=>{let r=i(s);n.has(r)||n.set(r,[]),n.get(r).push(s)}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(l,d){return e.formatItem(l,i,d,e)}let r=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(r=r.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(l=>s(e.styleArgumentTerm(e.argumentTerm(l)),e.styleArgumentDescription(e.argumentDescription(l))));if(r=r.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),l=>l.helpGroupHeading??"Options:").forEach((l,d)=>{let p=l.map(g=>s(e.styleOptionTerm(e.optionTerm(g)),e.styleOptionDescription(e.optionDescription(g))));r=r.concat(this.formatItemList(d,p,e))}),e.showGlobalOptions){let l=e.visibleGlobalOptions(t).map(d=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));r=r.concat(this.formatItemList("Global Options:",l,e))}return this.groupItems(t.commands,e.visibleCommands(t),l=>l.helpGroup()||"Commands:").forEach((l,d)=>{let p=l.map(g=>s(e.styleSubcommandTerm(e.subcommandTerm(g)),e.styleSubcommandDescription(e.subcommandDescription(g))));r=r.concat(this.formatItemList(d,p,e))}),r.join(`
|
|
3
|
+
`)}displayWidth(t){return X(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let r=" ".repeat(2);if(!i)return r+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,u=(this.helpWidth??80)-e-h-2,l;return u<this.minWidthToWrap||n.preformatted(i)?l=i:l=n.boxWrap(i,u).replace(/\n/g,`
|
|
4
|
+
`+" ".repeat(e+h)),r+a+" ".repeat(h)+l.replace(/\n/g,`
|
|
5
|
+
${r}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(r=>{let a=r.match(n);if(a===null){s.push("");return}let h=[a.shift()],c=this.displayWidth(h[0]);a.forEach(u=>{let l=this.displayWidth(u);if(c+l<=e){h.push(u),c+=l;return}s.push(h.join(""));let d=u.trimStart();h=[d],c=this.displayWidth(d)}),s.push(h.join(""))}),s.join(`
|
|
6
|
+
`)}};function X(o){let t=/\x1b\[\d*(;\d*)*m/g;return o.replace(t,"")}k.Help=V;k.stripColor=X});var N=C(W=>{var{InvalidArgumentError:yt}=b(),D=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=xt(t);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return typeof t=="string"&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new yt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Q(this.name().replace(/^no-/,"")):Q(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},I=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(t,e){let i=e.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:!1;return e.negate===(s===t)}};function Q(o){return o.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}function xt(o){let t,e,i=/^-[^-]$/,n=/^--[^-]/,s=o.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(t=s.shift()),n.test(s[0])&&(e=s.shift()),!t&&i.test(s[0])&&(t=s.shift()),!t&&n.test(s[0])&&(t=e,e=s.shift()),s[0].startsWith("-")){let r=s[0],a=`option creation failed due to '${r}' in option flags '${o}'`;throw/^-[^-][^-]/.test(r)?new Error(`${a}
|
|
7
|
+
- a short flag is a single dash and a single character
|
|
8
|
+
- either use a single dash and a single character (for a short flag)
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(r)?new Error(`${a}
|
|
10
|
+
- too many short flags`):n.test(r)?new Error(`${a}
|
|
11
|
+
- too many long flags`):new Error(`${a}
|
|
12
|
+
- unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:t,longFlag:e}}W.Option=D;W.DualOptions=I});var et=C(tt=>{function Et(o,t){if(Math.abs(o.length-t.length)>3)return Math.max(o.length,t.length);let e=[];for(let i=0;i<=o.length;i++)e[i]=[i];for(let i=0;i<=t.length;i++)e[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=o.length;n++){let s=1;o[n-1]===t[i-1]?s=0:s=1,e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+s),n>1&&i>1&&o[n-1]===t[i-2]&&o[n-2]===t[i-1]&&(e[n][i]=Math.min(e[n][i],e[n-2][i-2]+1))}return e[o.length][t.length]}function vt(o,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let e=o.startsWith("--");e&&(o=o.slice(2),t=t.map(r=>r.slice(2)));let i=[],n=3,s=.4;return t.forEach(r=>{if(r.length<=1)return;let a=Et(o,r),h=Math.max(o.length,r.length);(h-a)/h>s&&(a<n?(n=a,i=[r]):a===n&&i.push(r))}),i.sort((r,a)=>r.localeCompare(a)),e&&(i=i.map(r=>`--${r}`)),i.length>1?`
|
|
13
|
+
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
14
|
+
(Did you mean ${i[0]}?)`:""}tt.suggestSimilar=vt});var rt=C(R=>{var $t=A("node:events").EventEmitter,F=A("node:child_process"),_=A("node:path"),x=A("node:fs"),m=A("node:process"),{Argument:St,humanReadableArgName:Ht}=y(),{CommanderError:G}=b(),{Help:Tt,stripColor:Vt}=P(),{Option:it,DualOptions:kt}=N(),{suggestSimilar:nt}=et(),q=class o extends $t{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>m.stdout.write(e),writeErr:e=>m.stderr.write(e),outputError:(e,i)=>i(e),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>M()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>M()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:e=>Vt(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let n=e,s=i;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,r,a]=t.match(/([^ ]+) *(.*)/),h=this.createCommand(r);return n&&(h.description(n),h._executableHandler=!0),s.isDefault&&(this._defaultCommandName=h._name),h._hidden=!!(s.noHelp||s.hidden),h._executableFile=s.executableFile||null,a&&h.arguments(a),this._registerCommand(h),h.parent=this,h.copyInheritedSettings(this),n?this:h}createCommand(t){return new o(t)}createHelp(){return Object.assign(new Tt,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
15
|
+
- specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new St(t,e)}argument(t,e,i,n){let s=this.createArgument(t,e);return typeof i=="function"?s.default(n).argParser(i):s.default(i),this.addArgument(s),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e?.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=t??"help [command]",[,n,s]=i.match(/([^ ]+) *(.*)/),r=e??"display help for command",a=this.createCommand(n);return a.helpOption(!1),s&&a.arguments(s),r&&a.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=a,(t||e)&&this._initCommandGroup(a),this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
16
|
+
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new G(t,e,i)),m.exit(t)}action(t){let e=i=>{let n=this.registeredArguments.length,s=i.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),t.apply(this,s)};return this._actionHandler=e,this}createOption(t,e){return new it(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(s){if(s.code==="commander.invalidArgument"){let r=`${n} ${s.message}`;this.error(r,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
17
|
+
- already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let e=n=>[n.name()].concat(n.aliases()),i=e(t).find(n=>this._findCommand(n));if(i){let n=e(this._findCommand(i)).join("|"),s=e(t).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();if(t.negate){let s=t.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(i,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let n=(s,r,a)=>{s==null&&t.presetArg!==void 0&&(s=t.presetArg);let h=this.getOptionValue(i);s!==null&&t.parseArg?s=this._callParseArg(t,s,h,r):s!==null&&t.variadic&&(s=t._collectValue(s,h)),s==null&&(t.negate?s=!1:t.isBoolean()||t.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,a)};return this.on("option:"+e,s=>{let r=`error: option '${t.flags}' argument '${s}' is invalid.`;n(s,r,"cli")}),t.envVar&&this.on("optionEnv:"+e,s=>{let r=`error: option '${t.flags}' value '${s}' from env '${t.envVar}' is invalid.`;n(s,r,"env")}),this}_optionEx(t,e,i,n,s){if(typeof e=="object"&&e instanceof it)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(e,i);if(r.makeOptionMandatory(!!t.mandatory),typeof n=="function")r.default(s).argParser(n);else if(n instanceof RegExp){let a=n;n=(h,c)=>{let u=a.exec(h);return u?u[0]:c},r.default(s).argParser(n)}else r.default(n);return this.addOption(r)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:!0},t,e,i,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(e=i.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){m.versions?.electron&&(e.from="electron");let n=m.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(e.from="eval")}t===void 0&&(t=m.argv),this.rawArgs=t.slice();let i;switch(e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(x.existsSync(t))return;let n=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${t}' does not exist
|
|
19
|
+
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
+
- ${n}`;throw new Error(s)}_executeSubCommand(t,e){e=e.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,l){let d=_.resolve(u,l);if(x.existsSync(d))return d;if(n.includes(_.extname(l)))return;let p=n.find(g=>x.existsSync(`${d}${g}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=x.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=_.resolve(_.dirname(u),a)}if(a){let u=s(a,r);if(!u&&!t._executableFile&&this._scriptPath){let l=_.basename(this._scriptPath,_.extname(this._scriptPath));l!==this._name&&(u=s(a,`${l}-${t._name}`))}r=u||r}i=n.includes(_.extname(r));let h;m.platform!=="win32"?i?(e.unshift(r),e=st(m.execArgv).concat(e),h=F.spawn(m.argv[0],e,{stdio:"inherit"})):h=F.spawn(r,e,{stdio:"inherit"}):(this._checkForMissingExecutable(r,a,t._name),e.unshift(r),e=st(m.execArgv).concat(e),h=F.spawn(m.execPath,e,{stdio:"inherit"})),h.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(l=>{m.on(l,()=>{h.killed===!1&&h.exitCode===null&&h.kill(l)})});let c=this._exitCallback;h.on("close",u=>{u=u??1,c?c(new G(u,"commander.executeSubCommandAsync","(close)")):m.exit(u)}),h.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(r,a,t._name);else if(u.code==="EACCES")throw new Error(`'${r}' not executable`);if(!c)m.exit(1);else{let l=new G(1,"commander.executeSubCommandAsync","(error)");l.nestedError=u,c(l)}}),this.runningCommand=h}_dispatchSubcommand(t,e,i){let n=this._findCommand(t);n||this.help({error:!0}),n._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,e.concat(i));else return n._parseCommand(e,i)}),s}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,n,s)=>{let r=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;r=this._callParseArg(i,n,s,a)}return r};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce((r,a)=>t(i,a,r),i.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=t(i,s,i.defaultValue))),e[n]=s}),this.processedArgs=e}_chainOrCall(t,e){return t?.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let i=t,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[e]!==void 0).forEach(s=>{s._lifeCycleHooks[e].forEach(r=>{n.push({hookedCommand:s,callback:r})})}),e==="postAction"&&n.reverse(),n.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,e,i){let n=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{n=this._chainOrCall(n,()=>s(this,e))}),n}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(s,t,e)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent?.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=t.find(s=>i.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],i=[],n=e;function s(u){return u.length>1&&u[0]==="-"}let r=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(l=>l.options.map(d=>d.short).some(d=>/^-\d$/.test(d))):!1,a=null,h=null,c=0;for(;c<t.length||h;){let u=h??t[c++];if(h=null,u==="--"){n===i&&n.push(u),n.push(...t.slice(c));break}if(a&&(!s(u)||r(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,s(u)){let l=this._findOption(u);if(l){if(l.required){let d=t[c++];d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;c<t.length&&(!s(t[c])||r(t[c]))&&(d=t[c++]),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,u.slice(2)):(this.emit(`option:${l.name()}`),h=`-${u.slice(2)}`);continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),d=this._findOption(u.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(l+1));continue}}if(n===e&&s(u)&&!(this.commands.length===0&&r(u))&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(u)){e.push(u),i.push(...t.slice(c));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){e.push(u,...t.slice(c));break}else if(this._defaultCommandName){i.push(u,...t.slice(c));break}}if(this._passThroughOptions){n.push(u,...t.slice(c));break}n.push(u)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let n=this.options[i].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
|
|
22
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
24
|
+
`),this.outputHelp({error:!0}));let i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new kt(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!e(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let i=r=>{let a=r.attributeName(),h=this.getOptionValue(a),c=this.options.find(l=>l.negate&&a===l.attributeName()),u=this.options.find(l=>!l.negate&&a===l.attributeName());return c&&(c.presetArg===void 0&&h===!1||c.presetArg!==void 0&&h===c.presetArg)?c:u||r},n=r=>{let a=i(r),h=a.attributeName();return this.getOptionValueSource(h)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let r=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(r),s=s.parent}while(s&&!s._enablePositionalOptions);e=nt(t,n)}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${i} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),e=nt(t,n)}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
25
|
+
`),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>Ht(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=_.basename(t,_.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,s;return e?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:s}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e&&(s=e(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",n))}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(m.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
|
+
Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,s=>{let r;typeof e=="function"?r=e({error:s.error,command:s.command}):r=e,r&&s.write(`${r}
|
|
27
|
+
`)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function st(o){return o.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return(s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function M(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}R.Command=q;R.useColor=M});var lt=C(f=>{var{Argument:ot}=y(),{Command:j}=rt(),{CommanderError:Pt,InvalidArgumentError:at}=b(),{Help:Dt}=P(),{Option:ut}=N();f.program=new j;f.createCommand=o=>new j(o);f.createOption=(o,t)=>new ut(o,t);f.createArgument=(o,t)=>new ot(o,t);f.Command=j;f.Option=ut;f.Argument=ot;f.Help=Dt;f.CommanderError=Pt;f.InvalidArgumentError=at;f.InvalidOptionArgumentError=at});var ht=Ot(lt(),1),{program:ie,createCommand:ne,createArgument:se,createOption:re,CommanderError:oe,InvalidArgumentError:E,InvalidOptionArgumentError:ae,Command:ct,Argument:dt,Option:L,Help:mt}=ht.default;import{readFileSync as pt}from"node:fs";var It={R:"read",W:"write",D:"delete",M:"depends on HTTP method",L:"local config or cache only"},Wt=[],me=new Set(["--env","--group","--identity","-o","--output","--timeout","--tenant","--client-id","--certificate","--mode"]),Nt=["dv","ado","graph"];function Ft(o){let t=Number(o);if(!o.trim()||!Number.isFinite(t))throw new E(`not a number: ${o}`);return t}function pe(o){if(!/^\s*[+-]?\d+\s*$/.test(o))throw new E(`invalid int value: '${o}'`);return parseInt(o,10)}function fe(o,t){return[...t??[],o]}var ge=["GET","POST","PATCH","PUT","DELETE"];function _e(o){return new dt("<method>",o.join(" | ")).argParser(t=>{let e=t.toUpperCase();if(!o.includes(e))throw new E(`invalid choice: '${e}' (choose from ${o.join(", ")})`);return e})}function Ce(o){o.option("--env <name>[,<name>...]","environment to use; several (comma-separated) run a read command against each").option("--group <name>","run a read command against every environment in a group").option("--identity <name>","identity to use instead of the group's").option("-o, --output <format>","json (default) | ndjson | table | tsv").option("--dry-run","show the request without sending it").option("-v, --verbose","log requests to stderr (redacted)").option("-q, --quiet","suppress notices on stderr").addOption(new L("--timeout <seconds>","overall deadline, retries included").argParser(Ft))}function Gt(o){o.option("--client-id <id>","run as this app; the secret comes from PPDEVOPS_CLIENT_SECRET (or a prompt at a terminal)").option("--tenant <id|domain>","with --client-id: the app's tenant").option("--certificate <path>","with --client-id: a PEM (key and certificate) or PFX file instead of a secret").addOption(new L("--mode <mode>","with --client-id: read-only (default) | read-write | full").choices(["read-only","read-write","full"]))}function Y(o){let t=[];for(let e=o;e&&e.parent;e=e.parent)t.unshift(e.name());return t}function B(o){let t=o;for(;t.parent;)t=t.parent;return t}function Oe(o,t,e,i=[]){let n=o.command(t).description(e);return i.length&&n.aliases(i),!o.parent&&Nt.includes(t)&&Gt(n),n}var gt=new WeakMap;function Ae(o){return gt.get(o)}function qt(o){return o.replace(/[^A-Za-z0-9]+([A-Za-z0-9])/g,(t,e)=>e.toUpperCase()).replace(/[^A-Za-z0-9]/g,"")}var K=class extends ct{cls="L";argKeys=new Map;argKey(t,e){return this.argKeys.set(t,e),this}keyOf(t){return this.argKeys.get(t)??qt(t)}handler(t){return this.action(()=>{let e={...this.optsWithGlobals()},i=[...this.processedArgs];this.registeredArguments.forEach((n,s)=>{e[this.keyOf(n.name())]=i[s]}),e._cls=this.cls,gt.set(B(this),{path:Y(this),cls:this.cls,handler:t,args:e,operands:i})}),this}};function Mt(o,t){let e=mt.prototype.boxWrap;o.configureHelp({...o.configureHelp(),boxWrap(i,n){return i===t?i:e.call(this,i,n)}})}function be(o,t,e,i,n={}){if(!(e in It))throw new Error(`unknown command class '${String(e)}'`);let s=new K(t);return s.cls=e,s.copyInheritedSettings(o),s.description(n.description??i),n.description!==void 0&&s.summary(i),n.description?.includes(`
|
|
28
|
+
`)&&Mt(s,n.description),n.aliases?.length&&s.aliases(n.aliases),o.addCommand(s),Wt.push({path:Y(s),cls:e,help:i,command:s}),s}var Rt={dv:"dataverse",ado:"devops",whoami:null};function we(o){let t=o.path[0];if(t===void 0||!(t in Rt))return!1;let e=o.args.env;return!!o.args.group||typeof e=="string"&&e.includes(",")}var _t=new WeakMap;function jt(o){o.exitOverride(t=>{throw _t.set(t,o),t});for(let t of o.commands)jt(t)}function ye(o){if(o.code==="commander.helpDisplayed"||o.code==="commander.version")return null;let t=_t.get(o),i=`run: ${t?[B(t).name(),...Y(t)].join(" "):"ppdo-cli"} --help`;if(o.code==="commander.help")return new O("the following arguments are required: <command>",{hint:i});let[n="",...s]=o.message.replace(/^error: /,"").split(`
|
|
29
|
+
`);if(t){let a=Lt(o,t,n);if(a)return new O(a[0],{hint:a[1]?`run: ${B(t).name()} --help`:i})}let r=s.join(" ").match(/\(Did you mean (.+)\?\)/);return new O(n,{hint:r?`did you mean ${r[1]}? ${i}`:i})}function U(o){return(o.split(/[<[]/,1)[0]??"").split(/[ ,|]+/).filter(t=>t.startsWith("-")).join("/")}function ft(o){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)?o:`<${o}>`}function Lt(o,t,e){switch(o.code){case"commander.missingMandatoryOptionValue":case"commander.missingArgument":case"commander.unknownOption":case"commander.excessArguments":{let i=[...t.args],n=i.findIndex(u=>u.startsWith("-")&&u.length>1);n<0&&(n=i.length);let s=i.slice(0,n),r=t.registeredArguments,a=r.filter((u,l)=>u.required&&l>=s.length).map(u=>ft(u.name()));for(let u of t.options)u.mandatory&&t.getOptionValue(u.attributeName())===void 0&&a.push(U(u.flags));if(a.length)return[`the following arguments are required: ${a.join(", ")}`,!1];let c=[...r.some(u=>u.variadic)?[]:s.slice(r.length),...i.slice(n)];return c.length?[`unrecognized arguments: ${c.join(" ")}`,!0]:null}case"commander.optionMissingArgument":{let i=/^option '([^']+)' argument missing/.exec(e);return i?[`argument ${U(i[1])}: expected one argument`,!1]:null}case"commander.invalidArgument":{let i=/^option '([^']+)' argument '(.*)' is invalid\. (.*)$/s.exec(e),n,s,r;if(i)[n,s,r]=[U(i[1]),i[2],i[3]];else{if(i=/^command-argument value '(.*)' is invalid for argument '([^']+)'\. (.*)$/s.exec(e),!i)return null;[s,n,r]=[i[1],ft(i[2]),i[3]]}let a=/^Allowed choices are (.*)\.$/.exec(r);return a&&(r=`invalid choice: '${s}' (choose from ${a[1]})`),[`argument ${n}: ${r}`,!1]}case"commander.unknownCommand":{let i=/^unknown command '(.*)'/.exec(e);if(!i)return null;let n=t.commands.flatMap(s=>[s.name(),...s.aliases()]);return[`argument <command>: invalid choice: '${i[1]}' (choose from ${n.join(", ")})`,!1]}default:return null}}function xe(o,t){let e=[],i=t==="--header"?":":"=";for(let n of o??[]){let s=n.indexOf(i);if(s<0)throw new O(`${t} expects key${i}value, got '${n}'`);let r=n.slice(0,s),a=n.slice(s+1);e.push([r.trim(),i===":"?a.trim():a])}return e}var Ut={m:6e4,h:36e5,d:864e5,w:6048e5},Bt=/^(\d{4})-?(\d{2})-?(\d{2})(?:[T ](\d{2})(?::?(\d{2})(?::?(\d{2})(?:[.,](\d+))?)?)?)?\s*(Z|[+-]\d{2}(?::?\d{2}(?::?\d{2})?)?)?$/i;function Kt(o){let t=Bt.exec(o);if(!t)return null;let[,e,i,n,s="0",r="0",a="0",h="",c]=t,u=Number((h+"000").slice(0,3)),l=[Number(e),Number(i)-1,Number(n),Number(s),Number(r),Number(a)],d=Date.UTC(l[0],l[1],l[2],l[3],l[4],l[5],u),p=new Date(d);if(p.getUTCFullYear()!==l[0]||p.getUTCMonth()!==l[1]||p.getUTCDate()!==l[2]||p.getUTCHours()!==l[3]||p.getUTCMinutes()!==l[4]||p.getUTCSeconds()!==l[5])return null;let g=0;if(c&&c.toUpperCase()!=="Z"){let v=c.slice(1).replace(/:/g,""),Ct=c.startsWith("-")?-1:1,Z=Number(v.slice(0,2)),z=Number(v.slice(2,4)||"0"),J=Number(v.slice(4,6)||"0");if(Z>23||z>59||J>59)return null;g=Ct*((Z*60+z)*60+J)*1e3}return new Date(d-g)}function Ee(o,t="--since",e=new Date){if(!o)return null;let i,n=/^\s*(\d+)\s*([mhdw])\s*$/.exec(o);if(n)i=new Date(e.getTime()-Number(n[1])*(Ut[n[2]??"m"]??0));else if(i=Kt(o.trim()),!i)throw new O(`invalid ${t} '${o}'`,{hint:"use 30m, 12h, 7d, 2w or a date such as 2026-10-01"});return i.toISOString().slice(0,19)+"Z"}var Yt={ENOENT:"No such file or directory",EACCES:"Permission denied",EPERM:"Operation not permitted",EISDIR:"Is a directory"};function ve(o){if(o==null)return null;if(o==="-")return pt(0);if(o.startsWith("@")){let t=o.slice(1);try{return pt(t)}catch(e){let i=e;throw new O(`cannot read ${t}: ${Yt[i.code??""]??i.message}`)}}return Buffer.from(o,"utf8")}export{oe as a,E as b,ct as c,dt as d,L as e,Wt as f,me as g,Ft as h,pe as i,fe as j,ge as k,_e as l,Ce as m,Y as n,Oe as o,Ae as p,qt as q,be as r,Rt as s,we as t,jt as u,ye as v,xe as w,Ee as x,ve as y};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as F,b as N,c as H,j as M}from"./chunk-I3TMFYRJ.js";import{a as K,b as _,e as O}from"./chunk-MBNUMAAZ.js";import{d as D}from"./chunk-LB7WNZVK.js";import{a as P,b as E,c as B}from"./chunk-WXOTXJNG.js";import{createHash as Z,createPrivateKey as ye}from"node:crypto";import{existsSync as ve,readFileSync as Q,statSync as xe}from"node:fs";import{createDecipheriv as ee,createHash as Y,createPrivateKey as X,pbkdf2Sync as te,X509Certificate as ne}from"node:crypto";var l=class extends Error{};function S(e,n){if(n+2>e.length)throw new l("truncated DER");let r=e[n];if((r&31)===31)throw new l("unsupported DER tag");let t=n+1,o=e[t++];if(o===128){let a=t;for(;;){if(t+2>e.length)throw new l("truncated BER");if(e[t]===0&&e[t+1]===0)return{tag:r,value:e.subarray(a,t),end:t+2};t=S(e,t).end}}let c=o;if(o&128){let a=o&127;if(a>4)throw new l("DER length too long");c=0;for(let f=0;f<a;f++)c=c*256+e[t++]}if(t+c>e.length)throw new l("truncated DER");return{tag:r,value:e.subarray(t,t+c),end:t+c}}function u(e){let n=[];for(let r=0;r<e.value.length;){let t=S(e.value,r);n.push(t),r=t.end}return n}function C(e){return S(e,0)}function d(e,n,r){let t=e[n];if(!t)throw new l(`missing ${r}`);return t}function y(e){if(e.tag===4)return e.value;if(e.tag===36)return Buffer.concat(u(e).map(y));throw new l("expected an OCTET STRING")}function b(e){if(e.tag!==160)throw new l("expected [0]");return d(u(e),0,"[0] content")}function x(e){if(e.tag!==6)throw new l("expected an OID");let n=e.value,r=[],t=0;for(let o=0;o<n.length;o++)t=t*128+(n[o]&127),n[o]&128||(r.length?r.push(t):r.push(t<80?Math.floor(t/40):2,t<80?t%40:t-80),t=0);return r.join(".")}function G(e){if(e.tag!==2)throw new l("expected an INTEGER");let n=0;for(let r of e.value)n=n*256+r;return n}var j="1.2.840.113549.1.7.1",re="1.2.840.113549.1.7.6",oe="1.2.840.113549.1.12.10.1.1",ce="1.2.840.113549.1.12.10.1.2",se="1.2.840.113549.1.12.10.1.3",ie="1.2.840.113549.1.9.22.1",ae="1.2.840.113549.1.9.21",fe="1.2.840.113549.1.5.13",le="1.2.840.113549.1.5.12",ue="1.2.840.113549.1.12.1.3",L="1.2.840.113549.1.12.1.4",pe="1.2.840.113549.1.12.1.5",de="1.2.840.113549.1.12.1.6",he={"1.2.840.113549.2.7":"sha1","1.2.840.113549.2.8":"sha224","1.2.840.113549.2.9":"sha256","1.2.840.113549.2.10":"sha384","1.2.840.113549.2.11":"sha512"},ge={"2.16.840.1.101.3.4.1.2":["aes-128-cbc",16],"2.16.840.1.101.3.4.1.22":["aes-192-cbc",24],"2.16.840.1.101.3.4.1.42":["aes-256-cbc",32],"1.2.840.113549.3.7":["des-ede3-cbc",24]};function W(e,n,r,t,o){let f=h=>{if(!h.length)return Buffer.alloc(0);let m=Buffer.alloc(64*Math.ceil(h.length/64));for(let p=0;p<m.length;p++)m[p]=h[p%h.length];return m},s=Buffer.alloc(64,r),i=Buffer.concat([f(n),f(e)]),g=[],w=0;for(;w<o;){let h=Y("sha1").update(s).update(i).digest();for(let p=1;p<t;p++)h=Y("sha1").update(h).digest();if(g.push(h),w+=20,w>=o)break;let m=Buffer.alloc(64);for(let p=0;p<64;p++)m[p]=h[p%20];for(let p=0;p<i.length;p+=64){let k=1;for(let v=63;v>=0;v--){let T=i[p+v]+m[v]+k;i[p+v]=T&255,k=T>>8}}}return Buffer.concat(g).subarray(0,o)}var we=[Buffer.from([0,0]),Buffer.alloc(0)];function J(e,n,r,t){let o=ee(e,n,r);return Buffer.concat([o.update(t),o.final()])}function q(e,n,r){let t=u(e),o=x(d(t,0,"algorithm")),c=t[1],a=[];if(o===fe&&c){let[s,i]=u(c);if(!s||!i)throw new l("bad PBES2 parameters");let g=u(s);if(x(d(g,0,"KDF"))!==le)throw new l("unsupported key derivation");let w=u(d(g,1,"PBKDF2 parameters")),h=y(d(w,0,"salt")),m=G(d(w,1,"iterations")),p="sha1";for(let A of w.slice(2))A.tag===48&&(p=he[x(d(u(A),0,"PRF"))]??"");if(!p)throw new l("unsupported PRF");let k=u(i),v=ge[x(d(k,0,"cipher"))];if(!v)throw new l("unsupported cipher");let T=y(d(k,1,"IV"));a.push(()=>J(v[0],te(Buffer.alloc(0),h,m,v[1],p),T,n))}else if((o===ue||o===L)&&c){let s=u(c),i=y(d(s,0,"salt")),g=G(d(s,1,"iterations"));for(let w of we)a.push(()=>{let h=W(w,i,1,g,24);return o===L&&(h=Buffer.concat([h.subarray(0,16),h.subarray(0,8)])),J("des-ede3-cbc",h,W(w,i,2,g,8),n)})}else throw o===de||o===pe?new l("it uses RC2 encryption, which Node cannot decrypt"):new l(`unsupported encryption ${o}`);let f;for(let s of a)try{let i=s();return r(i),i}catch(i){f=i}throw new l(`cannot decrypt it without a password (${f?.message??"no key"})`)}function I(e){let n=e[2];if(!n||n.tag!==49)return null;for(let r of u(n)){let[t,o]=u(r);if(t&&o&&x(t)===ae){let c=u(o)[0];if(c)return y(c).toString("hex")}}return null}function U(e,n){for(let r of u(C(e))){let t=u(r),o=x(d(t,0,"bag type")),c=b(d(t,1,"bag value"));if(o===oe)n.keys.push({der:me(c),id:I(t)});else if(o===ce){let[a,f]=u(c);if(!a||!f)throw new l("bad shrouded key bag");let s=q(a,y(f),i=>{X({key:i,format:"der",type:"pkcs8"})});n.keys.push({der:s,id:I(t)})}else if(o===se){let a=u(c);if(x(d(a,0,"certificate type"))!==ie)continue;n.certs.push({der:y(b(d(a,1,"certificate"))),id:I(t)})}}}function me(e){let n=e.value.length,r;if(n<128)r=[e.tag,n];else{let t=[];for(let o=n;o>0;o=Math.floor(o/256))t.unshift(o&255);r=[e.tag,128|t.length,...t]}return Buffer.concat([Buffer.from(r),e.value])}function V(e){let n=u(C(e)),r=u(d(n,1,"authSafe"));if(x(d(r,0,"content type"))!==j)throw new l("it is signed, not password-protected");let t={keys:[],certs:[]};for(let f of u(C(y(b(d(r,1,"content")))))){let s=u(f),i=x(d(s,0,"content type"));if(i===j)U(y(b(d(s,1,"content"))),t);else if(i===re){let g=u(b(d(s,1,"content"))),w=u(d(g,1,"encrypted content info")),h=d(w,1,"algorithm"),m=w[2];if(!m)continue;let p=m.tag===160?Buffer.concat(u(m).map(y)):m.value;U(q(h,p,k=>{u(C(k))}),t)}}let o=t.keys[0];if(!o)throw new l("it has no private key");if(!t.certs.length)throw new l("it has no certificate");let c=X({key:o.der,format:"der",type:"pkcs8"}),a=o.id&&t.certs.find(f=>f.id===o.id)||t.certs.find(f=>{try{return new ne(f.der).checkPrivateKey(c)}catch{return!1}})||t.certs[0];return{privateKey:c.export({type:"pkcs8",format:"pem"}).toString(),certificate:a.der}}var $=new Map,R=new Map,z={7000215:"the client secret is wrong: check {where}",7000222:"the client secret has expired: create a new one on the app registration and update {where}",700016:"no app with this client id in tenant '{tenant}': check --client-id and --tenant",90002:"tenant '{tenant}' was not found: check --tenant",700027:"the certificate is not registered on the app, or its key doesn't match"};function ke(e){return e.certificate?e.certificate:e.secretEnv||"the secret"}function Ee(e){let n=e.replace(/\$(\w+)|\$\{([^}]*)\}/g,(r,t,o)=>process.env[t??o]??r);if(process.platform==="win32"&&(n=n.replace(/%([^%]+)%/g,(r,t)=>process.env[t]??r)),n==="~"||n.startsWith("~/")||n.startsWith("~\\")){let r=process.env.USERPROFILE||process.env.HOME||"";r&&(n=r+n.slice(1))}return n}var Be=/-----BEGIN ([A-Z ]+)-----[\s\S]+?-----END \1-----/g;function be(e){e=Ee(e);let n=e.toLowerCase();if(n.endsWith(".pfx")||n.endsWith(".p12")){if(!ve(e)||!xe(e).isFile())throw new E(`cannot read certificate ${e}: no such file`);let s;try{s=V(Q(e))}catch(i){let g=i instanceof Error?i.message:String(i);throw new E(`cannot read certificate ${e}: ${g}`,{hint:i instanceof l?"export it again without a password, or convert it to PEM: openssl pkcs12 -in <pfx> -nodes -out <pem>":void 0})}return{privateKey:s.privateKey,thumbprint:Z("sha1").update(s.certificate).digest("hex")}}let r;try{let s=Q(e);if(s.some(i=>i>127))throw new Error("'ascii' codec can't decode the file");r=s.toString("ascii")}catch(s){let i=s,g=i.code==="ENOENT"?`[Errno 2] No such file or directory: '${e}'`:i.message;throw new E(`cannot read certificate ${e}: ${g}`)}let t=new Map;for(let s of r.matchAll(Be))t.set(s[1],s[0]);let o=t.get("CERTIFICATE"),c=[...t].find(([s])=>s.endsWith("PRIVATE KEY")&&!s.includes("ENCRYPTED"))?.[1];if(!o||!c){let s=c?"the certificate":"an unencrypted private key";throw new E(`${e} has no ${s}`,{hint:"the PEM file needs both the private key and the certificate"})}let a=Buffer.from(o.replace(/-----[A-Z ]+-----/g,"").replace(/\s+/g,""),"base64"),f;try{f=ye(c).export({type:"pkcs8",format:"pem"}).toString()}catch(s){throw new E(`cannot read certificate ${e}: ${s.message}`)}return{privateKey:f,thumbprint:Z("sha1").update(a).digest("hex")}}async function Te(e){let n=JSON.stringify([e.clientId,e.tenant,e.certificate]),r=e.ephemeral?R.get(n):void 0;if(r!==void 0)return r;let t;if(e.certificate)t=be(e.certificate);else{let o=process.env[e.secretEnv||""]||"";if(!o&&e.ephemeral&&process.stdin.isTTY&&process.stderr.isTTY&&(o=await D(`Client secret for app ${e.clientId}: `)),!o)throw new B(`no client secret for app ${e.clientId}`,{hint:`set ${e.secretEnv}, or pass --certificate <pem|pfx>`});t=o}return e.ephemeral&&R.set(n,t),t}function Ce(e,n){if(e instanceof P)throw e;let r=e instanceof F?e:N();if(r)throw new P(`cannot reach login.microsoftonline.com: ${r.message}`,{hint:"check the network and proxy (HTTPS_PROXY)"});let t=M(e);if(!t)throw e;if(!(e.name==="ServerError"||t.codes.length>0)){let f=(t.description.split(/\r?\n/)[0]??"").split(". ")[0];throw new B(`cannot sign in as app ${n.clientId}: ${f}`,{hint:"check --tenant, and --certificate if given"})}let c=t.codes.find(f=>f in z),a=(c!==void 0?z[c]:"check --client-id, --tenant and the secret or certificate").replace("{where}",ke(n)).replace("{tenant}",n.tenant);throw new B(`sign-in as app ${n.clientId} failed: ${t.description}`,{code:t.error,hint:a})}async function Pe(e,n){let r=await Te(e),t=await import("./dist-ILNYGTM2.js"),o;try{o=await new t.ConfidentialClientApplication({auth:{clientId:e.clientId??"",authority:`https://login.microsoftonline.com/${e.tenant}`,...typeof r=="string"?{clientSecret:r}:{clientCertificate:r}},system:{networkClient:new H}}).acquireTokenByClientCredential({scopes:[n]})}catch(a){Ce(a,e)}if(!o?.accessToken)throw new B(`sign-in as app ${e.clientId} failed: no token returned`,{hint:"check --client-id, --tenant and the secret or certificate"});let c=o.expiresOn?o.expiresOn.getTime()/1e3:Date.now()/1e3;return[o.accessToken,c]}async function He(e,n,r,t){let o=JSON.stringify([e.clientId,e.tenant,n]),c=$.get(o);if(c&&!r&&c[1]-Date.now()/1e3>120)return t(` token: process (${e.name})`),c[0];t(` token: client credentials (${e.name}${r?", forced":""})`);let[a,f]=await Pe(e,n);return Ie(e,_(a)),$.set(o,[a,f]),a}function Ie(e,n){O(e.name,null,K(e.tenant)?e.tenant:null,n);let r=n?.appid||n?.azp;if(typeof r=="string"&&r&&r.toLowerCase()!==(e.clientId??"").toLowerCase())throw new B(`the token is for app ${r}, expected ${e.clientId}`)}function Me(){$.clear(),R.clear()}export{Ee as a,be as b,Te as c,Pe as d,He as e,Ie as f,Me as g};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{B as V,C as f,D as m,E as d,G as Y,I as h,P as v,a as B,b as A,d as _,e as P,f as z,h as j,i as D,k as W,l as H,m as J,n as $,o as i,p as U,q as y,r as T,t as S,w as L}from"./chunk-TXVNEV3M.js";import{b as G}from"./chunk-5SBBTR3Y.js";import{e as F}from"./chunk-S4KF5Z3S.js";import{b as I,d as E,j as C}from"./chunk-WXOTXJNG.js";var Z={owner:0,access:1,"aad-group":2,"aad-office":3},K=new Map(Object.entries(Z).map(([e,a])=>[a,e])),re=["Create","Read","Write","Delete","Append","AppendTo","Assign","Share"],ee="name,teamtype,azureactivedirectoryobjectid,membershiptype,isdefault,_businessunitid_value,_administratorid_value,description,teamid",Q="name,ismanaged,_businessunitid_value,_parentrootroleid_value,roleid";function M(){return Y(`odata.include-annotations="${W}"`)}function ce(e){return e.service.origin}function te(e){return typeof e=="number"&&K.has(e)?K.get(e):e===void 0?null:e}async function N(e,a,t){let n="fullname,domainname,isdisabled,_businessunitid_value,azureactivedirectoryobjectid,accessmode,systemuserid";t.toLowerCase()==="me"&&(t=d(await m(e,a,"GET","WhoAmI")).UserId);let s=A(t)?`systemuserid eq ${_(t)}`:`domainname eq ${P(t)}`,r=y(d(await m(e,a,"GET","systemusers",{params:[["$select",n],["$filter",s]],headers:M()})).value);if(!r.length)throw new E(`no user '${t}'`,{service:"dataverse",hint:"use me, a user id, or a sign-in name"});return r[0]}async function k(e,a,t){let n=A(t)?`teamid eq ${_(t)}`:`name eq ${P(t)}`,s=y(d(await m(e,a,"GET","teams",{params:[["$select",ee],["$filter",n]],headers:M()})).value);if(!s.length)throw new E(`no team '${t}'`,{service:"dataverse",hint:"run: ppdo-cli dv team list --name '*<part>*'"});if(s.length>1)throw new I(`${s.length} teams are named '${t}'; use an id`,{hint:s.map(r=>r.teamid).join(", ")});return s[0]}async function ae(e,a,t,n=null){if(A(t)){let o=d(await m(e,a,"GET",`roles(${_(t)})`,{params:[["$select",Q]]}));if(!n||i(o,"_businessunitid_value")===n)return o;t=o.name}let s=`name eq ${P(t)} and `+(n?`_businessunitid_value eq ${n}`:"_parentroleid_value eq null"),r=y(d(await m(e,a,"GET","roles",{params:[["$select",Q],["$filter",s]]})).value);if(!r.length)throw new E(`no role '${t}'`+(n?" in that business unit":""),{service:"dataverse",hint:"run: ppdo-cli dv role list --name '*<part>*'"});return r[0]}function q(e,a){return $(i(e,`${a}${H}`),i(e,a))}function ne(e){let a=i(e,"teamtype");return T({name:i(e,"name"),type:te(a),business_unit:q(e,"_businessunitid_value"),default:J(i(e,"isdefault"))?e.isdefault:null,entra_group:i(e,"azureactivedirectoryobjectid"),membership:a===2||a===3?q(e,"membershiptype"):null,id:i(e,"teamid")})}async function fe(e){let a=e.args,t=await f(e);G(e,t,"GET","teams",null);let n=[],s=v(a.type);s&&n.push(`teamtype eq ${Z[s]}`);let r=v(a.name);r&&n.push(D("name",r));let o=[["$select",ee],["$orderby","name"]];n.length&&o.push(["$filter",n.join(" and ")]);let[c]=await h(e,t,"teams",o,M(),L(a),"teams");await e.emit(c.map(ne))}async function O(e,a,t){let[n]=await h(e,a,`teams(${t})/teamroles_association`,[["$select","name"]],null,null);return S(n.map(s=>i(s,"name")),s=>s)}async function ye(e){let a=await f(e),t=await k(e,a,String(e.args.team)),[n]=await h(e,a,`teams(${t.teamid})/teammembership_association`,[["$select","fullname,domainname"],["$orderby","fullname"]],null,L(e.args),"members");await e.emit(T({...ne(t),description:i(t,"description"),roles:await O(e,a,t.teamid),members:n.map(s=>({name:i(s,"fullname"),upn:i(s,"domainname")}))}))}async function ie(e,a){let t=e.args,n=await f(e);G(e,n,a?"POST":"DELETE","teams",Buffer.from("{}"));let[s,r]=await n.lookups(async()=>{let c=await k(e,n,String(t.team));return[c,await ae(e,n,String(t.role),i(c,"_businessunitid_value"))]}),o=`teams(${s.teamid})/teamroles_association`;if(a){let c={"@odata.id":`${ce(n)}/api/data/v9.2/roles(${r.roleid})`};await m(e,n,"POST",`${o}/$ref`,{body:Buffer.from(C(c),"utf8")})}else await m(e,n,"DELETE",`${o}(${r.roleid})/$ref`);await e.emit({team:i(s,"name"),role:i(r,"name"),roles:await O(e,n,s.teamid)})}function Re(e){return ie(e,!0)}function $e(e){return ie(e,!1)}var X=["Basic","Local","Deep","Global"];async function se(e,a,t,n,s,r=m){if(n){let l=d(await r(e,a,"GET",`EntityDefinitions(LogicalName='${n}')`,{params:[["$select","SchemaName"]]})).SchemaName,p={};for(let R of re){let g=t.filter(u=>String(i(u,"PrivilegeName")??"").toLowerCase()===`prv${R}${l}`.toLowerCase()).map(u=>i(u,"Depth")),w="none";if(g.length){w=g[0];for(let u of g.slice(1))X.indexOf(u)>X.indexOf(w)&&(w=u)}p[R.toLowerCase()]=w}return{table:n,access:p}}let o=L(e.args),c=S(t.map(l=>({privilege:i(l,"PrivilegeName"),depth:i(l,"Depth")})),l=>l.privilege||"");return o!==null&&c.length>o&&(F(`showing the first ${o} of ${c.length} ${s}; pass --table <name>, --limit n or --all`),c=c.slice(0,o)),{total:t.length,privileges:c}}async function he(e){let a=e.args,t=await f(e);G(e,t,"GET","roles",null);let n=v(a.name),s=["_parentroleid_value eq null",...n?[D("name",n)]:[]],[r]=await h(e,t,"roles",[["$select","name,ismanaged,modifiedon,roleid"],["$filter",s.join(" and ")],["$orderby","name"]],null,L(a),"roles");await e.emit(r.map(o=>({name:i(o,"name"),managed:i(o,"ismanaged"),modified:i(o,"modifiedon"),id:i(o,"roleid")})))}async function ve(e){let a=e.args,t=await f(e),n=await ae(e,t,String(a.role)),[s,r]=j("RetrieveRolePrivilegesRole",[["RoleId",n.roleid]]),o=y(d(await m(e,t,"GET",s,{params:r})).RolePrivileges);await e.emit({name:n.name,managed:i(n,"ismanaged"),id:n.roleid,...await se(e,t,o,v(a.table),"privileges")})}async function be(e){let a=await f(e),t=await N(e,a,String(e.args.user)),n=t.systemuserid,[s]=await h(e,a,`systemusers(${n})/systemuserroles_association`,[["$select","name"]],null,null),[r]=await h(e,a,`systemusers(${n})/teammembership_association`,[["$select","name,teamtype,isdefault,teamid"]],null,null),o=[];for(let c of S(r,l=>String(i(l,"name")||"").toLowerCase()))o.push({name:i(c,"name"),type:te(i(c,"teamtype")),roles:await O(e,a,c.teamid)});await e.emit(T({name:i(t,"fullname"),upn:i(t,"domainname"),business_unit:q(t,"_businessunitid_value"),disabled:i(t,"isdisabled"),access_mode:q(t,"accessmode"),entra_object_id:i(t,"azureactivedirectoryobjectid"),id:n,roles:S(s.map(c=>i(c,"name")),c=>c),teams:o}))}async function _e(e){let a=await f(e),t=await N(e,a,String(e.args.user)),n=y(d(await m(e,a,"GET",`systemusers(${t.systemuserid})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`)).RolePrivileges);await e.emit({user:$(i(t,"domainname"),i(t,"fullname")),id:t.systemuserid,...await se(e,a,n,v(e.args.table),"privileges")})}async function le(e,a,t){B(t,"entity set name");let n=y(d(await m(e,a,"GET","EntityDefinitions",{params:[["$select","LogicalName"],["$filter",`EntitySetName eq ${P(t)}`]]})).value);if(!n.length)throw new E(`no table with entity set '${t}'`,{service:"dataverse",hint:"use the plural entity set name, e.g. accounts"});return n[0].LogicalName}function oe(e){return(e||"").split(",").map(a=>z(a)).filter(a=>a&&a!=="None").map(a=>a.replace(/Access$/,"").toLowerCase())}async function Ee(e){let a=e.args;V(a,{user:"--user",team:"--team"},!0,"dv access origin");let t=String(a.entityset),n=await f(e),s=await le(e,n,t),r=_(String(a.id)),o,c,l,p=v(a.user);if(p){let b=await N(e,n,p);[o,c,l]=[b.systemuserid,$(i(b,"domainname"),i(b,"fullname")),"systemusers"]}else{let b=await k(e,n,String(a.team));[o,c,l]=[b.teamid,i(b,"name"),"teams"]}let[R,g]=j("RetrieveAccessOrigin",[["ObjectId",r],["LogicalName",s],["PrincipalId",o]],new Set(["LogicalName"])),w=i(d(await m(e,n,"GET",R,{params:g})),"Response"),u=C({"@odata.id":`${t}(${r})`}),x=i(d(await m(e,n,"GET",`${l}(${o})/Microsoft.Dynamics.CRM.RetrievePrincipalAccess(Target=@t)`,{params:[["@t",u]]})),"AccessRights");await e.emit({record:`${t}(${r})`,principal:c,rights:oe(x),origin:w})}async function Pe(e){let a=e.args,t=String(a.entityset),n=await f(e);B(t,"entity set name");let s=_(String(a.id)),r=C({"@odata.id":`${t}(${s})`}),o=y(d(await m(e,n,"GET","RetrieveSharedPrincipalsAndAccess(Target=@t)",{params:[["@t",r]]})).PrincipalAccesses),c=[];for(let l of o){let p=U(i(l,"Principal")),R=String(i(p,"@odata.type")||""),g=R.slice(R.lastIndexOf(".")+1),w=$($(i(p,"ownerid"),i(p,"teamid")),i(p,"systemuserid")),u=null;try{if(g==="team")u=i(await k(e,n,w),"name");else if(g==="systemuser"){let x=await N(e,n,w);u=$(i(x,"domainname"),i(x,"fullname"))}}catch{}c.push(T({principal:u,type:g==="systemuser"?"user":g,id:w,rights:oe(i(l,"AccessMask"))}))}await e.emit(c)}export{Z as a,K as b,re as c,N as d,k as e,ae as f,fe as g,ye as h,Re as i,$e as j,se as k,he as l,ve as m,be as n,_e as o,le as p,oe as q,Ee as r,Pe as s};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{e as y,h as v}from"./chunk-ZNJ4DRCA.js";import{o as M,t as N,u as k}from"./chunk-WIA546AL.js";import{promises as l}from"node:fs";import*as d from"node:path";var F=class{files=new Map;keep=new Set;keepFile(e){this.keep.add(e.replaceAll("\\","/").toLowerCase())}put(e,t){e=v(e.replaceAll("\\","/"));let a=e.toLowerCase(),s=this.files.get(a);s===void 0?this.files.set(a,{rel:e,data:t}):s.data=t}xml(e,t){y(e).trim()||(e+=".xml"),this.put(e,N(t))}text(e,t){y(e).trim()||(e+=".xml"),this.put(e,k(t))}bytes(e,t){this.put(e,t)}get(e){return this.files.get(e.replaceAll("\\","/").toLowerCase())?.data}readXml(e){let t=this.get(e);return t===void 0?null:M(t)}get size(){return this.files.size}};async function C(n){let e=new Map,t=d.resolve(n),a;try{a=await l.readdir(t,{recursive:!0,withFileTypes:!0})}catch(i){if(i.code==="ENOENT"||i.code==="ENOTDIR")return e;throw i}let s=a.filter(i=>i.isFile()),g=await f(s,async i=>{let p=d.join(i.parentPath,i.name);try{return{full:p,size:(await l.stat(p)).size}}catch{return{full:p,size:-1}}});for(let{full:i,size:p}of g){let h=d.relative(t,i).replaceAll("\\","/");e.set(h.toLowerCase(),{rel:h,full:i,size:p})}return e}var S=class{pending;constructor(e){this.pending=(async()=>{let t=await C(e),a=await f([...t],async([s,g])=>{try{return[s,new Uint8Array(await l.readFile(g.full))]}catch{return[s,null]}});return{existing:t,data:new Map(a)}})(),this.pending.catch(()=>{})}result(){return this.pending}};function U(n,e){return n.length===e.length&&Buffer.compare(n,e)===0}function E(n){return n.sort((e,t)=>e<t?-1:e>t?1:0)}async function q(n,e,t){let a=t.keep??["resources/"],s,g;t.snapshot?{existing:s,data:g}=await t.snapshot.result():[s,g]=[await C(e),new Map];let i=d.resolve(e),p=await f([...n.files],async([o,r])=>{let u=s.get(o);if(u===void 0||u.size!==r.data.length)return{slot:r,old:u,equal:!1};if(g.has(o)){let c=g.get(o);return c!==null?{slot:r,old:u,equal:U(c,r.data)}:{slot:r,old:void 0,equal:!1}}try{return{slot:r,old:u,equal:U(new Uint8Array(await l.readFile(u.full)),r.data)}}catch(c){if(c.code==="ENOENT")return{slot:r,old:void 0,equal:!1};throw c}}),h=[],x=[],w=[],P=0;for(let{slot:o,old:r,equal:u}of p)u?P++:r!==void 0?(x.push(r.rel),w.push([r.full,o.data])):(h.push(o.rel),w.push([d.join(i,...o.rel.split("/")),o.data]));let A=E([...s].filter(([o])=>!n.files.has(o)&&!n.keep.has(o)&&!a.some(r=>o.startsWith(r))).map(([,o])=>o.rel)),m=t.delete?A:[];if(!t.check){let o=new Set(w.map(([r])=>d.dirname(r)));for(let r of o)await l.mkdir(r,{recursive:!0});if(await f(w,([r,u])=>R(r,u)),m.length){let r=m.map(c=>s.get(c.toLowerCase()).full);await f(r,T);let u=[...new Set(r.map(c=>d.dirname(c)))].sort((c,z)=>z.length-c.length);for(let c of u)await b(c,i)}}return{added:E(h),changed:E(x),deleted:m,stale:t.delete?[]:A,unchanged:P}}async function f(n,e,t=16){let a=new Array(n.length),s=0,g=async()=>{for(;s<n.length;){let i=s++;a[i]=await e(n[i])}};return await Promise.all(Array.from({length:Math.min(t,n.length)},g)),a}async function R(n,e){try{await l.writeFile(n,e)}catch(t){let a=t.code;if(a==="ENOENT")await l.mkdir(d.dirname(n),{recursive:!0}),await l.writeFile(n,e);else if(a==="EPERM"||a==="EACCES")await l.chmod(n,438),await l.writeFile(n,e);else throw t}}async function T(n){try{await l.unlink(n)}catch(e){let t=e.code;if(t==="ENOENT")return;if(t==="EPERM"||t==="EACCES"){await l.chmod(n,438),await l.unlink(n);return}throw e}}async function b(n,e){let t=e.replace(/[\\/]+$/,"");for(;n.length>t.length&&n.toLowerCase().startsWith(t.toLowerCase());){try{if((await l.readdir(n)).length)return;await l.rmdir(n)}catch{return}n=d.dirname(n)}}export{F as a,C as b,S as c,q as d,f as e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{d as z}from"./chunk-PYTSDUPY.js";import{C as Q,D as X,E as ee,I as te,L as ne,P as C,Q as oe,b as W,d as Z,m as q,n as K,o as r,p as D,q as R,t as B,u as G}from"./chunk-TXVNEV3M.js";import{a as V}from"./chunk-UCTMKA2J.js";import{b as Y}from"./chunk-5SBBTR3Y.js";import{e as T}from"./chunk-S4KF5Z3S.js";import{b as A}from"./chunk-WXOTXJNG.js";import{readFileSync as U}from"node:fs";import{gunzipSync as le}from"node:zlib";var ue=["resolved","not-found","type-unsupported"],ce=new Map([[3,"relationship-internal"],[4,"choice-value"],[5,"lookup-value"],[6,"view-column"],[7,"label"],[8,"relationship-condition"],[11,"relationship-role"],[12,"relationship-role-link"],[14,"key"],[46,"table-map"],[47,"column-map"],[48,"ribbon-command"],[49,"ribbon-context-group"],[50,"ribbon-customization"],[52,"ribbon-rule"],[53,"ribbon-tab-command-map"],[55,"ribbon-diff"],[68,"custom-control-default"],[88,"app-role"],[90,"plugin-type"],[93,"step-image"]]),ae=500,pe=new Map([[20,["role","name",null]],[26,["savedquery","name","returnedtypecode"]],[29,["workflow","uniquename|name","primaryentity"]],[36,["template","title","templatetypecode"]],[48,["ribboncommand","command","entity"]],[49,["ribboncontextgroup","contextgroupid","entity"]],[50,["ribboncustomization","entity","entity"]],[52,["ribbonrule","ruleid","entity"]],[53,["ribbontabtocommandmap","controlid","entity"]],[55,["ribbondiff","diffid","entity"]],[59,["savedqueryvisualization","name","primaryentitytypecode"]],[60,["systemform","name","objecttypecode"]],[61,["webresource","name",null]],[62,["sitemap","sitemapnameunique|sitemapname",null]],[63,["connectionrole","name",null]],[66,["customcontrol","name",null]],[70,["fieldsecurityprofile","name",null]],[80,["appmodule","uniquename|name",null]],[90,["plugintype","typename",null]],[91,["pluginassembly","name",null]],[92,["sdkmessageprocessingstep","name",null]],[93,["sdkmessageprocessingstepimage","name",null]],[95,["serviceendpoint","name",null]],[300,["canvasapp","name",null]],[380,["environmentvariabledefinition","schemaname",null]],[381,["environmentvariablevalue","schemaname",null]]]),se=["PicklistAttributeMetadata","MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata","BooleanAttributeMetadata"],fe="00000000-0000-0000-0000-000000000000";function ie(t){if(typeof t!="string"||!W(t))return null;let o=Z(t);return o===fe?null:o}function I(t){if(t==null)return"None";if(t===!0)return"True";if(t===!1)return"False";if(typeof t=="number")return String(t);if(typeof t=="string"){let o=t.includes("'")&&!t.includes('"')?'"':"'",s=t.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");return o==="'"&&(s=s.replace(/'/g,"\\'")),o+s+o}return Array.isArray(t)?"["+t.map(I).join(", ")+"]":"{"+Object.entries(t).map(([o,s])=>`${I(o)}: ${I(s)}`).join(", ")+"}"}var L=(t,o)=>`${t}|${o}`;function de(t){let o=new Map,s=(u,i,p=null)=>{let f=ie(i);if(typeof u!="number"||!Number.isInteger(u)||f===null)throw new A(`not a component (type, id): ${I(u)}, ${I(i)}`);let b=L(u,f),y=o.get(b);o.set(b,{key:[u,f],parent:y?.parent||ie(p)})},c=0;for(let u of t){if(c++,!u.trim())continue;let i;try{i=V(u)}catch(p){throw new A(`line ${c} is not JSON: ${p.message}`)}if("requiredcomponentobjectid"in i||"dependentcomponentobjectid"in i)for(let p of["required","dependent"])s(r(i,p+"componenttype"),r(i,p+"componentobjectid"),r(i,p+"componentparentid"));else"componenttype"in i?s(r(i,"componenttype"),r(i,"objectid")):s(r(i,"type"),r(i,"id"),r(i,"parent_id"))}return o}function re(t){return ne(t)}function ge(t,o){for(let s of o.split("|"))if(q(r(t,s)))return t[s];return null}var ye=["type","id","type_name","name_status","name","logical_name","schema_name","parent_type","parent_id","parent_logical_name","parent_schema_name","source"];function w(t,o,s,c={}){let u={};for(let i of ye)u[i]=null;Object.assign(u,{type:t,id:o,type_name:z.get(t)??ce.get(t)??null,name_status:s});for(let[i,p]of Object.entries(c))i in u&&(u[i]=p===void 0?null:p);return u}var F=class{constructor(o,s){this.rt=o;this.client=s}tablesCache=null;async get(o,s){return ee(await X(this.rt,this.client,"GET",o,{params:s}))}async all(o,s){return(await te(this.rt,this.client,o,s,null,null))[0]}async tables(){if(this.tablesCache===null){let o=await this.get("EntityDefinitions",[["$select","MetadataId,LogicalName,SchemaName,DisplayName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute,ObjectTypeCode"]]);this.tablesCache=new Map(R(o.value).map(s=>[String(s.MetadataId).toLowerCase(),s]))}return this.tablesCache}async tableByName(o){if(!q(o))return null;for(let s of(await this.tables()).values())if(s.LogicalName===o)return s;return null}async batch(o){let s=[],c=o.map(u=>({method:"GET",path:u}));for await(let[,,u]of oe(this.rt,this.client,c,!1,!0))s.push(...u);return s}};async function we(t,o,s){let c=new F(t,o),u=new Map,i=(e,n,a)=>{u.set(L(e,n),{key:[e,n],row:a})},p=new Map;for(let{key:e}of s.values()){let[n,a]=e;p.has(n)||p.set(n,[]),p.get(n).push(a)}let f=e=>p.get(e)??[],b=(e,n)=>s.get(L(e,n))?.parent??null,y=await c.tables(),S=async e=>{let n=await c.tableByName(e);return{parent_type:1,parent_id:n?n.MetadataId:null,parent_logical_name:e,parent_schema_name:n?n.SchemaName:null}};for(let e of f(1)){let n=y.get(e);i(1,e,n?w(1,e,"resolved",{name:re(r(n,"DisplayName")),logical_name:n.LogicalName,schema_name:n.SchemaName,source:"EntityDefinitions"}):w(1,e,"not-found",{source:"EntityDefinitions"}))}let h=new Map,$=B(G(f(2).map(e=>b(2,e)).filter(e=>e!==null&&y.has(e))),e=>e),x=await c.batch($.map(e=>`EntityDefinitions(${e})/Attributes?$select=MetadataId,LogicalName,SchemaName,DisplayName`));if($.forEach((e,n)=>{let a=x[n];if(a)for(let m of R(r(D(r(a,"body")),"value")))h.set(String(m.MetadataId).toLowerCase(),[m,y.get(e)])}),f(2).some(e=>!h.has(e))){let e=await c.get("EntityDefinitions",[["$select","MetadataId"],["$expand","Attributes($select=MetadataId,LogicalName,SchemaName,DisplayName)"]]);for(let n of R(e.value))for(let a of R(r(n,"Attributes"))){let m=String(a.MetadataId).toLowerCase();h.has(m)||h.set(m,[a,y.get(String(n.MetadataId).toLowerCase())??{}])}}for(let e of f(2)){let n=h.get(e);if(n){let[a,m]=n;i(2,e,w(2,e,"resolved",{name:re(r(a,"DisplayName")),logical_name:a.LogicalName,schema_name:a.SchemaName,parent_type:1,parent_id:r(m,"MetadataId"),parent_logical_name:r(m,"LogicalName"),parent_schema_name:r(m,"SchemaName"),source:"Attributes"}))}else i(2,e,w(2,e,"not-found",{source:"Attributes"}))}let me=[...f(10),...f(3)],H=new Map;if(me.length){let e=await c.get("RelationshipDefinitions",[["$select","MetadataId,SchemaName"]]);for(let n of R(e.value))H.set(String(n.MetadataId).toLowerCase(),n)}for(let e of[10,3])for(let n of f(e)){let a=H.get(n);i(e,n,a?w(e,n,"resolved",{name:a.SchemaName,schema_name:a.SchemaName,source:"RelationshipDefinitions"}):w(e,n,e===10?"not-found":"type-unsupported",{source:"RelationshipDefinitions"}))}if(f(14).length){let e=new Map,n=await c.get("EntityDefinitions",[["$select","MetadataId"],["$expand","Keys($select=MetadataId,LogicalName,SchemaName)"]]);for(let a of R(n.value))for(let m of R(r(a,"Keys")))e.set(String(m.MetadataId).toLowerCase(),[m,y.get(String(a.MetadataId).toLowerCase())??{}]);for(let a of f(14)){let m=e.get(a);if(m){let[_,N]=m;i(14,a,w(14,a,"resolved",{name:_.SchemaName,logical_name:_.LogicalName,schema_name:_.SchemaName,parent_type:1,parent_id:r(N,"MetadataId"),parent_logical_name:r(N,"LogicalName"),parent_schema_name:r(N,"SchemaName"),source:"Keys"}))}else i(14,a,w(14,a,"not-found",{source:"Keys"}))}}if(f(9).length){let e=new Map,n=await c.get("GlobalOptionSetDefinitions",[["$select","MetadataId,Name"]]);for(let l of R(n.value))e.set(String(l.MetadataId).toLowerCase(),l);let a=new Set;for(let l of f(9)){let g=e.get(l);g?i(9,l,w(9,l,"resolved",{name:g.Name,schema_name:g.Name,source:"GlobalOptionSetDefinitions"})):a.add(l)}let m=new Set;for(let{key:l,parent:g}of s.values())l[0]===2&&g&&m.add(g);for(let l of f(1))m.add(l);let _=[...y.keys()],N=[_.filter(l=>m.has(l)),_.filter(l=>!m.has(l))];for(let l=0;l<N.length;l++){let g=N[l];if(!a.size||!g.length)continue;l===1&&T(`looking for ${a.size} local choice(s) in the choice columns of every other table`);let j=g.flatMap(d=>se.map(k=>`EntityDefinitions(${d})/Attributes/Microsoft.Dynamics.CRM.${k}?$select=MetadataId,LogicalName,SchemaName&$expand=OptionSet($select=MetadataId,Name,IsGlobal)`));(await c.batch(j)).forEach((d,k)=>{let M=y.get(g[Math.floor(k/se.length)]);for(let v of R(r(D(r(d,"body")),"value"))){let P=D(r(v,"OptionSet")),E=String(K(r(P,"MetadataId"),"")).toLowerCase();a.has(E)&&(a.delete(E),i(9,E,w(9,E,"resolved",{name:r(P,"Name"),schema_name:r(P,"Name"),parent_type:2,parent_id:v.MetadataId,parent_logical_name:`${M.LogicalName}.${v.LogicalName}`,parent_schema_name:`${M.SchemaName}.${v.SchemaName}`,source:"Attributes/OptionSet"})))}})}for(let l of a)i(9,l,w(9,l,"not-found",{source:"GlobalOptionSetDefinitions"}))}let J=new Map;for(let e of y.values())J.set(r(e,"ObjectTypeCode"),e);for(let[e,n]of p){if([1,2,3,9,10,14].includes(e))continue;let a=pe.get(e),m=a?await c.tableByName(a[0]):e>=1e4?J.get(e)??null:null;if(!m){for(let d of n)i(e,d,w(e,d,"type-unsupported"));continue}let _=m.EntitySetName,N=m.PrimaryIdAttribute,l=a?a[1]:K(r(m,"PrimaryNameAttribute"),N),g=a?a[2]:null,j=G([N,...l.split("|"),...g?[g]:[]]).join(","),O=new Map;for(let d=0;d<n.length;d+=ae){let k=n.slice(d,d+ae).map(M=>`'${M}'`).join(",");for(let M of await c.all(_,[["$select",j],["$filter",`Microsoft.Dynamics.CRM.In(PropertyName='${N}',PropertyValues=[${k}])`]]))O.set(String(M[N]).toLowerCase(),M)}for(let d of n){let k=O.get(d);if(!k){i(e,d,w(e,d,"not-found",{source:_}));continue}let M=g?r(k,g):null,v=g&&M!==null&&M!=="none"?await S(M):{};i(e,d,w(e,d,"resolved",{name:ge(k,l),source:_,type_name:z.get(e)||ce.get(e)||m.LogicalName,...v}))}}return B([...u.values()],e=>[e.key[0],e.key[1]]).map(e=>e.row)}function be(t){let o;t==="-"?o=U(0,"utf8"):t.toLowerCase().endsWith(".gz")?o=le(U(t)).toString("utf8"):o=U(t,"utf8");let s="\\n\\r\\x0b\\x0c\\x1c\\x1d\\x1e\\x85\u2028\u2029",c=o.split(new RegExp(`\\r\\n|[${s}]`));return c.length&&c[c.length-1]===""&&c.pop(),c}async function xe(t){let o=t.args,s=C(o.file),c=C(o.type),u=C(o.component);if(!s&&!(c&&u))throw new A("give <type> <component>, or --file with components to name");let i=await Q(t);Y(t,i,"GET","EntityDefinitions",null);let p=new Map;if(s)for(let[S,h]of de(be(s)))p.set(S,h);if(c&&u){let{componentId:S,componentType:h}=await import("./lifecycle-OJRM7K2I.js"),$=await h(t,i,c),x=await S(t,i,$,u,c);p.has(L($,x))||p.set(L($,x),{key:[$,x],parent:null})}let f=await we(t,i,p),b={};for(let S of ue)b[S]=f.filter(h=>h.name_status===S).length;let y=C(o.save);if(y){let{save:S}=await import("./dependency-U6OQA5PS.js");await S(y,f),await t.emit({saved:y,components:f.length,...b})}else await t.emit(f);(b["not-found"]||b["type-unsupported"])&&T(`${b["not-found"]} not found, ${b["type-unsupported"]} of a type ppdo-cli can't name`)}export{ue as a,ce as b,ae as c,pe as d,I as e,de as f,re as g,ge as h,w as i,we as j,be as k,xe as l};
|