@cldmv/fix-headers 2.1.4 → 2.2.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/README.md +40 -13
- package/bin/fix-headers.mjs +15 -15
- package/dist/index.mjs +14 -14
- package/package.json +2 -2
- package/types/src/core/fix-headers.d.mts +5 -5
- package/types/src/header/parser.d.mts +25 -0
- package/types/src/utils/git.d.mts +17 -0
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**@cldmv/fix-headers** is a multi-language source header normalizer for Node.js projects. It scans a project's files, works out which project each file belongs to from the manifests around it (`package.json`, `pyproject.toml`, `composer.json`, `Cargo.toml`, `go.mod`, …), detects the author from git, and inserts or updates a standard header at the top of every file in that file's own comment syntax.
|
|
4
4
|
|
|
5
|
-
Headers stay correct without hand-editing: `@Date` follows the file's real creation time, `@Last modified time` only moves when the header changes, the `@Copyright` holder and years come from the manifest and the file's history, and `--check` validates existing headers in CI without writing anything. It runs as a `fix-headers` command line tool or as a library from ESM and CommonJS, and one shared config can serve every repository in an organisation.
|
|
5
|
+
Headers stay correct without hand-editing: `@Date` follows the file's real creation time, `@Author` keeps the original author, `@Last modified by` names whoever last edited the file's content and `@Last modified time` only moves when the header changes, the `@Copyright` holder and years come from the manifest and the file's history, and `--check` validates existing headers in CI without writing anything. It runs as a `fix-headers` command line tool or as a library from ESM and CommonJS, and one shared config can serve every repository in an organisation.
|
|
6
6
|
|
|
7
7
|
> _One header format for every file in every repository, detected from the project itself and kept current by a single command._
|
|
8
8
|
|
|
@@ -14,19 +14,17 @@ Headers stay correct without hand-editing: `@Date` follows the file's real creat
|
|
|
14
14
|
|
|
15
15
|
## ✨ What's New
|
|
16
16
|
|
|
17
|
-
### Latest: v2.1
|
|
17
|
+
### Latest: v2.2.1 (October 2026)
|
|
18
18
|
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
- **Repeatable `--input` and no more dependency folders** — every `--input` value is processed, not just the last ([#125](https://github.com/CLDMV/fix-headers/pull/125)), and `node_modules`, `bower_components`, `jspm_packages`, `.pnpm-store` and `.yarn` are never walked, at any depth, even without a `.gitignore` ([#126](https://github.com/CLDMV/fix-headers/pull/126)).
|
|
22
|
-
- [View full v2.1.4 Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.1.4.md)
|
|
19
|
+
- **Development-setup patch, nothing the package ships changed** — the repository's own `fix:headers` run moves to `@cldmv/configs` 1.2.4, whose shared config no longer forces author updates; `dist/`, `bin/`, the types and the runtime dependency are exactly as in v2.2.0.
|
|
20
|
+
- [View full v2.2.1 Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.2.1.md)
|
|
23
21
|
|
|
24
22
|
### Recent Releases
|
|
25
23
|
|
|
24
|
+
- **v2.2.0** (October 2026) — `@Last modified by` names whoever last edited the file's content: a run that only rewrites a header keeps the recorded editor instead of writing the run's identity ([Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.2.0.md))
|
|
25
|
+
- **v2.1.4** (October 2026) — strict JSON, Markdown named with `--input` and files with no or an unhandled extension are skipped and reported instead of getting a JavaScript comment; `--input` is repeatable; dependency folders are never walked; `require()` fails clearly where Node.js cannot load ES modules ([Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.1.4.md))
|
|
26
26
|
- **v2.1.3** (October 2026) — CI and development-dependency maintenance with no runtime change: a skipped PR run can no longer satisfy `✅ Required PR Check` and let a pull request merge before its tests finish ([Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.1.3.md))
|
|
27
27
|
- **v2.1.2** (October 2026) — no runtime change: the repository adopts the shared CLDMV fix-headers config from `@cldmv/configs` and stamps uniform file headers across its own sources ([Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.1.2.md))
|
|
28
|
-
- **v2.1.1** (October 2026) — a file that holds only a header now ends with the header instead of trailing `margin` blank lines; `esbuild` 0.28.2 clears GHSA-g7r4-m6w7-qqqr ([Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.1.1.md))
|
|
29
|
-
- **v2.1.0** (September 2026) — `spacing` and `margin` header layout options: every header is framed with empty comment lines and followed by two blank lines ([Changelog](https://github.com/CLDMV/fix-headers/blob/master/docs/changelog/v2/v2.1.0.md))
|
|
30
28
|
|
|
31
29
|
📚 For complete release notes, see the [docs/changelog/](https://github.com/CLDMV/fix-headers/tree/master/docs/changelog/) folder.
|
|
32
30
|
|
|
@@ -37,6 +35,7 @@ Headers stay correct without hand-editing: `@Date` follows the file's real creat
|
|
|
37
35
|
- Finds the project each file belongs to from its manifest (`package.json`, `pyproject.toml` / `setup.cfg` / `setup.py`, `composer.json`, `Cargo.toml`, `go.mod`), whatever the file's type
|
|
38
36
|
- `@Project` is the name from that project's manifest, so a CSS, HTML, YAML or JSONC file in a Python, PHP, Rust or Go project gets that project's name too; the folder name is used only when no manifest provides one. Override it with `projectName`. See [Project name and root](#-project-name-and-root)
|
|
39
37
|
- Auto-detects author and email from git config/commit history
|
|
38
|
+
- Keeps the original `@Author`, and changes `@Last modified by` only when the file's content (everything outside the header) was edited, so a run that only rewrites headers never claims other people's files. See [Author and last modified](#-author-and-last-modified)
|
|
40
39
|
- Supports per-run overrides for every detected value
|
|
41
40
|
- Supports folder inclusion and exclusion configuration; skips only what the project's ignore files (everything git honours) or your own exclusions say
|
|
42
41
|
- Supports monorepos: every file resolves its own project from the nearest manifest in its parent tree
|
|
@@ -124,8 +123,8 @@ Common CLI options:
|
|
|
124
123
|
- `--verbose` - list updated files; together with `--sample-output` or `--diff`, also list each file's field differences (`authorName: found "X", expected "Y"`)
|
|
125
124
|
- `--sample-output` - print the previous/new header and detected values for each changed file
|
|
126
125
|
- `--diff` - print a unified diff of each changed file's header (implies sample output)
|
|
127
|
-
- `--force-author-update`
|
|
128
|
-
- `--force-last-modified-author-update`
|
|
126
|
+
- `--force-author-update` - replace an existing `@Author`/`@Email` with the detected identity (see [Author and last modified](#-author-and-last-modified))
|
|
127
|
+
- `--force-last-modified-author-update` - write the detected identity as `@Last modified by` on every file, edited or not (rarely needed, see [Author and last modified](#-author-and-last-modified))
|
|
129
128
|
- `--use-gpg-signer-author` (the signing key's UID name, with the OpenPGP UID comment dropped)
|
|
130
129
|
- `--cwd <path>`
|
|
131
130
|
- `--input <path>` (repeatable) - process these files and folders instead of the whole project: the union of every value, each file once (`--input src/a.mjs --input src/b.mjs --input scripts`). A named file whose type cannot carry a header (see [Supported file types](#-supported-file-types)) is reported as `skipped: <file> (<reason>)` and left unchanged
|
|
@@ -178,8 +177,8 @@ Important options:
|
|
|
178
177
|
- `authorName?: string`
|
|
179
178
|
- `authorEmail?: string`
|
|
180
179
|
- `company?: string` - appends to `@Author` as `Name <Company>`
|
|
181
|
-
- `forceAuthorUpdate?: boolean` -
|
|
182
|
-
- `forceLastModifiedAuthorUpdate?: boolean` -
|
|
180
|
+
- `forceAuthorUpdate?: boolean` - replace an existing `@Author`/`@Email` with the detected (or overridden) identity. Off by default: `@Author` is the file's original author, and an existing value is never changed; a missing one is filled in. See [Author and last modified](#-author-and-last-modified)
|
|
181
|
+
- `forceLastModifiedAuthorUpdate?: boolean` - write the detected (or overridden) identity as `@Last modified by` on every file, whether its content was edited or not, and update files whose only difference is that identity. Off by default, and not needed for normal use: `@Last modified by` already becomes the run's identity on every file whose content was edited. See [Author and last modified](#-author-and-last-modified)
|
|
183
182
|
- `useGpgSignerAuthor?: boolean` - take the detected `@Author` name from the user ID of the OpenPGP key git signs commits with (`user.signingkey`, read through `gpg.openpgp.program` / `gpg.program` / `gpg`; the first user ID that is not revoked or expired). The OpenPGP UID comment is dropped, so `Nate Corcoran (2023 PC) <nate@example.com>` becomes `Nate Corcoran` (with `company: "CLDMV"`: `Nate Corcoran <CLDMV>`). It describes whoever runs the tool, whatever the last commit is — a squash merge made by GitHub or a bot has no locally verifiable signer. With no readable OpenPGP signing key (none configured, `gpg.format` is `ssh`/`x509`, or gpg is unavailable) it falls back to the last commit's signer (`%GS`), then `git config user.name`, then the last commit's author
|
|
184
183
|
- `companyName?: string` - the `@Copyright` holder for every file, instead of the one the project's manifests provide. There is no built-in default: unset, the holder comes from the manifests, and with none it is left out of the line (see [Copyright holder](#-copyright-holder))
|
|
185
184
|
- `copyrightStartYear?: number` - the `@Copyright` start year for every file. Unset (the default): each file's start year is the year of its own `@Date`, see [Copyright years](#-copyright-years)
|
|
@@ -344,6 +343,34 @@ The filesystem creation time is the earlier of the file's birth time and its mod
|
|
|
344
343
|
|
|
345
344
|
---
|
|
346
345
|
|
|
346
|
+
## 👤 Author and last modified
|
|
347
|
+
|
|
348
|
+
`@Author` / `@Email` name the file's original author, and `@Last modified by` / `@Last modified time` its last edit.
|
|
349
|
+
|
|
350
|
+
- **`@Author` / `@Email`** are written once. An existing value is never changed, whoever runs the tool, unless `forceAuthorUpdate` is set. A file without one gets the detected identity.
|
|
351
|
+
- **`@Last modified by`** changes only when the file's **content** was edited: everything outside the header. It then becomes the identity detected for the run (`authorName` / `authorEmail`, or git as described under `useGpgSignerAuthor`). Changes fix-headers makes to the header on its own, such as the date format (`normalizeDateFormat`), an epoch repair, `@Date` (`fixCreatedDate`), a time zone conversion, the frame, spacing or margin, or the `@Project`, `@Filename` or `@Copyright` values, keep the recorded editor.
|
|
352
|
+
- **`@Last modified time`** is restamped with the time of the run whenever fix-headers rewrites the header, header-only rewrites included. A file whose header is already current is not touched.
|
|
353
|
+
|
|
354
|
+
Whether the content was edited is decided against git `HEAD`. The header is taken out of the file and out of its `HEAD` version (`git show HEAD:<path>`), along with the blank lines after it, and the rest is compared:
|
|
355
|
+
|
|
356
|
+
| File | Content edited? | `@Author` | `@Last modified by` | `@Last modified time` |
|
|
357
|
+
| ------------------------------------------------------------ | -------------------------- | -------------------------- | ------------------- | --------------------- |
|
|
358
|
+
| Tracked, body the same as at `HEAD`, header rewritten | no | kept | kept | now |
|
|
359
|
+
| Tracked, body differs from `HEAD` | yes | kept | run identity | now |
|
|
360
|
+
| Not in `HEAD` (new, untracked or ignored, or no commits yet) | yes | kept (filled when missing) | run identity | now |
|
|
361
|
+
| Outside a git work tree, header rewritten | cannot tell, treated as no | kept | kept | now |
|
|
362
|
+
| Header already current, content not edited | no | unchanged | unchanged | unchanged |
|
|
363
|
+
|
|
364
|
+
A missing field is filled with the run identity in every row, and a file without a header gets the run identity in both. Adding a header to a committed file is not a content edit, so a later header-only run by someone else keeps whoever was recorded then.
|
|
365
|
+
|
|
366
|
+
`@Last modified time` also moves for a content edit by the editor already recorded: when the body differs from `HEAD` and the recorded time is older than the file's last commit, the edit has not been stamped yet, so it is restamped. Once stamped, the time is newer than the last commit, and running fix-headers again changes nothing until the next commit.
|
|
367
|
+
|
|
368
|
+
The check compares the working tree with `HEAD`, so run fix-headers before committing (a pre-commit hook, or `npm run fix:headers` before `git commit`). Content committed without a run is not detected later: at that point the body matches `HEAD`.
|
|
369
|
+
|
|
370
|
+
`forceLastModifiedAuthorUpdate` writes the run identity as `@Last modified by` on every file, edited or not. It is the old behaviour for configurations that relied on it; with content-edit detection it is not needed for normal use.
|
|
371
|
+
|
|
372
|
+
---
|
|
373
|
+
|
|
347
374
|
## 📆 Copyright years
|
|
348
375
|
|
|
349
376
|
`@Copyright: Copyright (c) <start>-<end> <companyName> All rights reserved.`
|
|
@@ -541,7 +568,7 @@ With `sampleOutput: true` (CLI: `--sample-output` or `--diff`), every changed en
|
|
|
541
568
|
- `issues` - one `{ field, previous, detected }` entry per header field whose written value differs from the existing header, in header order. Fields: `projectName`, `filename`, `createdAt`, `authorName`, `authorEmail`, `lastModifiedByName`, `lastModifiedByEmail`, `lastModifiedAt`, `copyrightStartYear`, `copyrightEndYear`, `companyName`. Values are the field text as written in the header (dates keep their `date (timestamp)` form); `previous` is `null` when the field was missing.
|
|
542
569
|
- `detectedValues` - the metadata resolved for the file. `projectNameSource` says where `projectName` came from: `{ from: "manifest", driver, manifest, dir }` (the driver, its manifest and the folder it sits in), `{ from: "folder", dir }` (the project root's folder name) or `{ from: "option" }` (`projectName`). `copyrightStartYear` is the start year written for the file, and `copyrightStartYearSource` says where it came from: `"option"` (`copyrightStartYear`) or `"created-date"` (the year of the file's `@Date`, see [Copyright years](#-copyright-years)). The run-level `result.metadata.copyrightStartYear` is the `copyrightStartYear` option, or `null` when it is not set.
|
|
543
570
|
|
|
544
|
-
`issues` compares the existing header against what is actually written, not against the raw detected metadata. fix-headers preserves an existing `@Author`/`@Email` and `@Last modified by`
|
|
571
|
+
`issues` compares the existing header against what is actually written, not against the raw detected metadata. fix-headers preserves an existing `@Author`/`@Email` unless `forceAuthorUpdate` is set, and an existing `@Last modified by` unless the file's content was edited or `forceLastModifiedAuthorUpdate` is set (see [Author and last modified](#-author-and-last-modified)), so those fields only appear when they really change. An updated file always gets a fresh `@Last modified time`, so `lastModifiedAt` is listed for every changed file that already had a header.
|
|
545
572
|
|
|
546
573
|
```js
|
|
547
574
|
const { changes } = await fixHeaders({ dryRun: true, sampleOutput: true });
|
package/bin/fix-headers.mjs
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Ur=Object.defineProperty;var i=(e,t)=>Ur(e,"name",{value:t,configurable:!0});import{realpathSync as jr}from"node:fs";import{fileURLToPath as Po,pathToFileURL as Ro}from"node:url";import{readFile as _r}from"node:fs/promises";import{createRequire as Hr}from"node:module";import{dirname as zr,isAbsolute as Br,resolve as Ze}from"node:path";var Wr=3e4,Yr=new Set(["localhost","127.0.0.1","[::1]"]);function fe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(fe,"isPlainObject");function de(e,t){let r={...e};for(let[n,o]of Object.entries(t))n!=="__proto__"&&(r[n]=fe(r[n])&&fe(o)?de(r[n],o):o);return r}i(de,"mergeConfig");function Qe(e){return e.kind==="file"?e.path:e.href}i(Qe,"describeSource");async function Vr(e){if(e.kind==="file")return{text:await _r(e.path,"utf8"),source:e};let t;try{t=await fetch(e.href,{cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(Wr)})}catch(r){let n=r.cause instanceof Error?r.cause.message:r.message;throw new Error(`Failed to fetch config ${e.href}: ${n}`,{cause:r})}if(!t.ok)throw new Error(`Failed to fetch config ${e.href}: HTTP ${t.status} ${t.statusText}`);return{text:await t.text(),source:{kind:"url",href:t.url}}}i(Vr,"readSource");function Xe(e){if(e.protocol==="http:"&&!Yr.has(e.hostname))throw new Error(`Refusing to fetch config over plain http: ${e.href} (use https)`);return{kind:"url",href:e.href}}i(Xe,"toUrlSource");function Gr(e,t){if(/^https?:\/\//i.test(e))return Xe(new URL(e));if(/^[a-z][a-z\d+.-]+:\/\//i.test(e))throw new Error(`Unsupported extends URL "${e}" in ${Qe(t)}; use https, a file path or a package path`);let r=/^\.{1,2}[\\/]/.test(e);if(t.kind==="url"){if(r||e.startsWith("/"))return Xe(new URL(e,t.href));throw new Error(`Cannot extend package "${e}" from the remote config ${t.href}; use a URL or a relative path`)}if(r||Br(e))return{kind:"file",path:Ze(zr(t.path),e)};try{return{kind:"file",path:Hr(t.path).resolve(e)}}catch(n){throw new Error(`Cannot resolve extends "${e}" from ${t.path}: ${n.message}`,{cause:n})}}i(Gr,"resolveReference");function Jr(e,t){if(e===void 0)return[];let r=Array.isArray(e)?e:[e];if(!r.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`Config "extends" must be a string or an array of strings: ${t}`);return r.map(n=>n.trim())}i(Jr,"readExtends");async function et(e,t){let r=Qe(e);if(t.includes(r))throw new Error(`Config extends cycle: ${[...t,r].join(" -> ")}`);let{text:n,source:o}=await Vr(e),a;try{a=JSON.parse(n)}catch(u){throw new Error(`Config ${r} is not valid JSON: ${u.message}`,{cause:u})}if(!fe(a))throw new Error(`Config file must contain a JSON object: ${r}`);let{extends:s,...c}=a,l={};for(let u of Jr(s,r))l=de(l,await et(Gr(u,o),[...t,r]));return de(l,c)}i(et,"loadSource");function qr(e,t=process.cwd()){return et({kind:"file",path:Ze(t,e)},[])}i(qr,"loadConfigFile");async function Z(e,t){let r=typeof e[t]=="string"?e[t].trim():"";if(r.length===0)return e;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o={...await qr(r,n),...e};return delete o[t],o}i(Z,"applyConfigOption");import{readFile as $o,stat as Ao,writeFile as Do}from"node:fs/promises";import{relative as Te,resolve as vr}from"node:path";import{extname as me}from"node:path";import{extname as Kr}from"node:path";var tt=[".css"];function Xr(e){let t=Kr(e).toLowerCase();return tt.includes(t)?{kind:"block",blockStart:"/*",blockLinePrefix:" * ",blockEnd:" */"}:null}i(Xr,"resolveCssCommentSyntax");var rt={id:"css",extensions:tt,enabledByDefault:!0,resolveCommentSyntax(e){return Xr(e)}};import{extname as Zr}from"node:path";var nt=[".go"];function Qr(e){let t=Zr(e).toLowerCase();return nt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(Qr,"resolveGoCommentSyntax");var ot={id:"go",extensions:nt,enabledByDefault:!0,resolveCommentSyntax(e){return Qr(e)}};import{extname as en}from"node:path";var it=[".html",".htm"];function tn(e){let t=en(e).toLowerCase();return it.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(tn,"resolveHtmlCommentSyntax");var at={id:"html",extensions:it,enabledByDefault:!0,resolveCommentSyntax(e){return tn(e)}};import{extname as rn}from"node:path";var st=[".jsonv",".jsonc",".json5"];function nn(e){let t=rn(e).toLowerCase();return st.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(nn,"resolveJsonCommentSyntax");var ct={id:"json",extensions:st,enabledByDefault:!0,resolveCommentSyntax(e){return nn(e)}};import{extname as on}from"node:path";var lt=[".md",".markdown"];function an(e){let t=on(e).toLowerCase();return lt.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(an,"resolveMarkdownCommentSyntax");function sn(e,t){let r=t.match(/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);return r?r[0]:""}i(sn,"resolveMarkdownPreservedPrefix");var ut={id:"markdown",extensions:lt,enabledByDefault:!1,requiresForce:!0,resolvePreservedPrefix(e,t){return sn(e,t)},resolveCommentSyntax(e){return an(e)}};import{extname as cn}from"node:path";var ft=[".js",".mjs",".cjs",".ts",".tsx",".jsx"];function ln(e){let t=cn(e).toLowerCase();return ft.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(ln,"resolveNodeCommentSyntax");function un(e,t){let r=t.match(/^#!.*\b(node|bun|deno|tsx|ts-node)\b.*(?:\r?\n|$)/);return r?r[0]:""}i(un,"resolveNodePreservedPrefix");var dt={id:"node",extensions:ft,enabledByDefault:!0,resolvePreservedPrefix(e,t){return un(e,t)},resolveCommentSyntax(e){return ln(e)}};import{extname as fn}from"node:path";var mt=[".php"];function dn(e){let t=fn(e).toLowerCase();return mt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(dn,"resolvePhpCommentSyntax");var pt={id:"php",extensions:mt,enabledByDefault:!0,resolveCommentSyntax(e){return dn(e)}};import{extname as mn}from"node:path";var ht=[".py"];function pn(e,t){let r=t.match(/^#!.*\bpython(?:\d+(?:\.\d+)*)?\b.*(?:\r?\n|$)/);return r?r[0]:""}i(pn,"resolvePythonPreservedPrefix");var gt={id:"python",extensions:ht,enabledByDefault:!0,resolvePreservedPrefix(e,t){return pn(e,t)},resolveCommentSyntax(e){let t=mn(e).toLowerCase();return ht.includes(t)?{kind:"line",linePrefix:"#"}:null}};import{extname as hn}from"node:path";var yt=[".rs"];function gn(e){let t=hn(e).toLowerCase();return yt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(gn,"resolveRustCommentSyntax");var xt={id:"rust",extensions:yt,enabledByDefault:!0,resolveCommentSyntax(e){return gn(e)}};import{extname as yn}from"node:path";var wt=[".yaml",".yml"];function xn(e){let t=yn(e).toLowerCase();return wt.includes(t)?{kind:"line",linePrefix:"#"}:null}i(xn,"resolveYamlCommentSyntax");var bt={id:"yaml",extensions:wt,enabledByDefault:!0,resolveCommentSyntax(e){return xn(e)}};var Q=[rt,ot,at,ct,ut,dt,pt,gt,xt,bt],wn=new Map(Q.map(e=>[e.id,e]));function bn(e,t){return!t||typeof t!="object"?e:e.kind==="line"?{...e,linePrefix:typeof t.linePrefix=="string"&&t.linePrefix.length>0?t.linePrefix:e.linePrefix,lineSeparator:typeof t.lineSeparator=="string"?t.lineSeparator:e.lineSeparator}:{...e,blockStart:typeof t.blockStart=="string"&&t.blockStart.length>0?t.blockStart:e.blockStart,blockLinePrefix:typeof t.blockLinePrefix=="string"&&t.blockLinePrefix.length>0?t.blockLinePrefix:e.blockLinePrefix,blockEnd:typeof t.blockEnd=="string"&&t.blockEnd.length>0?t.blockEnd:e.blockEnd}}i(bn,"applySyntaxOverride");function Et(e){if(e==null)return[];if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`forcedDetectors must be an array of detector ids, got ${JSON.stringify(e)}`);let t=Q.filter(r=>r.requiresForce===!0).map(r=>r.id);for(let r of e){if(!wn.has(r))throw new Error(`forcedDetectors: unknown detector "${r}" (force-only detectors: ${t.join(", ")})`);if(!t.includes(r))throw new Error(`forcedDetectors: "${r}" does not need forcing (force-only detectors: ${t.join(", ")})`)}return Array.from(new Set(e))}i(Et,"resolveForcedDetectors");function C(e={}){let t=new Set(Array.isArray(e.enabledDetectors)?e.enabledDetectors:[]),r=new Set(Array.isArray(e.disabledDetectors)?e.disabledDetectors:[]),n=new Set(Array.isArray(e.forcedDetectors)?e.forcedDetectors:[]);return Q.filter(o=>o.requiresForce===!0?n.has(o.id)&&!r.has(o.id):t.size>0?t.has(o.id):r.has(o.id)?!1:o.enabledByDefault)}i(C,"getEnabledDetectors");function kt(e={}){if(Array.isArray(e.includeExtensions)&&e.includeExtensions.length>0)return new Set(e.includeExtensions.map(r=>r.toLowerCase()));let t=C(e);return new Set(t.flatMap(r=>r.extensions))}i(kt,"getAllowedExtensions");function St(e,t={}){let r=me(e).toLowerCase();if(C(t).some(s=>s.extensions.includes(r)&&s.resolveCommentSyntax(e)!==null))return null;if(r.length===0)return"the file has no extension, so its comment syntax is unknown";let o=new Set(Array.isArray(t.forcedDetectors)?t.forcedDetectors:[]),a=Q.find(s=>s.requiresForce===!0&&s.extensions.includes(r)&&!o.has(s.id));return a?`${r} files get a header only when forced (--force-detector ${a.id} / forcedDetectors: ["${a.id}"])`:`no enabled detector handles ${r} files`}i(St,"getHeaderSkipReason");function $t(e,t={}){let r=me(e).toLowerCase(),n=Array.isArray(t.detectors)?t.detectors:C(t);for(let o of n){if(!o.extensions.includes(r))continue;let a=o.resolveCommentSyntax(e);if(a){let s=t.detectorSyntaxOverrides&&typeof t.detectorSyntaxOverrides=="object"?t.detectorSyntaxOverrides:{};return bn(a,s[o.id])}}return{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}}i($t,"getCommentSyntaxForFile");function At(e,t,r={}){let n=me(e).toLowerCase(),o=C(r);for(let a of o)if(a.extensions.includes(n))return typeof a.resolvePreservedPrefix=="function"?a.resolvePreservedPrefix(e,t):"";return""}i(At,"getPreservedPrefixForFile");var Dt=200,H=1,ee=2;function F(e,t,r){if(e==null)return r;if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error(`${t} must be a whole number of 0 or more, got ${JSON.stringify(e)}`);return e}i(F,"resolveLayoutCount");import{existsSync as Ln}from"node:fs";import{join as Ee,relative as Ot,resolve as ke,sep as we}from"node:path";import{realpath as Mn,stat as Pn}from"node:fs/promises";import{access as En,readdir as kn,readFile as Vi,stat as Sn}from"node:fs/promises";import{constants as $n}from"node:fs";import{dirname as qi,join as An,resolve as Ki}from"node:path";async function pe(e){try{return await En(e,$n.F_OK),!0}catch{return!1}}i(pe,"pathExists");async function he(e,t){let r=[],n=await kn(e,{withFileTypes:!0});for(let o of n){let a=An(e,o.name);if(o.isDirectory()&&t.recursive===!1||o.isDirectory()&&t.ignoreFolders.has(o.name)||o.isDirectory()&&await t.shouldSkipDirectory?.(a,o.name)===!0)continue;if(o.isDirectory()){let l=await he(a,t);r.push(...l);continue}if(!o.isFile())continue;let s=o.name.lastIndexOf(".");if(s===-1)continue;let c=o.name.slice(s).toLowerCase();t.allowedExtensions.has(c)&&r.push(a)}return r}i(he,"walkFiles");async function Nt(e){let t=await Sn(e);return{createdAt:t.birthtimeMs>0&&t.birthtime<t.mtime?t.birthtime:t.mtime,updatedAt:t.mtime}}i(Nt,"readFileDates");import{execFile as Dn}from"node:child_process";import{lstat as Nn,readFile as vn}from"node:fs/promises";import{dirname as vt,isAbsolute as Cn,join as jt,relative as Lt,resolve as ge,sep as Mt}from"node:path";import Fn from"ignore";function Ct(e,t){return new Promise(r=>{Dn("git",t,{cwd:e,encoding:"utf8",maxBuffer:Number.POSITIVE_INFINITY},(n,o)=>{if(!n){r({code:0,stdout:o});return}r({code:typeof n.code=="number"?n.code:-1,stdout:""})})})}i(Ct,"runGitCommand");function xe(e,t){return Lt(e,t).split(Mt).join("/")}i(xe,"toPosixRelative");async function Pt(e){try{return Fn().add(await vn(e,"utf8"))}catch{return null}}i(Pt,"readIgnoreFile");async function jn(e){return Nn(jt(e,".git")).then(()=>!0,()=>!1)}i(jn,"hasGitEntry");function Ft(e,t,r){for(let n=e.length-1;n>=0;n--){let{base:o,rules:a}=e[n],s=a.test(`${xe(o,t)}${r?"/":""}`);if(s.ignored||s.unignored)return s.ignored}return!1}i(Ft,"matchesRules");async function Rt(e,t){let r=await Pt(jt(e,".gitignore"));return{kind:"rules",nested:!0,excluded:!1,matchers:r?[...t,{base:e,rules:r}]:t}}i(Rt,"buildRulesContext");async function ye(e){let[t,r]=await Promise.all([Ct(e,["check-ignore","-q","."]),Ct(e,["ls-files","--cached","--others","--exclude-standard","-z"])]);if(t.code!==1||r.code!==0)return Rt(e,[]);let n=new Set,o=new Set;for(let a of r.stdout.split("\0")){let s=a.endsWith("/")?a.slice(0,-1):a;if(s.length!==0){n.add(s);for(let c=s.indexOf("/");c!==-1;c=s.indexOf("/",c+1))o.add(s.slice(0,c))}}return{kind:"git",root:e,entries:n,dirs:o}}i(ye,"resolveScopeContext");function It(e){let t=ge(e.root),r=e.gitignore;if(r===!1)return{isIgnored:i(async()=>!1,"isIgnored")};let n=new Map,o=i(async()=>{if(typeof r!="string"&&!Array.isArray(r))return ye(t);let c=typeof r=="string"?[r]:r.filter(u=>typeof u=="string"),l=[];for(let u of c){let f=await Pt(ge(t,u));f&&l.push({base:t,rules:f})}return{kind:"rules",nested:!1,excluded:!1,matchers:l}},"buildRootContext"),a=i(c=>{let l=n.get(c);return l||(l=c===t?o():s(c),n.set(c,l)),l},"contextFor"),s=i(async c=>{let l=await a(vt(c));return l.kind==="git"?l.entries.has(xe(l.root,c))?ye(c):l:!l.nested||l.excluded?l:Ft(l.matchers,c,!0)?{...l,excluded:!0}:await jn(c)?ye(c):Rt(c,l.matchers)},"deriveContext");return{async isIgnored(c,l){let u=ge(c),f=Lt(t,u);if(f.length===0||f===".."||f.startsWith(`..${Mt}`)||Cn(f))return!1;let p=await a(vt(u));if(p.kind==="git"){let g=xe(p.root,u);return!(p.entries.has(g)||l&&p.dirs.has(g))}return p.excluded||Ft(p.matchers,u,l)}}}i(It,"createIgnoreFilter");function Rn(e){return kt(e)}i(Rn,"resolveExtensions");var In=Object.freeze(["node_modules","bower_components","jspm_packages",".pnpm-store",".yarn"]),_t=new Set([".git",...In]),On=Object.freeze(["autoload.php","modules.txt"]);function Tt(e,t){return _t.has(t)?!0:t==="vendor"&&On.some(r=>Ln(Ee(e,r)))}i(Tt,"isNeverWalked");function be(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}i(be,"normalizeFolderPath");function Tn(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{path:t,recursive:!0};if(t&&typeof t=="object"&&typeof t.path=="string")return{path:t.path,recursive:t.recursive!==!1};throw new TypeError(`Invalid includeFolders entry: ${JSON.stringify(t)} (expected a path string or { path, recursive? })`)}):[]}i(Tn,"resolveIncludeFolders");function Ut(e,t){let r=t instanceof Error?t.message:String(t);console.warn(`fix-headers: skipped include folder "${e}" (${r})`)}i(Ut,"reportSkippedIncludeFolder");function Un(e,t){if(!Array.isArray(t)||t.length===0)return()=>!1;let r=ke(e),n=[],o=new Set;for(let a of t){if(typeof a!="string")continue;let s=be(a);if(s.length!==0){if(s.includes("/")){n.push(ke(r,s));continue}o.add(s)}}return(a,s)=>{if(o.has(s))return!0;for(let l of n)if(a===l||a.startsWith(`${l}/`))return!0;let c=be(Ot(r,a));return n.some(l=>{let u=be(Ot(r,l));return c===u||c.startsWith(`${u}/`)})}}i(Un,"buildExclusionMatcher");async function Se(e){let t=Rn(e),r=Tn(e.includeFolders),n=Array.isArray(e.excludeFolders)?e.excludeFolders:[],o=Un(e.projectRoot,n),a=It({root:e.projectRoot,gitignore:e.gitignore}),s=i(async(d,h)=>Tt(d,h)||o(d,h)||await a.isIgnored(d,!0),"shouldSkipDirectory"),c=r.length>0?r.map(d=>({includeFolder:d.path,rootPath:Ee(e.projectRoot,d.path),recursive:d.recursive})):[{includeFolder:".",rootPath:e.projectRoot,recursive:!0}],l=[];for(let d of c){let h=await Pn(d.rootPath).catch(k=>k);if(h instanceof Error){if(h.code==="ENOENT"){Ut(d.includeFolder,h);continue}throw h}if(!h.isDirectory()){Ut(d.includeFolder,`path is not a directory: ${d.rootPath}`);continue}let b=await Mn(d.rootPath).catch(()=>ke(d.rootPath));l.push({...d,realRoot:b})}let u=i((d,h)=>{if(d.realRoot===h.realRoot)return d.recursive||!h.recursive;let b=d.realRoot.endsWith(we)?d.realRoot:`${d.realRoot}${we}`;if(!d.recursive||!h.realRoot.startsWith(b))return!1;let k=d.rootPath;for(let D of h.realRoot.slice(b.length).split(we))if(k=Ee(k,D),Tt(k,D)||o(k,D))return!1;return!0},"covers"),f=[...l].sort((d,h)=>d.realRoot.length-h.realRoot.length||Number(h.recursive)-Number(d.recursive)),p=[];for(let d of f)p.some(h=>u(h,d))||p.push(d);let g=[];for(let d of l){if(!p.includes(d))continue;let h=await he(d.rootPath,{allowedExtensions:t,ignoreFolders:_t,shouldSkipDirectory:s,recursive:d.recursive});g.push(...h)}let x=[];for(let d of new Set(g))!o(d,d.split("/").at(-1)||"")&&!await a.isIgnored(d,!1)&&x.push(d);return x}i(Se,"discoverFiles");import{basename as co,dirname as lo,extname as uo,resolve as ve}from"node:path";import{dirname as Zt,isAbsolute as Kn,join as Qt,relative as Xn,resolve as er,sep as Zn}from"node:path";import{readFile as _n}from"node:fs/promises";import{join as Hn}from"node:path";async function zn(e){try{return await _n(e,"utf8")}catch{return null}}i(zn,"readManifest");async function $(e,t){let r=[];for(let n of t){let o=await zn(Hn(e,n));o!==null&&r.push({file:n,content:o})}return r.length>0?{dir:e,manifest:r[0].file,files:r}:null}i($,"detectManifests");function j(e,t){return e.files.find(r=>r.file===t)?.content??null}i(j,"manifestContent");function w(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(w,"cleanName");function $e(e){if(typeof e!="string")return;let t=e.search(/[<(]/);return w(t===-1?e:e.slice(0,t))}i($e,"personName");function te(e){try{return JSON.parse(e)}catch{return}}i(te,"parseJsonManifest");function*Ae(e,t){let r="";for(let n of e.split(/\r?\n/)){let o=n.trim();if(o.startsWith("[")){let a=o.match(/^\[([^[\]]+)\]/);r=a?a[1].split(".").map(s=>s.trim()).join("."):"";continue}r===t&&(yield o)}}i(Ae,"sectionLines");function z(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*(?:"([^"\\\\]*)"|'([^']*)')`);for(let o of Ae(e,t)){let a=o.match(n);if(a)return w(a[1]??a[2])}}i(z,"readTomlString");function De(e,t,r){let n=new RegExp(`^${r}\\s*[=:](.*)$`);for(let o of Ae(e,t)){let a=o.match(n);if(a)return w(a[1])}}i(De,"readIniValue");function Bn(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*\\[`),o=null;for(let a of Ae(e,t)){if(o!==null){o.push(a);continue}let s=a.match(n);s&&(o=[a.slice(s[0].length)])}return o===null?null:o.join(`
|
|
3
|
-
`)}i(
|
|
4
|
-
`,r);r=n===-1?e.length:n+1}else if(/\s/.test(e[r]))r+=1;else break;return r}i(
|
|
5
|
-
`)){let s=a.split(":");if(s[0]==="uid"&&s[1]!=="r"&&s[1]!=="e"&&s[9])return
|
|
6
|
-
`)[0],[o,a]=n.split("|");if(!o||!a)return null;let s=Number.parseInt(a,10);return Number.isNaN(s)?null:{date:
|
|
2
|
+
var Yr=Object.defineProperty;var i=(e,t)=>Yr(e,"name",{value:t,configurable:!0});import{realpathSync as Pr}from"node:fs";import{fileURLToPath as Wo,pathToFileURL as Yo}from"node:url";import{readFile as Gr}from"node:fs/promises";import{createRequire as Vr}from"node:module";import{dirname as Jr,isAbsolute as qr,resolve as rt}from"node:path";var Kr=3e4,Xr=new Set(["localhost","127.0.0.1","[::1]"]);function se(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(se,"isPlainObject");function ce(e,t){let r={...e};for(let[n,o]of Object.entries(t))n!=="__proto__"&&(r[n]=se(r[n])&&se(o)?ce(r[n],o):o);return r}i(ce,"mergeConfig");function nt(e){return e.kind==="file"?e.path:e.href}i(nt,"describeSource");async function Zr(e){if(e.kind==="file")return{text:await Gr(e.path,"utf8"),source:e};let t;try{t=await fetch(e.href,{cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(Kr)})}catch(r){let n=r.cause instanceof Error?r.cause.message:r.message;throw new Error(`Failed to fetch config ${e.href}: ${n}`,{cause:r})}if(!t.ok)throw new Error(`Failed to fetch config ${e.href}: HTTP ${t.status} ${t.statusText}`);return{text:await t.text(),source:{kind:"url",href:t.url}}}i(Zr,"readSource");function tt(e){if(e.protocol==="http:"&&!Xr.has(e.hostname))throw new Error(`Refusing to fetch config over plain http: ${e.href} (use https)`);return{kind:"url",href:e.href}}i(tt,"toUrlSource");function Qr(e,t){if(/^https?:\/\//i.test(e))return tt(new URL(e));if(/^[a-z][a-z\d+.-]+:\/\//i.test(e))throw new Error(`Unsupported extends URL "${e}" in ${nt(t)}; use https, a file path or a package path`);let r=/^\.{1,2}[\\/]/.test(e);if(t.kind==="url"){if(r||e.startsWith("/"))return tt(new URL(e,t.href));throw new Error(`Cannot extend package "${e}" from the remote config ${t.href}; use a URL or a relative path`)}if(r||qr(e))return{kind:"file",path:rt(Jr(t.path),e)};try{return{kind:"file",path:Vr(t.path).resolve(e)}}catch(n){throw new Error(`Cannot resolve extends "${e}" from ${t.path}: ${n.message}`,{cause:n})}}i(Qr,"resolveReference");function en(e,t){if(e===void 0)return[];let r=Array.isArray(e)?e:[e];if(!r.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`Config "extends" must be a string or an array of strings: ${t}`);return r.map(n=>n.trim())}i(en,"readExtends");async function ot(e,t){let r=nt(e);if(t.includes(r))throw new Error(`Config extends cycle: ${[...t,r].join(" -> ")}`);let{text:n,source:o}=await Zr(e),a;try{a=JSON.parse(n)}catch(u){throw new Error(`Config ${r} is not valid JSON: ${u.message}`,{cause:u})}if(!se(a))throw new Error(`Config file must contain a JSON object: ${r}`);let{extends:s,...c}=a,l={};for(let u of en(s,r))l=ce(l,await ot(Qr(u,o),[...t,r]));return ce(l,c)}i(ot,"loadSource");function tn(e,t=process.cwd()){return ot({kind:"file",path:rt(t,e)},[])}i(tn,"loadConfigFile");async function q(e,t){let r=typeof e[t]=="string"?e[t].trim():"";if(r.length===0)return e;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o={...await tn(r,n),...e};return delete o[t],o}i(q,"applyConfigOption");import{readFile as Mo,stat as Ro,writeFile as Po}from"node:fs/promises";import{relative as Pe,resolve as Lr}from"node:path";import{extname as le}from"node:path";import{extname as rn}from"node:path";var it=[".css"];function nn(e){let t=rn(e).toLowerCase();return it.includes(t)?{kind:"block",blockStart:"/*",blockLinePrefix:" * ",blockEnd:" */"}:null}i(nn,"resolveCssCommentSyntax");var at={id:"css",extensions:it,enabledByDefault:!0,resolveCommentSyntax(e){return nn(e)}};import{extname as on}from"node:path";var st=[".go"];function an(e){let t=on(e).toLowerCase();return st.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(an,"resolveGoCommentSyntax");var ct={id:"go",extensions:st,enabledByDefault:!0,resolveCommentSyntax(e){return an(e)}};import{extname as sn}from"node:path";var lt=[".html",".htm"];function cn(e){let t=sn(e).toLowerCase();return lt.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(cn,"resolveHtmlCommentSyntax");var ut={id:"html",extensions:lt,enabledByDefault:!0,resolveCommentSyntax(e){return cn(e)}};import{extname as ln}from"node:path";var ft=[".jsonv",".jsonc",".json5"];function un(e){let t=ln(e).toLowerCase();return ft.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(un,"resolveJsonCommentSyntax");var dt={id:"json",extensions:ft,enabledByDefault:!0,resolveCommentSyntax(e){return un(e)}};import{extname as fn}from"node:path";var mt=[".md",".markdown"];function dn(e){let t=fn(e).toLowerCase();return mt.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(dn,"resolveMarkdownCommentSyntax");function mn(e,t){let r=t.match(/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);return r?r[0]:""}i(mn,"resolveMarkdownPreservedPrefix");var pt={id:"markdown",extensions:mt,enabledByDefault:!1,requiresForce:!0,resolvePreservedPrefix(e,t){return mn(e,t)},resolveCommentSyntax(e){return dn(e)}};import{extname as pn}from"node:path";var ht=[".js",".mjs",".cjs",".ts",".tsx",".jsx"];function hn(e){let t=pn(e).toLowerCase();return ht.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(hn,"resolveNodeCommentSyntax");function gn(e,t){let r=t.match(/^#!.*\b(node|bun|deno|tsx|ts-node)\b.*(?:\r?\n|$)/);return r?r[0]:""}i(gn,"resolveNodePreservedPrefix");var gt={id:"node",extensions:ht,enabledByDefault:!0,resolvePreservedPrefix(e,t){return gn(e,t)},resolveCommentSyntax(e){return hn(e)}};import{extname as yn}from"node:path";var yt=[".php"];function xn(e){let t=yn(e).toLowerCase();return yt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(xn,"resolvePhpCommentSyntax");var xt={id:"php",extensions:yt,enabledByDefault:!0,resolveCommentSyntax(e){return xn(e)}};import{extname as wn}from"node:path";var wt=[".py"];function bn(e,t){let r=t.match(/^#!.*\bpython(?:\d+(?:\.\d+)*)?\b.*(?:\r?\n|$)/);return r?r[0]:""}i(bn,"resolvePythonPreservedPrefix");var bt={id:"python",extensions:wt,enabledByDefault:!0,resolvePreservedPrefix(e,t){return bn(e,t)},resolveCommentSyntax(e){let t=wn(e).toLowerCase();return wt.includes(t)?{kind:"line",linePrefix:"#"}:null}};import{extname as kn}from"node:path";var kt=[".rs"];function En(e){let t=kn(e).toLowerCase();return kt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(En,"resolveRustCommentSyntax");var Et={id:"rust",extensions:kt,enabledByDefault:!0,resolveCommentSyntax(e){return En(e)}};import{extname as Sn}from"node:path";var St=[".yaml",".yml"];function $n(e){let t=Sn(e).toLowerCase();return St.includes(t)?{kind:"line",linePrefix:"#"}:null}i($n,"resolveYamlCommentSyntax");var $t={id:"yaml",extensions:St,enabledByDefault:!0,resolveCommentSyntax(e){return $n(e)}};var K=[at,ct,ut,dt,pt,gt,xt,bt,Et,$t],An=new Map(K.map(e=>[e.id,e]));function Dn(e,t){return!t||typeof t!="object"?e:e.kind==="line"?{...e,linePrefix:typeof t.linePrefix=="string"&&t.linePrefix.length>0?t.linePrefix:e.linePrefix,lineSeparator:typeof t.lineSeparator=="string"?t.lineSeparator:e.lineSeparator}:{...e,blockStart:typeof t.blockStart=="string"&&t.blockStart.length>0?t.blockStart:e.blockStart,blockLinePrefix:typeof t.blockLinePrefix=="string"&&t.blockLinePrefix.length>0?t.blockLinePrefix:e.blockLinePrefix,blockEnd:typeof t.blockEnd=="string"&&t.blockEnd.length>0?t.blockEnd:e.blockEnd}}i(Dn,"applySyntaxOverride");function At(e){if(e==null)return[];if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`forcedDetectors must be an array of detector ids, got ${JSON.stringify(e)}`);let t=K.filter(r=>r.requiresForce===!0).map(r=>r.id);for(let r of e){if(!An.has(r))throw new Error(`forcedDetectors: unknown detector "${r}" (force-only detectors: ${t.join(", ")})`);if(!t.includes(r))throw new Error(`forcedDetectors: "${r}" does not need forcing (force-only detectors: ${t.join(", ")})`)}return Array.from(new Set(e))}i(At,"resolveForcedDetectors");function F(e={}){let t=new Set(Array.isArray(e.enabledDetectors)?e.enabledDetectors:[]),r=new Set(Array.isArray(e.disabledDetectors)?e.disabledDetectors:[]),n=new Set(Array.isArray(e.forcedDetectors)?e.forcedDetectors:[]);return K.filter(o=>o.requiresForce===!0?n.has(o.id)&&!r.has(o.id):t.size>0?t.has(o.id):r.has(o.id)?!1:o.enabledByDefault)}i(F,"getEnabledDetectors");function Dt(e={}){if(Array.isArray(e.includeExtensions)&&e.includeExtensions.length>0)return new Set(e.includeExtensions.map(r=>r.toLowerCase()));let t=F(e);return new Set(t.flatMap(r=>r.extensions))}i(Dt,"getAllowedExtensions");function vt(e,t={}){let r=le(e).toLowerCase();if(F(t).some(s=>s.extensions.includes(r)&&s.resolveCommentSyntax(e)!==null))return null;if(r.length===0)return"the file has no extension, so its comment syntax is unknown";let o=new Set(Array.isArray(t.forcedDetectors)?t.forcedDetectors:[]),a=K.find(s=>s.requiresForce===!0&&s.extensions.includes(r)&&!o.has(s.id));return a?`${r} files get a header only when forced (--force-detector ${a.id} / forcedDetectors: ["${a.id}"])`:`no enabled detector handles ${r} files`}i(vt,"getHeaderSkipReason");function Ct(e,t={}){let r=le(e).toLowerCase(),n=Array.isArray(t.detectors)?t.detectors:F(t);for(let o of n){if(!o.extensions.includes(r))continue;let a=o.resolveCommentSyntax(e);if(a){let s=t.detectorSyntaxOverrides&&typeof t.detectorSyntaxOverrides=="object"?t.detectorSyntaxOverrides:{};return Dn(a,s[o.id])}}return{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}}i(Ct,"getCommentSyntaxForFile");function Nt(e,t,r={}){let n=le(e).toLowerCase(),o=F(r);for(let a of o)if(a.extensions.includes(n))return typeof a.resolvePreservedPrefix=="function"?a.resolvePreservedPrefix(e,t):"";return""}i(Nt,"getPreservedPrefixForFile");var Ft=200,B=1,X=2;function j(e,t,r){if(e==null)return r;if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error(`${t} must be a whole number of 0 or more, got ${JSON.stringify(e)}`);return e}i(j,"resolveLayoutCount");import{existsSync as Tn}from"node:fs";import{join as ye,relative as Ut,resolve as xe,sep as he}from"node:path";import{realpath as Hn,stat as _n}from"node:fs/promises";import{access as vn,readdir as Cn,readFile as ra,stat as Nn}from"node:fs/promises";import{constants as Fn}from"node:fs";import{dirname as ia,join as jn,resolve as aa}from"node:path";async function ue(e){try{return await vn(e,Fn.F_OK),!0}catch{return!1}}i(ue,"pathExists");async function fe(e,t){let r=[],n=await Cn(e,{withFileTypes:!0});for(let o of n){let a=jn(e,o.name);if(o.isDirectory()&&t.recursive===!1||o.isDirectory()&&t.ignoreFolders.has(o.name)||o.isDirectory()&&await t.shouldSkipDirectory?.(a,o.name)===!0)continue;if(o.isDirectory()){let l=await fe(a,t);r.push(...l);continue}if(!o.isFile())continue;let s=o.name.lastIndexOf(".");if(s===-1)continue;let c=o.name.slice(s).toLowerCase();t.allowedExtensions.has(c)&&r.push(a)}return r}i(fe,"walkFiles");async function jt(e){let t=await Nn(e);return{createdAt:t.birthtimeMs>0&&t.birthtime<t.mtime?t.birthtime:t.mtime,updatedAt:t.mtime}}i(jt,"readFileDates");import{execFile as Ln}from"node:child_process";import{lstat as Mn,readFile as Rn}from"node:fs/promises";import{dirname as Lt,isAbsolute as Pn,join as Pt,relative as It,resolve as de,sep as Ot}from"node:path";import In from"ignore";function Mt(e,t){return new Promise(r=>{Ln("git",t,{cwd:e,encoding:"utf8",maxBuffer:Number.POSITIVE_INFINITY},(n,o)=>{if(!n){r({code:0,stdout:o});return}r({code:typeof n.code=="number"?n.code:-1,stdout:""})})})}i(Mt,"runGitCommand");function pe(e,t){return It(e,t).split(Ot).join("/")}i(pe,"toPosixRelative");async function Tt(e){try{return In().add(await Rn(e,"utf8"))}catch{return null}}i(Tt,"readIgnoreFile");async function On(e){return Mn(Pt(e,".git")).then(()=>!0,()=>!1)}i(On,"hasGitEntry");function Rt(e,t,r){for(let n=e.length-1;n>=0;n--){let{base:o,rules:a}=e[n],s=a.test(`${pe(o,t)}${r?"/":""}`);if(s.ignored||s.unignored)return s.ignored}return!1}i(Rt,"matchesRules");async function Ht(e,t){let r=await Tt(Pt(e,".gitignore"));return{kind:"rules",nested:!0,excluded:!1,matchers:r?[...t,{base:e,rules:r}]:t}}i(Ht,"buildRulesContext");async function me(e){let[t,r]=await Promise.all([Mt(e,["check-ignore","-q","."]),Mt(e,["ls-files","--cached","--others","--exclude-standard","-z"])]);if(t.code!==1||r.code!==0)return Ht(e,[]);let n=new Set,o=new Set;for(let a of r.stdout.split("\0")){let s=a.endsWith("/")?a.slice(0,-1):a;if(s.length!==0){n.add(s);for(let c=s.indexOf("/");c!==-1;c=s.indexOf("/",c+1))o.add(s.slice(0,c))}}return{kind:"git",root:e,entries:n,dirs:o}}i(me,"resolveScopeContext");function _t(e){let t=de(e.root),r=e.gitignore;if(r===!1)return{isIgnored:i(async()=>!1,"isIgnored")};let n=new Map,o=i(async()=>{if(typeof r!="string"&&!Array.isArray(r))return me(t);let c=typeof r=="string"?[r]:r.filter(u=>typeof u=="string"),l=[];for(let u of c){let f=await Tt(de(t,u));f&&l.push({base:t,rules:f})}return{kind:"rules",nested:!1,excluded:!1,matchers:l}},"buildRootContext"),a=i(c=>{let l=n.get(c);return l||(l=c===t?o():s(c),n.set(c,l)),l},"contextFor"),s=i(async c=>{let l=await a(Lt(c));return l.kind==="git"?l.entries.has(pe(l.root,c))?me(c):l:!l.nested||l.excluded?l:Rt(l.matchers,c,!0)?{...l,excluded:!0}:await On(c)?me(c):Ht(c,l.matchers)},"deriveContext");return{async isIgnored(c,l){let u=de(c),f=It(t,u);if(f.length===0||f===".."||f.startsWith(`..${Ot}`)||Pn(f))return!1;let m=await a(Lt(u));if(m.kind==="git"){let g=pe(m.root,u);return!(m.entries.has(g)||l&&m.dirs.has(g))}return m.excluded||Rt(m.matchers,u,l)}}}i(_t,"createIgnoreFilter");function Un(e){return Dt(e)}i(Un,"resolveExtensions");var zn=Object.freeze(["node_modules","bower_components","jspm_packages",".pnpm-store",".yarn"]),Wt=new Set([".git",...zn]),Bn=Object.freeze(["autoload.php","modules.txt"]);function zt(e,t){return Wt.has(t)?!0:t==="vendor"&&Bn.some(r=>Tn(ye(e,r)))}i(zt,"isNeverWalked");function ge(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}i(ge,"normalizeFolderPath");function Wn(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{path:t,recursive:!0};if(t&&typeof t=="object"&&typeof t.path=="string")return{path:t.path,recursive:t.recursive!==!1};throw new TypeError(`Invalid includeFolders entry: ${JSON.stringify(t)} (expected a path string or { path, recursive? })`)}):[]}i(Wn,"resolveIncludeFolders");function Bt(e,t){let r=t instanceof Error?t.message:String(t);console.warn(`fix-headers: skipped include folder "${e}" (${r})`)}i(Bt,"reportSkippedIncludeFolder");function Yn(e,t){if(!Array.isArray(t)||t.length===0)return()=>!1;let r=xe(e),n=[],o=new Set;for(let a of t){if(typeof a!="string")continue;let s=ge(a);if(s.length!==0){if(s.includes("/")){n.push(xe(r,s));continue}o.add(s)}}return(a,s)=>{if(o.has(s))return!0;for(let l of n)if(a===l||a.startsWith(`${l}/`))return!0;let c=ge(Ut(r,a));return n.some(l=>{let u=ge(Ut(r,l));return c===u||c.startsWith(`${u}/`)})}}i(Yn,"buildExclusionMatcher");async function we(e){let t=Un(e),r=Wn(e.includeFolders),n=Array.isArray(e.excludeFolders)?e.excludeFolders:[],o=Yn(e.projectRoot,n),a=_t({root:e.projectRoot,gitignore:e.gitignore}),s=i(async(d,h)=>zt(d,h)||o(d,h)||await a.isIgnored(d,!0),"shouldSkipDirectory"),c=r.length>0?r.map(d=>({includeFolder:d.path,rootPath:ye(e.projectRoot,d.path),recursive:d.recursive})):[{includeFolder:".",rootPath:e.projectRoot,recursive:!0}],l=[];for(let d of c){let h=await _n(d.rootPath).catch($=>$);if(h instanceof Error){if(h.code==="ENOENT"){Bt(d.includeFolder,h);continue}throw h}if(!h.isDirectory()){Bt(d.includeFolder,`path is not a directory: ${d.rootPath}`);continue}let b=await Hn(d.rootPath).catch(()=>xe(d.rootPath));l.push({...d,realRoot:b})}let u=i((d,h)=>{if(d.realRoot===h.realRoot)return d.recursive||!h.recursive;let b=d.realRoot.endsWith(he)?d.realRoot:`${d.realRoot}${he}`;if(!d.recursive||!h.realRoot.startsWith(b))return!1;let $=d.rootPath;for(let v of h.realRoot.slice(b.length).split(he))if($=ye($,v),zt($,v)||o($,v))return!1;return!0},"covers"),f=[...l].sort((d,h)=>d.realRoot.length-h.realRoot.length||Number(h.recursive)-Number(d.recursive)),m=[];for(let d of f)m.some(h=>u(h,d))||m.push(d);let g=[];for(let d of l){if(!m.includes(d))continue;let h=await fe(d.rootPath,{allowedExtensions:t,ignoreFolders:Wt,shouldSkipDirectory:s,recursive:d.recursive});g.push(...h)}let x=[];for(let d of new Set(g))!o(d,d.split("/").at(-1)||"")&&!await a.isIgnored(d,!1)&&x.push(d);return x}i(we,"discoverFiles");import{basename as xo,dirname as wo,extname as bo,resolve as Ae}from"node:path";import{dirname as rr,isAbsolute as ro,join as nr,relative as no,resolve as or,sep as oo}from"node:path";import{readFile as Gn}from"node:fs/promises";import{join as Vn}from"node:path";async function Jn(e){try{return await Gn(e,"utf8")}catch{return null}}i(Jn,"readManifest");async function A(e,t){let r=[];for(let n of t){let o=await Jn(Vn(e,n));o!==null&&r.push({file:n,content:o})}return r.length>0?{dir:e,manifest:r[0].file,files:r}:null}i(A,"detectManifests");function L(e,t){return e.files.find(r=>r.file===t)?.content??null}i(L,"manifestContent");function w(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(w,"cleanName");function be(e){if(typeof e!="string")return;let t=e.search(/[<(]/);return w(t===-1?e:e.slice(0,t))}i(be,"personName");function Z(e){try{return JSON.parse(e)}catch{return}}i(Z,"parseJsonManifest");function*ke(e,t){let r="";for(let n of e.split(/\r?\n/)){let o=n.trim();if(o.startsWith("[")){let a=o.match(/^\[([^[\]]+)\]/);r=a?a[1].split(".").map(s=>s.trim()).join("."):"";continue}r===t&&(yield o)}}i(ke,"sectionLines");function W(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*(?:"([^"\\\\]*)"|'([^']*)')`);for(let o of ke(e,t)){let a=o.match(n);if(a)return w(a[1]??a[2])}}i(W,"readTomlString");function Ee(e,t,r){let n=new RegExp(`^${r}\\s*[=:](.*)$`);for(let o of ke(e,t)){let a=o.match(n);if(a)return w(a[1])}}i(Ee,"readIniValue");function qn(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*\\[`),o=null;for(let a of ke(e,t)){if(o!==null){o.push(a);continue}let s=a.match(n);s&&(o=[a.slice(s[0].length)])}return o===null?null:o.join(`
|
|
3
|
+
`)}i(qn,"tomlArrayText");function Kn(e,t){let r=t;for(;r<e.length;)if(e[r]==="#"){let n=e.indexOf(`
|
|
4
|
+
`,r);r=n===-1?e.length:n+1}else if(/\s/.test(e[r]))r+=1;else break;return r}i(Kn,"skipTomlSpace");function Y(e,t){let r=qn(e,t,"authors");if(r===null)return;let n=r.slice(Kn(r,0)),o=n.match(/^(?:"([^"\\\n]*)"|'([^'\n]*)')/);if(o)return be(o[1]??o[2]);let s=n.match(/^\{([^}\n]*)\}/)?.[1].match(/(?:^|,)\s*name\s*=\s*(?:"([^"\\\n]*)"|'([^'\n]*)')/);return s?w(s[1]??s[2]):void 0}i(Y,"readTomlAuthor");var Yt=["go.mod"];function Xn(e){let t=e.match(/^\s*module\s+(.+)$/m);if(t)return w(t[1].replace(/\/\/.*$/,"").trim().replace(/^["`](.*)["`]$/,"$1"))}i(Xn,"readModulePath");var Gt={id:"go",languages:["go"],manifests:Yt,detect(e){return A(e,Yt)},read(e){return{name:Xn(e.files[0].content)}}};var Vt=["package.json"];function Zn(e){let t=w(e?.name),r=w(e?.publisher),n=typeof e?.engines?.vscode=="string";return t&&r&&n?`${r}.${t}`:t}i(Zn,"readPublishedName");function Qn(e){if(e!==null&&typeof e=="object"){let t=e;return w(t.company)??w(t.name)}return be(e)}i(Qn,"readAuthorCompany");var Jt={id:"node",languages:["node"],manifests:Vt,detect(e){return A(e,Vt)},read(e){let t=Z(e.files[0].content);return{name:Zn(t),company:Qn(t?.author)}}};var qt=["composer.json"],Kt={id:"php",languages:["php"],manifests:qt,detect(e){return A(e,qt)},read(e){let t=Z(e.files[0].content),r=t?.authors;return{name:w(t?.name),company:Array.isArray(r)?w(r[0]?.name):void 0}}};var Xt=["pyproject.toml","setup.cfg","setup.py"];function Zt(e,t){let r=e.indexOf("setup(");if(r===-1)return;let n=e.slice(r).match(new RegExp(`\\b${t}\\s*=\\s*(["'])([^"'\\n]+)\\1`));return n&&n[2].trim()||void 0}i(Zt,"readSetupPyArgument");function eo(e){let t=L(e,"pyproject.toml"),r=L(e,"setup.cfg"),n=L(e,"setup.py");return(t===null?void 0:W(t,"project","name")??W(t,"tool.poetry","name"))??(r===null?void 0:Ee(r,"metadata","name"))??(n===null?void 0:Zt(n,"name"))}i(eo,"readPythonName");function to(e){let t=L(e,"pyproject.toml"),r=L(e,"setup.cfg"),n=L(e,"setup.py");return(t===null?void 0:Y(t,"project")??Y(t,"tool.poetry"))??(r===null?void 0:Ee(r,"metadata","author"))??(n===null?void 0:Zt(n,"author"))}i(to,"readPythonCompany");var Qt={id:"python",languages:["python"],manifests:Xt,detect(e){return A(e,Xt)},read(e){return{name:eo(e),company:to(e)}}};var er=["Cargo.toml"],tr={id:"rust",languages:["rust"],manifests:er,detect(e){return A(e,er)},read(e){let t=e.files[0].content;return{name:W(t,"package","name"),company:Y(t,"package")}}};var io=[Jt,Qt,Kt,tr,Gt],ir=["name","company"];async function Se(e,t,r){let o=(await Promise.all(t.map(async s=>({driver:s,detection:await s.detect(e)})))).filter(s=>s.detection!==null),a=o.filter(s=>typeof r=="string"&&s.driver.languages.includes(r));return[...a,...o.filter(s=>!a.includes(s))]}i(Se,"claimFolder");function ao(e,t){let r=no(t,e);return r!==""&&r!==".."&&!r.startsWith(`..${oo}`)&&!ro(r)}i(ao,"isStrictlyInside");async function ar(e,t={}){let r=Array.isArray(t.drivers)?t.drivers:io,n=typeof t.scanRoot=="string"?or(t.scanRoot):null,o=or(e),a=await Se(o,r,t.language);for(;a.length===0;){if(await ue(nr(o,".git")))return{root:o,marker:".git",drivers:[],fields:{},sources:{}};let f=rr(o);if(f===o)return null;o=f,a=await Se(o,r,t.language)}let s={},c={},l=o,u=a;for(;;){for(let{driver:m,detection:g}of u){let x=m.read(g);for(let d of ir)s[d]===void 0&&x[d]!==void 0&&(s[d]=x[d],c[d]={driver:m.id,manifest:g.manifest,dir:l})}if(ir.every(m=>s[m]!==void 0)||n===null||!ao(l,n)||await ue(nr(l,".git")))break;l=rr(l),u=await Se(l,r,t.language)}return{root:o,marker:a[0].detection.manifest,drivers:a.map(f=>f.driver.id),fields:s,sources:c}}i(ar,"resolveManifestProject");import{execFile as so}from"node:child_process";import{basename as co,dirname as lo}from"node:path";import{promisify as uo}from"node:util";var $e=uo(so);async function S(e,t){try{let{stdout:r}=await $e("git",t,{cwd:e}),n=r.trim();return n.length>0?n:null}catch{return null}}i(S,"runGit");function sr(e,t){let r=0;for(let n=t-1;n>=0&&e[n]==="\\";n--)r++;return r%2===1}i(sr,"isEscaped");function fo(e){let t=e.trim();if(!t.endsWith(")")||sr(t,t.length-1))return t;let r=0;for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(o!=="("&&o!==")"||sr(t,n))&&(r+=o===")"?1:-1,r===0))return t.slice(0,n).trim()}return t}i(fo,"stripUidComment");function mo(e){let t=e.trim();if(t.length===0)return{authorName:null,authorEmail:null};let r=t.match(/<([^>\n]+)>\s*$/),n=r?.[1]?.trim()||null,o=(r?t.slice(0,r.index):t).trim();return{authorName:fo(o)||o||null,authorEmail:n}}i(mo,"parseSignerUid");async function po(e,t){try{let{stdout:r}=await $e(e,t),n=r.trim();return n.length>0?n:null}catch{return null}}i(po,"runProgram");function ho(e){return e.replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(Number.parseInt(r,16)))}i(ho,"decodeColonField");async function go(e){let t=await S(e,["config","--get","gpg.format"]);if(t!==null&&t!=="openpgp")return null;let r=await S(e,["config","--get","user.signingkey"]);if(!r)return null;let n=await S(e,["config","--get","gpg.openpgp.program"])||await S(e,["config","--get","gpg.program"])||"gpg",o=await po(n,["--batch","--with-colons","--list-keys",r]);if(!o)return null;for(let a of o.split(`
|
|
5
|
+
`)){let s=a.split(":");if(s[0]==="uid"&&s[1]!=="r"&&s[1]!=="e"&&s[9])return ho(s[9])}return null}i(go,"readSigningKeyUid");async function cr(e,t={}){let r=await S(e,["config","--get","user.name"]),n=await S(e,["config","--get","user.email"]);if(t.useGpgSignerAuthor===!0){let o=await go(e)||await S(e,["log","-1","--format=%GS"]),a=mo(o||"");r=a.authorName||r,n=n||a.authorEmail}if(!r||!n){let o=await S(e,["log","-1","--format=%an|%ae"]);if(o){let[a,s]=o.split("|");r=r||a||null,n=n||s||null}}return{authorName:r,authorEmail:n}}i(cr,"detectGitAuthor");function lr(e){return e.replace(/z$/i,"+00:00")}i(lr,"canonicalGitDate");async function ur(e,t){let r=await S(e,["log","--follow","--format=%aI|%at","--reverse","--",t]);if(!r)return null;let n=r.split(`
|
|
6
|
+
`)[0],[o,a]=n.split("|");if(!o||!a)return null;let s=Number.parseInt(a,10);return Number.isNaN(s)?null:{date:lr(o),timestamp:s}}i(ur,"getGitCreationDate");async function fr(e,t){let r=await S(e,["log","-1","--format=%aI|%at","--",t]);if(!r)return null;let[n,o]=r.split("|");if(!n||!o)return null;let a=Number.parseInt(o,10);return Number.isNaN(a)?null:{date:lr(n),timestamp:a}}i(fr,"getGitLastModifiedDate");var yo=256*1024*1024;async function dr(e){let t=lo(e);if(await S(t,["rev-parse","--is-inside-work-tree"])!=="true")return{state:"no-git",content:null};try{let{stdout:r}=await $e("git",["show",`HEAD:./${co(e)}`],{cwd:t,encoding:"utf8",maxBuffer:yo});return{state:"tracked",content:r}}catch{return{state:"untracked",content:null}}}i(dr,"readGitHeadFile");function ko(e){return xo(e)||"project"}i(ko,"folderName");function Eo(e,t){if(typeof t!="string")return e;let r=t.trim();return r.length===0||/<[^>]+>/.test(e)?e:`${e} <${r}>`}i(Eo,"formatAuthorNameWithCompany");async function So(e,t={}){let r=Array.isArray(t.detectors)?t.detectors:F(t),n=typeof t.preferredExtension=="string"?t.preferredExtension.trim().toLowerCase():"",o=n.length>0?r.find(u=>u.extensions.includes(n)):void 0,a=await ar(e,{drivers:t.drivers,language:o?.id,scanRoot:t.scanRoot}),s=a?a.root:Ae(e),c=a?.sources.name,l=a?.sources.company;return{language:o?.id??a?.drivers[0]??"unknown",rootDir:s,marker:a?a.marker:null,projectName:a?.fields.name??ko(s),projectNameSource:c?{from:"manifest",...c}:{from:"folder",dir:s},companyName:a?.fields.company??null,companyNameSource:l?{from:"manifest",...l}:{from:"none"},drivers:a?a.drivers:[]}}i(So,"detectProjectFromMarkers");async function De(e={}){let t=e.targetFilePath||e.cwd||process.cwd(),r=Ae(t),n=F(e),o=e.targetFilePath?wo(r):r,a=e.targetFilePath?bo(r).toLowerCase():"",s=Ae(e.projectRoot||e.cwd||process.cwd()),c=await So(o,{detectors:n,preferredExtension:a,scanRoot:s}),l=await cr(c.rootDir,{useGpgSignerAuthor:e.useGpgSignerAuthor===!0}),u=e.authorName||l.authorName||"Unknown Author",f=typeof e.companyName=="string"?e.companyName.trim():"";return{projectName:e.projectName||c.projectName,projectNameSource:e.projectName?{from:"option"}:c.projectNameSource,language:e.language||c.language,projectRoot:e.projectRoot||c.rootDir,marker:e.marker===void 0?c.marker:e.marker,authorName:Eo(u,e.company),authorEmail:e.authorEmail||l.authorEmail||"unknown@example.com",companyName:f||c.companyName,companyNameSource:f?{from:"option"}:c.companyNameSource,copyrightStartYear:Number.isInteger(e.copyrightStartYear)?Number(e.copyrightStartYear):null}}i(De,"resolveProjectMetadata");function $o(e){return ve({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),offsetMinutes:-e.getTimezoneOffset()})}i($o,"formatDateWithTimezone");function ve(e){return`${gr(e," ")} ${yr(e.offsetMinutes)}`}i(ve,"formatSpaceDate");function pr(e){if(typeof e!="string")throw new Error(`timezone must be an IANA time zone name string, such as "America/Los_Angeles" or "UTC" (got ${typeof e})`);try{hr(e)}catch(t){throw new Error(`Unknown time zone "${e}": expected an IANA time zone name, such as "America/Los_Angeles" or "UTC"`,{cause:t})}return e}i(pr,"assertTimeZone");var mr=new Map;function hr(e){let t=mr.get(e);return t||(t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),mr.set(e,t)),t}i(hr,"getZoneFormatter");function Ce(e,t){let r={};for(let o of hr(t).formatToParts(new Date(e*1e3)))r[o.type]=Number(o.value);let n=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)/1e3;return{year:r.year,month:r.month,day:r.day,hour:r.hour,minute:r.minute,second:r.second,offsetMinutes:(n-e)/60}}i(Ce,"toZonedDateParts");function gr(e,t){let r=i(n=>String(n).padStart(2,"0"),"pad");return`${String(e.year).padStart(4,"0")}-${r(e.month)}-${r(e.day)}${t}${r(e.hour)}:${r(e.minute)}:${r(e.second)}`}i(gr,"formatWallClock");function yr(e){let t=i(n=>String(n).padStart(2,"0"),"pad"),r=Math.abs(e);return`${e>=0?"+":"-"}${t(Math.floor(r/60))}:${t(r%60)}`}i(yr,"formatOffset");function Q(e=new Date){return{date:$o(e),timestamp:Math.floor(e.getTime()/1e3)}}i(Q,"toDatePayload");var Ao=/^(\d{4})-(\d{2})-(\d{2})(?:T|\s+)(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?\s*(?:(Z)|([+-])(\d{2}):?(\d{2}))$/i;function M(e){let t=Ao.exec(e.trim());if(!t)return null;let[r,n,o,a,s,c]=t.slice(1,7).map(Number),l=t[7]?0:Number(t[9])*60+Number(t[10]),u=t[8]==="-"?-l:l,f=new Date(Date.UTC(r,n-1,o,a,s,c));return!(f.getUTCFullYear()===r&&f.getUTCMonth()===n-1&&f.getUTCDate()===o&&f.getUTCHours()===a&&f.getUTCMinutes()===s&&f.getUTCSeconds()===c)||Number(t[10]??0)>59?null:{year:r,month:n,day:o,hour:a,minute:s,second:c,offsetMinutes:u,timestamp:Math.floor(f.getTime()/1e3)-u*60}}i(M,"parseHeaderDate");function Ne(e){return`${gr(e,"T")}${yr(e.offsetMinutes)}`}i(Ne,"formatIsoDate");var Do={"git-created":"git first commit","filesystem-created":"filesystem creation time"};function xr(e,t){let r=e.match(new RegExp(`${t}:[^\\S\\n]*(.*)$`,"m"));return r?r[1].trim():null}i(xr,"readHeaderField");function Fe(e){let t=null;for(let{source:r,payload:n}of e)n&&(!t||n.timestamp<t.payload.timestamp)&&(t={source:r,payload:n});return t}i(Fe,"pickOldestDate");function br({existing:e,gitCreated:t,filesystemCreated:r,fixCreatedDate:n=!1}){let o=[{source:"git-created",payload:t},{source:"filesystem-created",payload:r}];if(!e)return Fe(o);if(!n)return{source:"existing-header",payload:e};let a=M(e.date)?e:null;return Fe([{source:"existing-header",payload:a},...o])}i(br,"resolveCreatedDate");function kr(e,t=null){if(t)return Ce(e.timestamp,t).year;let r=M(e.date);return r?r.year:new Date(e.timestamp*1e3).getFullYear()}i(kr,"dateYear");function wr(e,t,r,n){let o=e.match(/^(.+?)\s*\((\d+)\)$/),a=o?M(o[1]):null;if(!o||!a)return n.push({check:`${r}-format`,field:t,advisory:!1,value:e,message:`${t} value "${e}" is not a "<datetime> (<epoch>)" pair with a recognised datetime`}),null;let s=Number.parseInt(o[2],10);return s!==a.timestamp&&n.push({check:`${r}-epoch`,field:t,advisory:!1,value:e,expected:`${o[1]} (${a.timestamp})`,message:`${t} epoch ${s} does not match ${o[1]} (expected ${a.timestamp})`}),{text:o[1],timestamp:a.timestamp}}i(wr,"checkDateValue");function Er(e,t={},r={}){let n=[],o=xr(e,"@Date"),a=o===null?null:wr(o,"@Date","created",n),s=Fe([{source:"git-created",payload:t.gitCreated},{source:"filesystem-created",payload:t.filesystemCreated}]);if(a&&s&&a.timestamp>s.payload.timestamp){let f=Do[s.source];n.push({check:"created-newer-than-source",field:"@Date",advisory:r.strictCreatedDate!==!0,value:o,expected:`${s.payload.date} (${s.payload.timestamp})`,source:s.source,message:`@Date ${a.text} is later than the ${f} ${s.payload.date} (${s.payload.timestamp})`})}let c=xr(e,"@Last modified time"),l=c===null?null:wr(c,"@Last modified time","modified",n),u=t.gitLastModified;return l&&u&&l.timestamp!==u.timestamp&&n.push({check:"modified-git",field:"@Last modified time",advisory:!0,value:c,expected:`${u.date} (${u.timestamp})`,message:`@Last modified time ${l.text} does not match the git last commit ${u.date} (${u.timestamp})`}),n}i(Er,"checkHeaderDates");function je(e){if(!e)return null;let t=M(e.date);return t&&t.timestamp!==e.timestamp?{date:e.date,timestamp:t.timestamp}:e}i(je,"repairDateEpoch");function Sr(e){let t=M(e.date);return t?{date:Ne(t),timestamp:t.timestamp}:e}i(Sr,"normalizeDatePayload");function $r(e,t){let r=M(e.date);if(!r)return e;let n=Ce(r.timestamp,t);return n.offsetMinutes===r.offsetMinutes||!Number.isInteger(n.offsetMinutes)?e:{date:/^\d{4}-\d{2}-\d{2}T/i.test(e.date.trim())?Ne(n):ve(n),timestamp:r.timestamp}}i($r,"convertDatePayload");import{relative as Co}from"node:path";import{extname as vo}from"node:path";function G(e,t={}){let r=vo(e).toLowerCase(),n=j(t.spacing,"spacing",B);return r.length===0?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */",spacing:n}:{...Ct(e,t),spacing:n}}i(G,"getHeaderSyntaxForFile");function Ar(e,t){let r=e.spacing??B;if(e.kind==="line"){let c=e.linePrefix||"#",l=typeof e.lineSeparator=="string"?e.lineSeparator:" ",u=Array.from({length:r},()=>c);return[...u,...t.map(f=>`${c}${l}${f}`),...u].join(`
|
|
7
7
|
`)}let n=e.blockStart||(e.kind==="html"?"<!--":"/**"),o=e.blockLinePrefix||(e.kind==="html"?" ":" * "),a=e.blockEnd||(e.kind==="html"?"-->":" */"),s=Array.from({length:r},()=>o.trimEnd());return[n,...s,...t.map(c=>`${o}${c}`),...s,a].join(`
|
|
8
|
-
`)}i(
|
|
9
|
-
`).slice(0,
|
|
10
|
-
`),s=
|
|
8
|
+
`)}i(Ar,"renderHeaderLines");function Dr(e){let t=`/${Co(e.projectRoot,e.absoluteFilePath).replace(/\\/g,"/")}`,r=G(e.absoluteFilePath,e.syntaxOptions||{language:e.language}),n=e.createdByName||e.authorName,o=e.createdByEmail||e.authorEmail,a=e.lastModifiedByName||e.authorName,s=e.lastModifiedByEmail||e.authorEmail,c=typeof e.companyName=="string"?e.companyName.trim():"",l=c.length>0?`${c} `:"",u=[`@Project: ${e.projectName}`,`@Filename: ${t}`,`@Date: ${e.createdAt.date} (${e.createdAt.timestamp})`,`@Author: ${n}`,`@Email: <${o}>`,"-----",`@Last modified by: ${a} (${s})`,`@Last modified time: ${e.lastModifiedAt.date} (${e.lastModifiedAt.timestamp})`,"-----",`@Copyright: Copyright (c) ${e.copyrightStartYear}-${e.currentYear} ${l}All rights reserved.`];return Ar(r,u)}i(Dr,"buildHeader");var No=Object.freeze(["projectName","filename","createdAt","authorName","authorEmail","lastModifiedByName","lastModifiedByEmail","lastModifiedAt","copyrightStartYear","copyrightEndYear","companyName"]);function C(e,t){let r=e.match(new RegExp(`@${t}:[ \\t]*(.*)$`,"m")),n=r?r[1].trim():"";return n.length>0?n:null}i(C,"readTag");function Fo(e){if(e===null)return{name:null,email:null};if(!e.endsWith(")"))return{name:e,email:null};let t=e.slice(0,-1),r=t.indexOf("(",t.lastIndexOf(")")+1);return r===-1?{name:e,email:null}:{name:t.slice(0,r).trimEnd()||null,email:t.slice(r+1)||null}}i(Fo,"splitLastModifiedBy");function jo(e){let t={startYear:null,endYear:null,companyName:null},r=e?.match(/^Copyright\s+\(c\)\s+(\d{4})/i);if(!r)return t;let n=e.slice(r[0].length),o=n.match(/^\s*-\s*(\d{4})/);o&&(n=n.slice(o[0].length));let a=n.toLowerCase(),s=a.endsWith("all rights reserved.")?20:a.endsWith("all rights reserved")?19:0;return s===0||!/^\s/.test(n)?t:{startYear:r[1],endYear:o?o[1]:null,companyName:n.slice(0,-s).trim()||null}}i(jo,"splitCopyright");function vr(e){let t=Fo(C(e,"Last modified by")),r=jo(C(e,"Copyright")),n=C(e,"Email");return{projectName:C(e,"Project"),filename:C(e,"Filename"),createdAt:C(e,"Date"),authorName:C(e,"Author"),authorEmail:n===null?null:n.replace(/^<(.*)>$/,"$1"),lastModifiedByName:t.name,lastModifiedByEmail:t.email,lastModifiedAt:C(e,"Last modified time"),copyrightStartYear:r.startYear,copyrightEndYear:r.endYear,companyName:r.companyName}}i(vr,"parseHeaderFields");function Cr(e,t){let r=vr(e??""),n=vr(t);return No.filter(o=>r[o]!==n[o]).map(o=>({field:o,previous:r[o],detected:n[o]}))}i(Cr,"compareHeaderFields");function ee(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(ee,"escapeRegex");function Le(e,t,r={}){let n=Nt(e,t,r);return n.length===0?{prefix:"",body:t}:{prefix:n,body:t.slice(n.length)}}i(Le,"splitPreservedPrefix");function Nr(e,t){if(t.kind==="html"){let n=ee(t.blockStart||"<!--"),o=ee(t.blockEnd||"-->");return e.match(new RegExp(`^${n}[\\s\\S]*?${o}\\n*`))}if(t.kind==="line"){let n=ee(t.linePrefix||"#");return e.match(new RegExp(`^(?:${n}.*\\n)+\\n*`))}let r=ee((t.blockEnd||" */").trim());return e.match(new RegExp(`^/\\*[\\s\\S]*?${r}\\n*`))}i(Nr,"matchHeaderSegment");function te(e,t="",r={}){let{prefix:n,body:o}=Le(t,e,r),a=o.split(`
|
|
9
|
+
`).slice(0,Ft).join(`
|
|
10
|
+
`),s=G(t,r);if(!Nr(a,s))return null;let l=0,u=0;for(;;){let f=a.slice(l),m=Nr(f,s);if(!m||!m[0].includes("@Project:"))break;l+=m[0].length,u=l}return u===0?null:{start:n.length,end:n.length+u}}i(te,"findProjectHeader");function Me(e,t,r="",n={}){let o=te(e,r,n),a=j(n.margin,"margin",X),s=G(r,n).kind==="line"?Math.max(1,a):a,c=`
|
|
11
11
|
`.repeat(s+1),l=i(g=>g.trim()===""?`${t}
|
|
12
|
-
`:`${t}${c}${g}`,"join");if(!o){let{prefix:g,body:x}=
|
|
12
|
+
`:`${t}${c}${g}`,"join");if(!o){let{prefix:g,body:x}=Le(r,e,n),d=`${g}${l(x.replace(/^\n+/,""))}`;return{nextContent:d,changed:d!==e}}let u=e.slice(0,o.start),f=e.slice(o.end).replace(/^\n+/,""),m=`${u}${l(f)}`;return{nextContent:m,changed:m!==e}}i(Me,"replaceOrInsertHeader");function Re(e,t="",r={}){let n=te(e,t,r),{prefix:o,body:a}=n?{prefix:e.slice(0,n.start),body:e.slice(n.end)}:Le(t,e,r),s=a.replace(/^\n+/,"");return`${o}${s.trim()===""?"":s}`}i(Re,"extractHeaderlessBody");function Lo(e,t){let r=e.length,n=t.length,o=Array.from({length:r+1},()=>new Array(n+1).fill(0));for(let l=r-1;l>=0;l-=1)for(let u=n-1;u>=0;u-=1)o[l][u]=e[l]===t[u]?o[l+1][u+1]+1:Math.max(o[l+1][u],o[l][u+1]);let a=[],s=0,c=0;for(;s<r&&c<n;)e[s]===t[c]?(a.push({type:" ",line:e[s]}),s+=1,c+=1):o[s+1][c]>=o[s][c+1]?(a.push({type:"-",line:e[s]}),s+=1):(a.push({type:"+",line:t[c]}),c+=1);for(;s<r;s+=1)a.push({type:"-",line:e[s]});for(;c<n;c+=1)a.push({type:"+",line:t[c]});return a}i(Lo,"diffLines");function Fr(e,t){return`${t===0?e:e+1},${t}`}i(Fr,"formatRange");function jr(e,t,r={}){let n=e===null?[]:e.split(`
|
|
13
13
|
`),o=t.split(`
|
|
14
|
-
`),a=
|
|
15
|
-
`)}i(
|
|
16
|
-
`).length-1;
|
|
14
|
+
`),a=Lo(n,o),s=Math.max(0,r.context??3),c=r.lineOffset??0,l=[];if(a.forEach((g,x)=>{if(g.type===" ")return;let d=l[l.length-1];d&&x-d.last<=s*2+1?d.last=x:l.push({first:x,last:x})}),l.length===0)return"";let u=r.fromFile??"a",f=r.toFile??"b",m=[`--- ${e===null?"/dev/null":u}`,`+++ ${f}`];for(let g of l){let x=Math.max(0,g.first-s),d=Math.min(a.length,g.last+s+1),h=a.slice(0,x),b=a.slice(x,d),$=h.filter(k=>k.type!=="+").length+c,v=h.filter(k=>k.type!=="-").length+c,R=b.filter(k=>k.type!=="+").length,V=b.filter(k=>k.type!=="-").length;m.push(`@@ -${Fr($,R)} +${Fr(v,V)} @@`);for(let k of b)m.push(`${k.type}${k.line}`)}return m.join(`
|
|
15
|
+
`)}i(jr,"createUnifiedDiff");function Io(e){return q(e,"configFile")}i(Io,"resolveRuntimeOptions");function Oo(e){if(e==null)return[];let t=Array.isArray(e)?e:[e];if(t.some(r=>typeof r!="string"))throw new Error(`input must be a path or an array of paths, got ${JSON.stringify(e)}`);return t.filter(r=>r.trim().length>0)}i(Oo,"resolveInputs");function To(e){let t=e.match(/@Author:\s*(.+)$/m),r=e.match(/@Email:\s*<([^>\n]+)>/m);return{authorName:t?.[1]?.trim(),authorEmail:r?.[1]?.trim()}}i(To,"extractHeaderAuthorIdentity");function Ho(e){let t=e.match(/@Last modified by:\s*(.+?)\s*\(([^)\n]+)\)\s*$/m);return{authorName:t?.[1]?.trim(),authorEmail:t?.[2]?.trim()}}i(Ho,"extractHeaderLastModifiedIdentity");function _o(e){let t=e.match(/@Date:\s*(.+?)\s*\((\d+)\)$/m);if(!t||!t[1]||!t[2])return null;let r=Number.parseInt(t[2],10);return Number.isNaN(r)?null:{date:t[1].trim(),timestamp:r}}i(_o,"extractHeaderCreatedAt");function Uo(e){let t=e.match(/@Last modified time:\s*(.+?)\s*\((\d+)\)$/m);if(!t||!t[1]||!t[2])return null;let r=Number.parseInt(t[2],10);return Number.isNaN(r)?null:{date:t[1].trim(),timestamp:r}}i(Uo,"extractHeaderLastModifiedAt");async function zo(e,t,r){let n=await dr(t);return n.state!=="tracked"?{edited:n.state==="untracked",state:n.state}:{edited:Re(n.content,t,r)!==Re(e,t,r),state:"tracked"}}i(zo,"detectContentEdit");async function Mr(e={}){let t=await Io(e),r=t.timezone===void 0||t.timezone===null?null:pr(t.timezone),n=t.convertTimezone===!0;if(n&&!r)throw new Error("convertTimezone requires timezone: set timezone (CLI --timezone <name>) to the IANA zone to convert header dates into");let o=At(t.forcedDetectors),a=Lr(t.projectRoot||t.cwd||process.cwd()),s=await De({...t,cwd:a});j(t.spacing,"spacing",B),j(t.margin,"margin",X);let c=t.check===!0,l=c||t.dryRun===!0,u=t.fixCreatedDate===!0,f=i(y=>y,"keepDate"),m=t.normalizeDateFormat===!0?Sr:f,g=r?y=>$r(y,r):f,x=n?g:f,d={language:s.language,enabledDetectors:t.enabledDetectors,disabledDetectors:t.disabledDetectors,forcedDetectors:o,includeFolders:t.includeFolders,excludeFolders:t.excludeFolders,includeExtensions:t.includeExtensions,gitignore:t.gitignore},h=Oo(t.input),b;if(h.length>0){let y=new Set;for(let P of h){let p=Lr(a,P),I=await Ro(p).catch(()=>null);if(!I)throw new Error(`Input path does not exist: ${P}`);if(I.isFile())y.add(p);else if(I.isDirectory())for(let N of await we({...d,projectRoot:p}))y.add(N);else throw new Error(`Input path must be a file or directory: ${P}`)}b=Array.from(y)}else b=await we({...d,projectRoot:a});let $=new Date().getFullYear(),v=[],R=[],V=new Set,k=0,Oe=0,Te=0;for(let y of b){let P=vt(y,{enabledDetectors:t.enabledDetectors,disabledDetectors:t.disabledDetectors,forcedDetectors:o});if(P!==null){R.push({file:Pe(a,y),reason:P});continue}let p=await De({...t,cwd:a,targetFilePath:y});V.add(`${p.language}:${p.projectRoot}`);let I=Pe(a,y),N=await Mo(y,"utf8"),T={language:p.language,enabledDetectors:t.enabledDetectors,disabledDetectors:t.disabledDetectors,forcedDetectors:o,detectorSyntaxOverrides:t.detectorSyntaxOverrides,spacing:t.spacing,margin:t.margin},re=te(N,y,T),E=re?N.slice(re.start,re.end):"",He=E.length>0?To(E):{},_e=E.length>0?Ho(E):{},Tr=E.length>0?_o(E):null,Hr=E.length>0?Uo(E):null,Ue=await jt(y),ze=Pe(p.projectRoot,y),Be=await ur(p.projectRoot,ze),H=await fr(p.projectRoot,ze),We=Q(Ue.createdAt),ne=br({existing:je(Tr),gitCreated:Be,filesystemCreated:We,fixCreatedDate:u}),_=je(Hr),Ye=ne.source,_r=_?"existing-header":H?"git-last-modified":"filesystem-updated",oe=m(Ye==="existing-header"?x(ne.payload):g(ne.payload)),Ur=p.copyrightStartYear===null?"created-date":"option",Ge=p.copyrightStartYear??kr(oe,r),Ve=m(_?x(_):g(H||Q(Ue.updatedAt))),Je=t.forceAuthorUpdate===!0,zr=t.forceLastModifiedAuthorUpdate===!0,qe=await zo(N,y,T),Ke=zr||qe.edited,Xe=i(D=>Dr({absoluteFilePath:y,language:p.language,syntaxOptions:T,projectRoot:p.projectRoot,projectName:p.projectName,createdByName:Je?p.authorName:He.authorName||p.authorName,createdByEmail:Je?p.authorEmail:He.authorEmail||p.authorEmail,lastModifiedByName:Ke?p.authorName:_e.authorName||p.authorName,lastModifiedByEmail:Ke?p.authorEmail:_e.authorEmail||p.authorEmail,authorName:p.authorName,authorEmail:p.authorEmail,createdAt:oe,lastModifiedAt:D,copyrightStartYear:Ge,companyName:p.companyName,currentYear:$}),"renderHeader"),Ze=Xe(Ve),Qe=Me(N,Ze,y,T),Br=qe.edited&&_!==null&&H!==null&&_.timestamp<H.timestamp,J=Qe.changed||Br,et=J?m(g(Q(new Date))):Ve,Wr=J?"current-time-on-change":_r,U=J?Xe(et):Ze,O=J?Me(N,U,y,T):Qe,ie={file:I,changed:O.changed};if(c){let D=Er(E,{gitCreated:Be,gitLastModified:H,filesystemCreated:We},{strictCreatedDate:t.strictCreatedDate===!0}),z=D.filter(ae=>ae.advisory).length;ie.dateIssues=D,Te+=z,Oe+=D.length>z?1:0}if(t.sampleOutput===!0&&O.changed){let D=E.length>0?E.trimEnd():null,z=I.replace(/\\/g,"/"),ae=O.nextContent.slice(0,O.nextContent.indexOf(U)).split(`
|
|
16
|
+
`).length-1;ie.sample={previousValue:D,newValue:U,diff:jr(D,U,{fromFile:`a/${z}`,toFile:`b/${z}`,lineOffset:ae}),issues:Cr(D,U),detectedValues:{projectName:p.projectName,projectNameSource:p.projectNameSource,language:p.language,projectRoot:p.projectRoot,marker:p.marker,authorName:p.authorName,authorEmail:p.authorEmail,companyName:p.companyName,companyNameSource:p.companyNameSource,copyrightStartYear:Ge,copyrightStartYearSource:Ur,createdAtSource:Ye,lastModifiedAtSource:Wr,createdAt:oe,lastModifiedAt:et}}}v.push(ie),O.changed&&(k+=1,l||await Po(y,O.nextContent,"utf8"))}return{metadata:s,detectedProjects:Array.from(V),filesScanned:b.length-R.length,filesUpdated:k,filesSkipped:R.length,dryRun:l,check:c,...c?{filesWithDateDrift:Oe,dateAdvisories:Te}:{},changes:v,skipped:R}}i(Mr,"fixHeaders");function Bo(e){return Mr(e)}i(Bo,"fixHeaders");var Rr=Bo;var Go=`fix-headers CLI
|
|
17
17
|
|
|
18
18
|
Usage:
|
|
19
19
|
fix-headers [options]
|
|
@@ -31,8 +31,8 @@ Options:
|
|
|
31
31
|
--verbose Print updated file paths in summary mode; with --sample-output or --diff, also print each file's field differences
|
|
32
32
|
--sample-output Show previous/new header sample for changed files
|
|
33
33
|
--diff Print a unified diff of each changed file's header (implies sample output)
|
|
34
|
-
--force-author-update
|
|
35
|
-
--force-last-modified-author-update
|
|
34
|
+
--force-author-update Replace an existing @Author/@Email with the detected/current values
|
|
35
|
+
--force-last-modified-author-update Write the detected identity as @Last modified by on every file, edited or not
|
|
36
36
|
--use-gpg-signer-author Use signed-commit UID (%GS) for detected @Author
|
|
37
37
|
--cwd <path> Working directory for project detection
|
|
38
38
|
--input <path> File or folder to process instead of the whole project (repeatable)
|
|
@@ -62,5 +62,5 @@ Examples:
|
|
|
62
62
|
fix-headers --check --verbose
|
|
63
63
|
fix-headers --timezone America/Los_Angeles --convert-timezone
|
|
64
64
|
fix-headers --project-name @scope/pkg --company-name "Catalyzed Motivation Inc."
|
|
65
|
-
`;function
|
|
65
|
+
`;function Vo(e){return e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase())}i(Vo,"toCamelCase");function Jo(e){let t={},r={help:!1,json:!1,diff:!1},n={"include-folder":"includeFolders","exclude-folder":"excludeFolders","include-extension":"includeExtensions","enable-detector":"enabledDetectors","disable-detector":"disabledDetectors","force-detector":"forcedDetectors",input:"input"},o={cwd:"cwd","project-name":"projectName",language:"language","project-root":"projectRoot",marker:"marker","author-name":"authorName","author-email":"authorEmail",company:"company","company-name":"companyName","copyright-start-year":"copyrightStartYear",spacing:"spacing",margin:"margin",timezone:"timezone",config:"config"};for(let a=0;a<e.length;a+=1){let s=e[a];if(s==="-h"||s==="--help"){r.help=!0;continue}if(s==="--json"){r.json=!0;continue}if(s==="--diff"){r.diff=!0;continue}if(s==="--verbose"){t.verbose=!0;continue}if(s==="--dry-run"){t.dryRun=!0;continue}if(s==="--check"){t.check=!0;continue}if(s==="--fix-created-date"){t.fixCreatedDate=!0;continue}if(s==="--strict-created-date"){t.strictCreatedDate=!0;continue}if(s==="--normalize-date-format"){t.normalizeDateFormat=!0;continue}if(s==="--convert-timezone"){t.convertTimezone=!0;continue}if(s==="--sample-output"){t.sampleOutput=!0;continue}if(s==="--force-author-update"){t.forceAuthorUpdate=!0;continue}if(s==="--force-last-modified-author-update"){t.forceLastModifiedAuthorUpdate=!0;continue}if(s==="--use-gpg-signer-author"){t.useGpgSignerAuthor=!0;continue}if(!s.startsWith("--"))throw new Error(`Unexpected argument: ${s}`);let c=s.slice(2);if(c==="include-folder-non-recursive"){let f=e[a+1];if(!f||f.startsWith("--"))throw new Error(`Missing value for --${c}`);a+=1;let m=Array.isArray(t.includeFolders)?t.includeFolders:[];t.includeFolders=[...m,{path:f,recursive:!1}];continue}if(n[c]){let f=e[a+1];if(!f||f.startsWith("--"))throw new Error(`Missing value for --${c}`);a+=1;let m=n[c],g=Array.isArray(t[m])?t[m]:[];t[m]=Array.from(new Set([...g,f]));continue}if(o[c]){let f=e[a+1];if(!f||f.startsWith("--"))throw new Error(`Missing value for --${c}`);a+=1;let m=o[c];if(m==="copyrightStartYear"||m==="spacing"||m==="margin"){if(t[m]=Number.parseInt(f,10),Number.isNaN(t[m]))throw new Error(`Invalid number for --${c}: ${f}`)}else m==="marker"&&f==="null"?t[m]=null:t[m]=f;continue}let l=Vo(c),u=e[a+1];if(!u||u.startsWith("--"))throw new Error(`Unknown or malformed flag: --${c}`);a+=1,t[l]=u}return{options:t,help:r.help,json:r.json,diff:r.diff}}i(Jo,"parseCliArgs");function qo(e){return q(e,"config")}i(qo,"applyConfigFile");function Ie(e){if(!e||typeof e!="object")return[];let t=e;return(Array.isArray(t.changes)?t.changes:[]).filter(n=>n&&n.changed===!0&&n.sample&&typeof n.sample.newValue=="string")}i(Ie,"getSampledChanges");function Ir(e){return typeof e=="string"?`"${e}"`:"(missing)"}i(Ir,"formatIssueValue");function Ko(e,t){for(let r of Ie(t)){let n=Array.isArray(r.sample.issues)?r.sample.issues:[];if(e(`issues: ${r.file||"<unknown-file>"}`),n.length===0){e(" (no field differences; header formatting only)");continue}for(let o of n)e(` ${o?.field||"<unknown-field>"}: found ${Ir(o?.previous)}, expected ${Ir(o?.detected)}`)}}i(Ko,"printIssues");function Xo(e,t){for(let r of Ie(t))typeof r.sample.diff=="string"&&r.sample.diff.length>0&&e(r.sample.diff)}i(Xo,"printDiffs");function Zo(e,t){for(let r of Ie(t))e(`sample: ${r.file||"<unknown-file>"}`),e("previous:"),e(r.sample.previousValue===null?"(none)":String(r.sample.previousValue)),e("new:"),e(r.sample.newValue),r.sample.detectedValues&&typeof r.sample.detectedValues=="object"&&(e("detected-values:"),e(JSON.stringify(r.sample.detectedValues,null,2)))}i(Zo,"printSampleOutput");function Qo(e,t){if(!t||typeof t!="object")return;let r=t,o=(Array.isArray(r.changes)?r.changes:[]).filter(a=>a&&a.changed===!0).map(a=>a.file||"<unknown-file>");for(let a of o)e(`updated: ${a}`)}i(Qo,"printChangedFiles");function ei(e,t){let r=Array.isArray(t.skipped)?t.skipped:[];for(let n of r)e(`skipped: ${n?.file||"<unknown-file>"} (${n?.reason||"no reason given"})`)}i(ei,"printSkipped");function Or(e,t,r,n){let o=r.sampleOutput===!0||n;r.verbose===!0&&(Qo(e,t),o&&Ko(e,t)),r.sampleOutput===!0&&Zo(e,t),n&&Xo(e,t)}i(Or,"printDetails");function ti(e,t,r){let n=Array.isArray(t.changes)?t.changes:[];for(let o of n){let a=Array.isArray(o?.dateIssues)?o.dateIssues:[];for(let s of a)s.advisory===!0&&!r||e(`${s.advisory===!0?"advisory":"drift"}: ${o.file||"<unknown-file>"}: ${s.message}`)}}i(ti,"printDateIssues");async function ri(e,t={}){let r=t.runner||Rr,n=t.stdout||console.log,o=t.stderr||console.error;try{let a=Jo(e);if(a.help)return n(Go),0;let s=await qo(a.options),c=await r(a.diff?{...s,sampleOutput:!0}:s),l=c&&typeof c=="object"&&c.check===!0?c:null,u=l&&Number(l.filesWithDateDrift)>0?1:0;if(a.json)return n(JSON.stringify(c,null,2)),u;if(l)return n(`fix-headers check: scanned=${l.filesScanned??0}, drift=${l.filesWithDateDrift??0}, advisories=${l.dateAdvisories??0}`),ti(n,l,s.verbose===!0),u;if(c&&typeof c=="object"){let f=c,m=Number(f.filesSkipped)>0?`, skipped=${f.filesSkipped}`:"";n(`fix-headers complete: scanned=${f.filesScanned??0}, updated=${f.filesUpdated??0}${m}, dryRun=${f.dryRun===!0}`),ei(n,f),Or(n,c,s,a.diff)}else Or(n,c,s,a.diff),n("fix-headers complete");return 0}catch(a){let s=a instanceof Error?a.message:String(a);return o(`fix-headers failed: ${s}`),1}}i(ri,"runCli");function ni(e=process.argv,t=import.meta.url,r=ri){let n=!1;if(e[1])try{let o=Pr(e[1]),a=Pr(Wo(t));n=o===a}catch{n=t===Yo(e[1]).href}return n?(r(e.slice(2)).then(o=>{process.exitCode=o}),!0):!1}i(ni,"runCliAsMain");ni();export{qo as applyConfigFile,Jo as parseCliArgs,ri as runCli,ni as runCliAsMain};
|
|
66
66
|
//# sourceMappingURL=fix-headers.mjs.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var Rr=Object.defineProperty;var i=(e,t)=>Rr(e,"name",{value:t,configurable:!0});import{readFile as wo,stat as bo,writeFile as Eo}from"node:fs/promises";import{relative as Te,resolve as Ar}from"node:path";import{readFile as jr}from"node:fs/promises";import{createRequire as Ir}from"node:module";import{dirname as Tr,isAbsolute as Or,resolve as Ke}from"node:path";var _r=3e4,Hr=new Set(["localhost","127.0.0.1","[::1]"]);function ue(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ue,"isPlainObject");function fe(e,t){let r={...e};for(let[n,o]of Object.entries(t))n!=="__proto__"&&(r[n]=ue(r[n])&&ue(o)?fe(r[n],o):o);return r}i(fe,"mergeConfig");function Xe(e){return e.kind==="file"?e.path:e.href}i(Xe,"describeSource");async function Ur(e){if(e.kind==="file")return{text:await jr(e.path,"utf8"),source:e};let t;try{t=await fetch(e.href,{cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(_r)})}catch(r){let n=r.cause instanceof Error?r.cause.message:r.message;throw new Error(`Failed to fetch config ${e.href}: ${n}`,{cause:r})}if(!t.ok)throw new Error(`Failed to fetch config ${e.href}: HTTP ${t.status} ${t.statusText}`);return{text:await t.text(),source:{kind:"url",href:t.url}}}i(Ur,"readSource");function qe(e){if(e.protocol==="http:"&&!Hr.has(e.hostname))throw new Error(`Refusing to fetch config over plain http: ${e.href} (use https)`);return{kind:"url",href:e.href}}i(qe,"toUrlSource");function Br(e,t){if(/^https?:\/\//i.test(e))return qe(new URL(e));if(/^[a-z][a-z\d+.-]+:\/\//i.test(e))throw new Error(`Unsupported extends URL "${e}" in ${Xe(t)}; use https, a file path or a package path`);let r=/^\.{1,2}[\\/]/.test(e);if(t.kind==="url"){if(r||e.startsWith("/"))return qe(new URL(e,t.href));throw new Error(`Cannot extend package "${e}" from the remote config ${t.href}; use a URL or a relative path`)}if(r||Or(e))return{kind:"file",path:Ke(Tr(t.path),e)};try{return{kind:"file",path:Ir(t.path).resolve(e)}}catch(n){throw new Error(`Cannot resolve extends "${e}" from ${t.path}: ${n.message}`,{cause:n})}}i(Br,"resolveReference");function zr(e,t){if(e===void 0)return[];let r=Array.isArray(e)?e:[e];if(!r.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`Config "extends" must be a string or an array of strings: ${t}`);return r.map(n=>n.trim())}i(zr,"readExtends");async function Ze(e,t){let r=Xe(e);if(t.includes(r))throw new Error(`Config extends cycle: ${[...t,r].join(" -> ")}`);let{text:n,source:o}=await Ur(e),a;try{a=JSON.parse(n)}catch(u){throw new Error(`Config ${r} is not valid JSON: ${u.message}`,{cause:u})}if(!ue(a))throw new Error(`Config file must contain a JSON object: ${r}`);let{extends:s,...l}=a,c={};for(let u of zr(s,r))c=fe(c,await Ze(Br(u,o),[...t,r]));return fe(c,l)}i(Ze,"loadSource");function Yr(e,t=process.cwd()){return Ze({kind:"file",path:Ke(t,e)},[])}i(Yr,"loadConfigFile");async function Qe(e,t){let r=typeof e[t]=="string"?e[t].trim():"";if(r.length===0)return e;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o={...await Yr(r,n),...e};return delete o[t],o}i(Qe,"applyConfigOption");import{extname as me}from"node:path";import{extname as Gr}from"node:path";var et=[".css"];function Wr(e){let t=Gr(e).toLowerCase();return et.includes(t)?{kind:"block",blockStart:"/*",blockLinePrefix:" * ",blockEnd:" */"}:null}i(Wr,"resolveCssCommentSyntax");var tt={id:"css",extensions:et,enabledByDefault:!0,resolveCommentSyntax(e){return Wr(e)}};import{extname as Vr}from"node:path";var rt=[".go"];function Jr(e){let t=Vr(e).toLowerCase();return rt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(Jr,"resolveGoCommentSyntax");var nt={id:"go",extensions:rt,enabledByDefault:!0,resolveCommentSyntax(e){return Jr(e)}};import{extname as qr}from"node:path";var ot=[".html",".htm"];function Kr(e){let t=qr(e).toLowerCase();return ot.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(Kr,"resolveHtmlCommentSyntax");var it={id:"html",extensions:ot,enabledByDefault:!0,resolveCommentSyntax(e){return Kr(e)}};import{extname as Xr}from"node:path";var at=[".jsonv",".jsonc",".json5"];function Zr(e){let t=Xr(e).toLowerCase();return at.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(Zr,"resolveJsonCommentSyntax");var st={id:"json",extensions:at,enabledByDefault:!0,resolveCommentSyntax(e){return Zr(e)}};import{extname as Qr}from"node:path";var ct=[".md",".markdown"];function en(e){let t=Qr(e).toLowerCase();return ct.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(en,"resolveMarkdownCommentSyntax");function tn(e,t){let r=t.match(/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);return r?r[0]:""}i(tn,"resolveMarkdownPreservedPrefix");var lt={id:"markdown",extensions:ct,enabledByDefault:!1,requiresForce:!0,resolvePreservedPrefix(e,t){return tn(e,t)},resolveCommentSyntax(e){return en(e)}};import{extname as rn}from"node:path";var ut=[".js",".mjs",".cjs",".ts",".tsx",".jsx"];function nn(e){let t=rn(e).toLowerCase();return ut.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(nn,"resolveNodeCommentSyntax");function on(e,t){let r=t.match(/^#!.*\b(node|bun|deno|tsx|ts-node)\b.*(?:\r?\n|$)/);return r?r[0]:""}i(on,"resolveNodePreservedPrefix");var ft={id:"node",extensions:ut,enabledByDefault:!0,resolvePreservedPrefix(e,t){return on(e,t)},resolveCommentSyntax(e){return nn(e)}};import{extname as an}from"node:path";var mt=[".php"];function sn(e){let t=an(e).toLowerCase();return mt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(sn,"resolvePhpCommentSyntax");var dt={id:"php",extensions:mt,enabledByDefault:!0,resolveCommentSyntax(e){return sn(e)}};import{extname as cn}from"node:path";var pt=[".py"];function ln(e,t){let r=t.match(/^#!.*\bpython(?:\d+(?:\.\d+)*)?\b.*(?:\r?\n|$)/);return r?r[0]:""}i(ln,"resolvePythonPreservedPrefix");var ht={id:"python",extensions:pt,enabledByDefault:!0,resolvePreservedPrefix(e,t){return ln(e,t)},resolveCommentSyntax(e){let t=cn(e).toLowerCase();return pt.includes(t)?{kind:"line",linePrefix:"#"}:null}};import{extname as un}from"node:path";var gt=[".rs"];function fn(e){let t=un(e).toLowerCase();return gt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(fn,"resolveRustCommentSyntax");var yt={id:"rust",extensions:gt,enabledByDefault:!0,resolveCommentSyntax(e){return fn(e)}};import{extname as mn}from"node:path";var xt=[".yaml",".yml"];function dn(e){let t=mn(e).toLowerCase();return xt.includes(t)?{kind:"line",linePrefix:"#"}:null}i(dn,"resolveYamlCommentSyntax");var wt={id:"yaml",extensions:xt,enabledByDefault:!0,resolveCommentSyntax(e){return dn(e)}};var Z=[tt,nt,it,st,lt,ft,dt,ht,yt,wt],pn=new Map(Z.map(e=>[e.id,e]));function hn(e,t){return!t||typeof t!="object"?e:e.kind==="line"?{...e,linePrefix:typeof t.linePrefix=="string"&&t.linePrefix.length>0?t.linePrefix:e.linePrefix,lineSeparator:typeof t.lineSeparator=="string"?t.lineSeparator:e.lineSeparator}:{...e,blockStart:typeof t.blockStart=="string"&&t.blockStart.length>0?t.blockStart:e.blockStart,blockLinePrefix:typeof t.blockLinePrefix=="string"&&t.blockLinePrefix.length>0?t.blockLinePrefix:e.blockLinePrefix,blockEnd:typeof t.blockEnd=="string"&&t.blockEnd.length>0?t.blockEnd:e.blockEnd}}i(hn,"applySyntaxOverride");function bt(e){if(e==null)return[];if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`forcedDetectors must be an array of detector ids, got ${JSON.stringify(e)}`);let t=Z.filter(r=>r.requiresForce===!0).map(r=>r.id);for(let r of e){if(!pn.has(r))throw new Error(`forcedDetectors: unknown detector "${r}" (force-only detectors: ${t.join(", ")})`);if(!t.includes(r))throw new Error(`forcedDetectors: "${r}" does not need forcing (force-only detectors: ${t.join(", ")})`)}return Array.from(new Set(e))}i(bt,"resolveForcedDetectors");function v(e={}){let t=new Set(Array.isArray(e.enabledDetectors)?e.enabledDetectors:[]),r=new Set(Array.isArray(e.disabledDetectors)?e.disabledDetectors:[]),n=new Set(Array.isArray(e.forcedDetectors)?e.forcedDetectors:[]);return Z.filter(o=>o.requiresForce===!0?n.has(o.id)&&!r.has(o.id):t.size>0?t.has(o.id):r.has(o.id)?!1:o.enabledByDefault)}i(v,"getEnabledDetectors");function Et(e={}){if(Array.isArray(e.includeExtensions)&&e.includeExtensions.length>0)return new Set(e.includeExtensions.map(r=>r.toLowerCase()));let t=v(e);return new Set(t.flatMap(r=>r.extensions))}i(Et,"getAllowedExtensions");function St(e,t={}){let r=me(e).toLowerCase();if(v(t).some(s=>s.extensions.includes(r)&&s.resolveCommentSyntax(e)!==null))return null;if(r.length===0)return"the file has no extension, so its comment syntax is unknown";let o=new Set(Array.isArray(t.forcedDetectors)?t.forcedDetectors:[]),a=Z.find(s=>s.requiresForce===!0&&s.extensions.includes(r)&&!o.has(s.id));return a?`${r} files get a header only when forced (--force-detector ${a.id} / forcedDetectors: ["${a.id}"])`:`no enabled detector handles ${r} files`}i(St,"getHeaderSkipReason");function kt(e,t={}){let r=me(e).toLowerCase(),n=Array.isArray(t.detectors)?t.detectors:v(t);for(let o of n){if(!o.extensions.includes(r))continue;let a=o.resolveCommentSyntax(e);if(a){let s=t.detectorSyntaxOverrides&&typeof t.detectorSyntaxOverrides=="object"?t.detectorSyntaxOverrides:{};return hn(a,s[o.id])}}return{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}}i(kt,"getCommentSyntaxForFile");function Dt(e,t,r={}){let n=me(e).toLowerCase(),o=v(r);for(let a of o)if(a.extensions.includes(n))return typeof a.resolvePreservedPrefix=="function"?a.resolvePreservedPrefix(e,t):"";return""}i(Dt,"getPreservedPrefixForFile");var $t=200,U=1,Q=2;function F(e,t,r){if(e==null)return r;if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error(`${t} must be a whole number of 0 or more, got ${JSON.stringify(e)}`);return e}i(F,"resolveLayoutCount");import{existsSync as An}from"node:fs";import{join as be,relative as It,resolve as Ee,sep as xe}from"node:path";import{realpath as Cn,stat as vn}from"node:fs/promises";import{access as gn,readdir as yn,readFile as Ai,stat as xn}from"node:fs/promises";import{constants as wn}from"node:fs";import{dirname as Fi,join as bn,resolve as Pi}from"node:path";async function de(e){try{return await gn(e,wn.F_OK),!0}catch{return!1}}i(de,"pathExists");async function pe(e,t){let r=[],n=await yn(e,{withFileTypes:!0});for(let o of n){let a=bn(e,o.name);if(o.isDirectory()&&t.recursive===!1||o.isDirectory()&&t.ignoreFolders.has(o.name)||o.isDirectory()&&await t.shouldSkipDirectory?.(a,o.name)===!0)continue;if(o.isDirectory()){let c=await pe(a,t);r.push(...c);continue}if(!o.isFile())continue;let s=o.name.lastIndexOf(".");if(s===-1)continue;let l=o.name.slice(s).toLowerCase();t.allowedExtensions.has(l)&&r.push(a)}return r}i(pe,"walkFiles");async function Nt(e){let t=await xn(e);return{createdAt:t.birthtimeMs>0&&t.birthtime<t.mtime?t.birthtime:t.mtime,updatedAt:t.mtime}}i(Nt,"readFileDates");import{execFile as En}from"node:child_process";import{lstat as Sn,readFile as kn}from"node:fs/promises";import{dirname as At,isAbsolute as Dn,join as Ft,relative as Pt,resolve as he,sep as Lt}from"node:path";import $n from"ignore";function Ct(e,t){return new Promise(r=>{En("git",t,{cwd:e,encoding:"utf8",maxBuffer:Number.POSITIVE_INFINITY},(n,o)=>{if(!n){r({code:0,stdout:o});return}r({code:typeof n.code=="number"?n.code:-1,stdout:""})})})}i(Ct,"runGitCommand");function ye(e,t){return Pt(e,t).split(Lt).join("/")}i(ye,"toPosixRelative");async function Mt(e){try{return $n().add(await kn(e,"utf8"))}catch{return null}}i(Mt,"readIgnoreFile");async function Nn(e){return Sn(Ft(e,".git")).then(()=>!0,()=>!1)}i(Nn,"hasGitEntry");function vt(e,t,r){for(let n=e.length-1;n>=0;n--){let{base:o,rules:a}=e[n],s=a.test(`${ye(o,t)}${r?"/":""}`);if(s.ignored||s.unignored)return s.ignored}return!1}i(vt,"matchesRules");async function Rt(e,t){let r=await Mt(Ft(e,".gitignore"));return{kind:"rules",nested:!0,excluded:!1,matchers:r?[...t,{base:e,rules:r}]:t}}i(Rt,"buildRulesContext");async function ge(e){let[t,r]=await Promise.all([Ct(e,["check-ignore","-q","."]),Ct(e,["ls-files","--cached","--others","--exclude-standard","-z"])]);if(t.code!==1||r.code!==0)return Rt(e,[]);let n=new Set,o=new Set;for(let a of r.stdout.split("\0")){let s=a.endsWith("/")?a.slice(0,-1):a;if(s.length!==0){n.add(s);for(let l=s.indexOf("/");l!==-1;l=s.indexOf("/",l+1))o.add(s.slice(0,l))}}return{kind:"git",root:e,entries:n,dirs:o}}i(ge,"resolveScopeContext");function jt(e){let t=he(e.root),r=e.gitignore;if(r===!1)return{isIgnored:i(async()=>!1,"isIgnored")};let n=new Map,o=i(async()=>{if(typeof r!="string"&&!Array.isArray(r))return ge(t);let l=typeof r=="string"?[r]:r.filter(u=>typeof u=="string"),c=[];for(let u of l){let d=await Mt(he(t,u));d&&c.push({base:t,rules:d})}return{kind:"rules",nested:!1,excluded:!1,matchers:c}},"buildRootContext"),a=i(l=>{let c=n.get(l);return c||(c=l===t?o():s(l),n.set(l,c)),c},"contextFor"),s=i(async l=>{let c=await a(At(l));return c.kind==="git"?c.entries.has(ye(c.root,l))?ge(l):c:!c.nested||c.excluded?c:vt(c.matchers,l,!0)?{...c,excluded:!0}:await Nn(l)?ge(l):Rt(l,c.matchers)},"deriveContext");return{async isIgnored(l,c){let u=he(l),d=Pt(t,u);if(d.length===0||d===".."||d.startsWith(`..${Lt}`)||Dn(d))return!1;let p=await a(At(u));if(p.kind==="git"){let g=ye(p.root,u);return!(p.entries.has(g)||c&&p.dirs.has(g))}return p.excluded||vt(p.matchers,u,c)}}}i(jt,"createIgnoreFilter");function Fn(e){return Et(e)}i(Fn,"resolveExtensions");var Pn=Object.freeze(["node_modules","bower_components","jspm_packages",".pnpm-store",".yarn"]),_t=new Set([".git",...Pn]),Ln=Object.freeze(["autoload.php","modules.txt"]);function Tt(e,t){return _t.has(t)?!0:t==="vendor"&&Ln.some(r=>An(be(e,r)))}i(Tt,"isNeverWalked");function we(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}i(we,"normalizeFolderPath");function Mn(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{path:t,recursive:!0};if(t&&typeof t=="object"&&typeof t.path=="string")return{path:t.path,recursive:t.recursive!==!1};throw new TypeError(`Invalid includeFolders entry: ${JSON.stringify(t)} (expected a path string or { path, recursive? })`)}):[]}i(Mn,"resolveIncludeFolders");function Ot(e,t){let r=t instanceof Error?t.message:String(t);console.warn(`fix-headers: skipped include folder "${e}" (${r})`)}i(Ot,"reportSkippedIncludeFolder");function Rn(e,t){if(!Array.isArray(t)||t.length===0)return()=>!1;let r=Ee(e),n=[],o=new Set;for(let a of t){if(typeof a!="string")continue;let s=we(a);if(s.length!==0){if(s.includes("/")){n.push(Ee(r,s));continue}o.add(s)}}return(a,s)=>{if(o.has(s))return!0;for(let c of n)if(a===c||a.startsWith(`${c}/`))return!0;let l=we(It(r,a));return n.some(c=>{let u=we(It(r,c));return l===u||l.startsWith(`${u}/`)})}}i(Rn,"buildExclusionMatcher");async function Se(e){let t=Fn(e),r=Mn(e.includeFolders),n=Array.isArray(e.excludeFolders)?e.excludeFolders:[],o=Rn(e.projectRoot,n),a=jt({root:e.projectRoot,gitignore:e.gitignore}),s=i(async(f,h)=>Tt(f,h)||o(f,h)||await a.isIgnored(f,!0),"shouldSkipDirectory"),l=r.length>0?r.map(f=>({includeFolder:f.path,rootPath:be(e.projectRoot,f.path),recursive:f.recursive})):[{includeFolder:".",rootPath:e.projectRoot,recursive:!0}],c=[];for(let f of l){let h=await vn(f.rootPath).catch(S=>S);if(h instanceof Error){if(h.code==="ENOENT"){Ot(f.includeFolder,h);continue}throw h}if(!h.isDirectory()){Ot(f.includeFolder,`path is not a directory: ${f.rootPath}`);continue}let b=await Cn(f.rootPath).catch(()=>Ee(f.rootPath));c.push({...f,realRoot:b})}let u=i((f,h)=>{if(f.realRoot===h.realRoot)return f.recursive||!h.recursive;let b=f.realRoot.endsWith(xe)?f.realRoot:`${f.realRoot}${xe}`;if(!f.recursive||!h.realRoot.startsWith(b))return!1;let S=f.rootPath;for(let N of h.realRoot.slice(b.length).split(xe))if(S=be(S,N),Tt(S,N)||o(S,N))return!1;return!0},"covers"),d=[...c].sort((f,h)=>f.realRoot.length-h.realRoot.length||Number(h.recursive)-Number(f.recursive)),p=[];for(let f of d)p.some(h=>u(h,f))||p.push(f);let g=[];for(let f of c){if(!p.includes(f))continue;let h=await pe(f.rootPath,{allowedExtensions:t,ignoreFolders:_t,shouldSkipDirectory:s,recursive:f.recursive});g.push(...h)}let x=[];for(let f of new Set(g))!o(f,f.split("/").at(-1)||"")&&!await a.isIgnored(f,!1)&&x.push(f);return x}i(Se,"discoverFiles");import{basename as no,dirname as oo,extname as io,resolve as Ae}from"node:path";import{dirname as Xt,isAbsolute as Gn,join as Zt,relative as Wn,resolve as Qt,sep as Vn}from"node:path";import{readFile as jn}from"node:fs/promises";import{join as In}from"node:path";async function Tn(e){try{return await jn(e,"utf8")}catch{return null}}i(Tn,"readManifest");async function D(e,t){let r=[];for(let n of t){let o=await Tn(In(e,n));o!==null&&r.push({file:n,content:o})}return r.length>0?{dir:e,manifest:r[0].file,files:r}:null}i(D,"detectManifests");function P(e,t){return e.files.find(r=>r.file===t)?.content??null}i(P,"manifestContent");function w(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(w,"cleanName");function ke(e){if(typeof e!="string")return;let t=e.search(/[<(]/);return w(t===-1?e:e.slice(0,t))}i(ke,"personName");function ee(e){try{return JSON.parse(e)}catch{return}}i(ee,"parseJsonManifest");function*De(e,t){let r="";for(let n of e.split(/\r?\n/)){let o=n.trim();if(o.startsWith("[")){let a=o.match(/^\[([^[\]]+)\]/);r=a?a[1].split(".").map(s=>s.trim()).join("."):"";continue}r===t&&(yield o)}}i(De,"sectionLines");function B(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*(?:"([^"\\\\]*)"|'([^']*)')`);for(let o of De(e,t)){let a=o.match(n);if(a)return w(a[1]??a[2])}}i(B,"readTomlString");function $e(e,t,r){let n=new RegExp(`^${r}\\s*[=:](.*)$`);for(let o of De(e,t)){let a=o.match(n);if(a)return w(a[1])}}i($e,"readIniValue");function On(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*\\[`),o=null;for(let a of De(e,t)){if(o!==null){o.push(a);continue}let s=a.match(n);s&&(o=[a.slice(s[0].length)])}return o===null?null:o.join(`
|
|
2
|
-
`)}i(
|
|
3
|
-
`,r);r=n===-1?e.length:n+1}else if(/\s/.test(e[r]))r+=1;else break;return r}i(
|
|
4
|
-
`)){let s
|
|
5
|
-
`)[0],[o,
|
|
6
|
-
`)}let n=e.blockStart||(e.kind==="html"?"<!--":"/**"),o=e.blockLinePrefix||(e.kind==="html"?" ":" * "),
|
|
7
|
-
`)}i(
|
|
8
|
-
`).slice(0
|
|
9
|
-
`),
|
|
10
|
-
`.repeat(
|
|
11
|
-
`:`${t}${l}${g}`,"join");if(!o){let{prefix:g,body:x}=
|
|
1
|
+
var _r=Object.defineProperty;var i=(e,t)=>_r(e,"name",{value:t,configurable:!0});import{readFile as Co,stat as vo,writeFile as Fo}from"node:fs/promises";import{relative as Re,resolve as Lr}from"node:path";import{readFile as Ur}from"node:fs/promises";import{createRequire as Br}from"node:module";import{dirname as zr,isAbsolute as Yr,resolve as et}from"node:path";var Gr=3e4,Wr=new Set(["localhost","127.0.0.1","[::1]"]);function se(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(se,"isPlainObject");function ae(e,t){let r={...e};for(let[n,o]of Object.entries(t))n!=="__proto__"&&(r[n]=se(r[n])&&se(o)?ae(r[n],o):o);return r}i(ae,"mergeConfig");function tt(e){return e.kind==="file"?e.path:e.href}i(tt,"describeSource");async function Vr(e){if(e.kind==="file")return{text:await Ur(e.path,"utf8"),source:e};let t;try{t=await fetch(e.href,{cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(Gr)})}catch(r){let n=r.cause instanceof Error?r.cause.message:r.message;throw new Error(`Failed to fetch config ${e.href}: ${n}`,{cause:r})}if(!t.ok)throw new Error(`Failed to fetch config ${e.href}: HTTP ${t.status} ${t.statusText}`);return{text:await t.text(),source:{kind:"url",href:t.url}}}i(Vr,"readSource");function Qe(e){if(e.protocol==="http:"&&!Wr.has(e.hostname))throw new Error(`Refusing to fetch config over plain http: ${e.href} (use https)`);return{kind:"url",href:e.href}}i(Qe,"toUrlSource");function Jr(e,t){if(/^https?:\/\//i.test(e))return Qe(new URL(e));if(/^[a-z][a-z\d+.-]+:\/\//i.test(e))throw new Error(`Unsupported extends URL "${e}" in ${tt(t)}; use https, a file path or a package path`);let r=/^\.{1,2}[\\/]/.test(e);if(t.kind==="url"){if(r||e.startsWith("/"))return Qe(new URL(e,t.href));throw new Error(`Cannot extend package "${e}" from the remote config ${t.href}; use a URL or a relative path`)}if(r||Yr(e))return{kind:"file",path:et(zr(t.path),e)};try{return{kind:"file",path:Br(t.path).resolve(e)}}catch(n){throw new Error(`Cannot resolve extends "${e}" from ${t.path}: ${n.message}`,{cause:n})}}i(Jr,"resolveReference");function qr(e,t){if(e===void 0)return[];let r=Array.isArray(e)?e:[e];if(!r.every(n=>typeof n=="string"&&n.trim().length>0))throw new Error(`Config "extends" must be a string or an array of strings: ${t}`);return r.map(n=>n.trim())}i(qr,"readExtends");async function rt(e,t){let r=tt(e);if(t.includes(r))throw new Error(`Config extends cycle: ${[...t,r].join(" -> ")}`);let{text:n,source:o}=await Vr(e),s;try{s=JSON.parse(n)}catch(u){throw new Error(`Config ${r} is not valid JSON: ${u.message}`,{cause:u})}if(!se(s))throw new Error(`Config file must contain a JSON object: ${r}`);let{extends:a,...l}=s,c={};for(let u of qr(a,r))c=ae(c,await rt(Jr(u,o),[...t,r]));return ae(c,l)}i(rt,"loadSource");function Kr(e,t=process.cwd()){return rt({kind:"file",path:et(t,e)},[])}i(Kr,"loadConfigFile");async function nt(e,t){let r=typeof e[t]=="string"?e[t].trim():"";if(r.length===0)return e;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),o={...await Kr(r,n),...e};return delete o[t],o}i(nt,"applyConfigOption");import{extname as ce}from"node:path";import{extname as Xr}from"node:path";var ot=[".css"];function Zr(e){let t=Xr(e).toLowerCase();return ot.includes(t)?{kind:"block",blockStart:"/*",blockLinePrefix:" * ",blockEnd:" */"}:null}i(Zr,"resolveCssCommentSyntax");var it={id:"css",extensions:ot,enabledByDefault:!0,resolveCommentSyntax(e){return Zr(e)}};import{extname as Qr}from"node:path";var st=[".go"];function en(e){let t=Qr(e).toLowerCase();return st.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(en,"resolveGoCommentSyntax");var at={id:"go",extensions:st,enabledByDefault:!0,resolveCommentSyntax(e){return en(e)}};import{extname as tn}from"node:path";var ct=[".html",".htm"];function rn(e){let t=tn(e).toLowerCase();return ct.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(rn,"resolveHtmlCommentSyntax");var lt={id:"html",extensions:ct,enabledByDefault:!0,resolveCommentSyntax(e){return rn(e)}};import{extname as nn}from"node:path";var ut=[".jsonv",".jsonc",".json5"];function on(e){let t=nn(e).toLowerCase();return ut.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(on,"resolveJsonCommentSyntax");var dt={id:"json",extensions:ut,enabledByDefault:!0,resolveCommentSyntax(e){return on(e)}};import{extname as sn}from"node:path";var ft=[".md",".markdown"];function an(e){let t=sn(e).toLowerCase();return ft.includes(t)?{kind:"html",blockStart:"<!--",blockLinePrefix:" ",blockEnd:"-->"}:null}i(an,"resolveMarkdownCommentSyntax");function cn(e,t){let r=t.match(/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);return r?r[0]:""}i(cn,"resolveMarkdownPreservedPrefix");var mt={id:"markdown",extensions:ft,enabledByDefault:!1,requiresForce:!0,resolvePreservedPrefix(e,t){return cn(e,t)},resolveCommentSyntax(e){return an(e)}};import{extname as ln}from"node:path";var pt=[".js",".mjs",".cjs",".ts",".tsx",".jsx"];function un(e){let t=ln(e).toLowerCase();return pt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(un,"resolveNodeCommentSyntax");function dn(e,t){let r=t.match(/^#!.*\b(node|bun|deno|tsx|ts-node)\b.*(?:\r?\n|$)/);return r?r[0]:""}i(dn,"resolveNodePreservedPrefix");var ht={id:"node",extensions:pt,enabledByDefault:!0,resolvePreservedPrefix(e,t){return dn(e,t)},resolveCommentSyntax(e){return un(e)}};import{extname as fn}from"node:path";var gt=[".php"];function mn(e){let t=fn(e).toLowerCase();return gt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(mn,"resolvePhpCommentSyntax");var yt={id:"php",extensions:gt,enabledByDefault:!0,resolveCommentSyntax(e){return mn(e)}};import{extname as pn}from"node:path";var xt=[".py"];function hn(e,t){let r=t.match(/^#!.*\bpython(?:\d+(?:\.\d+)*)?\b.*(?:\r?\n|$)/);return r?r[0]:""}i(hn,"resolvePythonPreservedPrefix");var wt={id:"python",extensions:xt,enabledByDefault:!0,resolvePreservedPrefix(e,t){return hn(e,t)},resolveCommentSyntax(e){let t=pn(e).toLowerCase();return xt.includes(t)?{kind:"line",linePrefix:"#"}:null}};import{extname as gn}from"node:path";var bt=[".rs"];function yn(e){let t=gn(e).toLowerCase();return bt.includes(t)?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}:null}i(yn,"resolveRustCommentSyntax");var Et={id:"rust",extensions:bt,enabledByDefault:!0,resolveCommentSyntax(e){return yn(e)}};import{extname as xn}from"node:path";var St=[".yaml",".yml"];function wn(e){let t=xn(e).toLowerCase();return St.includes(t)?{kind:"line",linePrefix:"#"}:null}i(wn,"resolveYamlCommentSyntax");var kt={id:"yaml",extensions:St,enabledByDefault:!0,resolveCommentSyntax(e){return wn(e)}};var q=[it,at,lt,dt,mt,ht,yt,wt,Et,kt],bn=new Map(q.map(e=>[e.id,e]));function En(e,t){return!t||typeof t!="object"?e:e.kind==="line"?{...e,linePrefix:typeof t.linePrefix=="string"&&t.linePrefix.length>0?t.linePrefix:e.linePrefix,lineSeparator:typeof t.lineSeparator=="string"?t.lineSeparator:e.lineSeparator}:{...e,blockStart:typeof t.blockStart=="string"&&t.blockStart.length>0?t.blockStart:e.blockStart,blockLinePrefix:typeof t.blockLinePrefix=="string"&&t.blockLinePrefix.length>0?t.blockLinePrefix:e.blockLinePrefix,blockEnd:typeof t.blockEnd=="string"&&t.blockEnd.length>0?t.blockEnd:e.blockEnd}}i(En,"applySyntaxOverride");function Dt(e){if(e==null)return[];if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`forcedDetectors must be an array of detector ids, got ${JSON.stringify(e)}`);let t=q.filter(r=>r.requiresForce===!0).map(r=>r.id);for(let r of e){if(!bn.has(r))throw new Error(`forcedDetectors: unknown detector "${r}" (force-only detectors: ${t.join(", ")})`);if(!t.includes(r))throw new Error(`forcedDetectors: "${r}" does not need forcing (force-only detectors: ${t.join(", ")})`)}return Array.from(new Set(e))}i(Dt,"resolveForcedDetectors");function F(e={}){let t=new Set(Array.isArray(e.enabledDetectors)?e.enabledDetectors:[]),r=new Set(Array.isArray(e.disabledDetectors)?e.disabledDetectors:[]),n=new Set(Array.isArray(e.forcedDetectors)?e.forcedDetectors:[]);return q.filter(o=>o.requiresForce===!0?n.has(o.id)&&!r.has(o.id):t.size>0?t.has(o.id):r.has(o.id)?!1:o.enabledByDefault)}i(F,"getEnabledDetectors");function $t(e={}){if(Array.isArray(e.includeExtensions)&&e.includeExtensions.length>0)return new Set(e.includeExtensions.map(r=>r.toLowerCase()));let t=F(e);return new Set(t.flatMap(r=>r.extensions))}i($t,"getAllowedExtensions");function At(e,t={}){let r=ce(e).toLowerCase();if(F(t).some(a=>a.extensions.includes(r)&&a.resolveCommentSyntax(e)!==null))return null;if(r.length===0)return"the file has no extension, so its comment syntax is unknown";let o=new Set(Array.isArray(t.forcedDetectors)?t.forcedDetectors:[]),s=q.find(a=>a.requiresForce===!0&&a.extensions.includes(r)&&!o.has(a.id));return s?`${r} files get a header only when forced (--force-detector ${s.id} / forcedDetectors: ["${s.id}"])`:`no enabled detector handles ${r} files`}i(At,"getHeaderSkipReason");function Nt(e,t={}){let r=ce(e).toLowerCase(),n=Array.isArray(t.detectors)?t.detectors:F(t);for(let o of n){if(!o.extensions.includes(r))continue;let s=o.resolveCommentSyntax(e);if(s){let a=t.detectorSyntaxOverrides&&typeof t.detectorSyntaxOverrides=="object"?t.detectorSyntaxOverrides:{};return En(s,a[o.id])}}return{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */"}}i(Nt,"getCommentSyntaxForFile");function Ct(e,t,r={}){let n=ce(e).toLowerCase(),o=F(r);for(let s of o)if(s.extensions.includes(n))return typeof s.resolvePreservedPrefix=="function"?s.resolvePreservedPrefix(e,t):"";return""}i(Ct,"getPreservedPrefixForFile");var vt=200,z=1,K=2;function L(e,t,r){if(e==null)return r;if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error(`${t} must be a whole number of 0 or more, got ${JSON.stringify(e)}`);return e}i(L,"resolveLayoutCount");import{existsSync as Pn}from"node:fs";import{join as ge,relative as _t,resolve as ye,sep as pe}from"node:path";import{realpath as Rn,stat as jn}from"node:fs/promises";import{access as Sn,readdir as kn,readFile as Ti,stat as Dn}from"node:fs/promises";import{constants as $n}from"node:fs";import{dirname as _i,join as An,resolve as Ui}from"node:path";async function le(e){try{return await Sn(e,$n.F_OK),!0}catch{return!1}}i(le,"pathExists");async function ue(e,t){let r=[],n=await kn(e,{withFileTypes:!0});for(let o of n){let s=An(e,o.name);if(o.isDirectory()&&t.recursive===!1||o.isDirectory()&&t.ignoreFolders.has(o.name)||o.isDirectory()&&await t.shouldSkipDirectory?.(s,o.name)===!0)continue;if(o.isDirectory()){let c=await ue(s,t);r.push(...c);continue}if(!o.isFile())continue;let a=o.name.lastIndexOf(".");if(a===-1)continue;let l=o.name.slice(a).toLowerCase();t.allowedExtensions.has(l)&&r.push(s)}return r}i(ue,"walkFiles");async function Ft(e){let t=await Dn(e);return{createdAt:t.birthtimeMs>0&&t.birthtime<t.mtime?t.birthtime:t.mtime,updatedAt:t.mtime}}i(Ft,"readFileDates");import{execFile as Nn}from"node:child_process";import{lstat as Cn,readFile as vn}from"node:fs/promises";import{dirname as Lt,isAbsolute as Fn,join as Rt,relative as jt,resolve as de,sep as It}from"node:path";import Ln from"ignore";function Mt(e,t){return new Promise(r=>{Nn("git",t,{cwd:e,encoding:"utf8",maxBuffer:Number.POSITIVE_INFINITY},(n,o)=>{if(!n){r({code:0,stdout:o});return}r({code:typeof n.code=="number"?n.code:-1,stdout:""})})})}i(Mt,"runGitCommand");function me(e,t){return jt(e,t).split(It).join("/")}i(me,"toPosixRelative");async function Tt(e){try{return Ln().add(await vn(e,"utf8"))}catch{return null}}i(Tt,"readIgnoreFile");async function Mn(e){return Cn(Rt(e,".git")).then(()=>!0,()=>!1)}i(Mn,"hasGitEntry");function Pt(e,t,r){for(let n=e.length-1;n>=0;n--){let{base:o,rules:s}=e[n],a=s.test(`${me(o,t)}${r?"/":""}`);if(a.ignored||a.unignored)return a.ignored}return!1}i(Pt,"matchesRules");async function Ot(e,t){let r=await Tt(Rt(e,".gitignore"));return{kind:"rules",nested:!0,excluded:!1,matchers:r?[...t,{base:e,rules:r}]:t}}i(Ot,"buildRulesContext");async function fe(e){let[t,r]=await Promise.all([Mt(e,["check-ignore","-q","."]),Mt(e,["ls-files","--cached","--others","--exclude-standard","-z"])]);if(t.code!==1||r.code!==0)return Ot(e,[]);let n=new Set,o=new Set;for(let s of r.stdout.split("\0")){let a=s.endsWith("/")?s.slice(0,-1):s;if(a.length!==0){n.add(a);for(let l=a.indexOf("/");l!==-1;l=a.indexOf("/",l+1))o.add(a.slice(0,l))}}return{kind:"git",root:e,entries:n,dirs:o}}i(fe,"resolveScopeContext");function Ht(e){let t=de(e.root),r=e.gitignore;if(r===!1)return{isIgnored:i(async()=>!1,"isIgnored")};let n=new Map,o=i(async()=>{if(typeof r!="string"&&!Array.isArray(r))return fe(t);let l=typeof r=="string"?[r]:r.filter(u=>typeof u=="string"),c=[];for(let u of l){let f=await Tt(de(t,u));f&&c.push({base:t,rules:f})}return{kind:"rules",nested:!1,excluded:!1,matchers:c}},"buildRootContext"),s=i(l=>{let c=n.get(l);return c||(c=l===t?o():a(l),n.set(l,c)),c},"contextFor"),a=i(async l=>{let c=await s(Lt(l));return c.kind==="git"?c.entries.has(me(c.root,l))?fe(l):c:!c.nested||c.excluded?c:Pt(c.matchers,l,!0)?{...c,excluded:!0}:await Mn(l)?fe(l):Ot(l,c.matchers)},"deriveContext");return{async isIgnored(l,c){let u=de(l),f=jt(t,u);if(f.length===0||f===".."||f.startsWith(`..${It}`)||Fn(f))return!1;let p=await s(Lt(u));if(p.kind==="git"){let g=me(p.root,u);return!(p.entries.has(g)||c&&p.dirs.has(g))}return p.excluded||Pt(p.matchers,u,c)}}}i(Ht,"createIgnoreFilter");function In(e){return $t(e)}i(In,"resolveExtensions");var Tn=Object.freeze(["node_modules","bower_components","jspm_packages",".pnpm-store",".yarn"]),zt=new Set([".git",...Tn]),On=Object.freeze(["autoload.php","modules.txt"]);function Ut(e,t){return zt.has(t)?!0:t==="vendor"&&On.some(r=>Pn(ge(e,r)))}i(Ut,"isNeverWalked");function he(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}i(he,"normalizeFolderPath");function Hn(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{path:t,recursive:!0};if(t&&typeof t=="object"&&typeof t.path=="string")return{path:t.path,recursive:t.recursive!==!1};throw new TypeError(`Invalid includeFolders entry: ${JSON.stringify(t)} (expected a path string or { path, recursive? })`)}):[]}i(Hn,"resolveIncludeFolders");function Bt(e,t){let r=t instanceof Error?t.message:String(t);console.warn(`fix-headers: skipped include folder "${e}" (${r})`)}i(Bt,"reportSkippedIncludeFolder");function _n(e,t){if(!Array.isArray(t)||t.length===0)return()=>!1;let r=ye(e),n=[],o=new Set;for(let s of t){if(typeof s!="string")continue;let a=he(s);if(a.length!==0){if(a.includes("/")){n.push(ye(r,a));continue}o.add(a)}}return(s,a)=>{if(o.has(a))return!0;for(let c of n)if(s===c||s.startsWith(`${c}/`))return!0;let l=he(_t(r,s));return n.some(c=>{let u=he(_t(r,c));return l===u||l.startsWith(`${u}/`)})}}i(_n,"buildExclusionMatcher");async function xe(e){let t=In(e),r=Hn(e.includeFolders),n=Array.isArray(e.excludeFolders)?e.excludeFolders:[],o=_n(e.projectRoot,n),s=Ht({root:e.projectRoot,gitignore:e.gitignore}),a=i(async(d,h)=>Ut(d,h)||o(d,h)||await s.isIgnored(d,!0),"shouldSkipDirectory"),l=r.length>0?r.map(d=>({includeFolder:d.path,rootPath:ge(e.projectRoot,d.path),recursive:d.recursive})):[{includeFolder:".",rootPath:e.projectRoot,recursive:!0}],c=[];for(let d of l){let h=await jn(d.rootPath).catch(D=>D);if(h instanceof Error){if(h.code==="ENOENT"){Bt(d.includeFolder,h);continue}throw h}if(!h.isDirectory()){Bt(d.includeFolder,`path is not a directory: ${d.rootPath}`);continue}let b=await Rn(d.rootPath).catch(()=>ye(d.rootPath));c.push({...d,realRoot:b})}let u=i((d,h)=>{if(d.realRoot===h.realRoot)return d.recursive||!h.recursive;let b=d.realRoot.endsWith(pe)?d.realRoot:`${d.realRoot}${pe}`;if(!d.recursive||!h.realRoot.startsWith(b))return!1;let D=d.rootPath;for(let N of h.realRoot.slice(b.length).split(pe))if(D=ge(D,N),Ut(D,N)||o(D,N))return!1;return!0},"covers"),f=[...c].sort((d,h)=>d.realRoot.length-h.realRoot.length||Number(h.recursive)-Number(d.recursive)),p=[];for(let d of f)p.some(h=>u(h,d))||p.push(d);let g=[];for(let d of c){if(!p.includes(d))continue;let h=await ue(d.rootPath,{allowedExtensions:t,ignoreFolders:zt,shouldSkipDirectory:a,recursive:d.recursive});g.push(...h)}let x=[];for(let d of new Set(g))!o(d,d.split("/").at(-1)||"")&&!await s.isIgnored(d,!1)&&x.push(d);return x}i(xe,"discoverFiles");import{basename as mo,dirname as po,extname as ho,resolve as De}from"node:path";import{dirname as tr,isAbsolute as Xn,join as rr,relative as Zn,resolve as nr,sep as Qn}from"node:path";import{readFile as Un}from"node:fs/promises";import{join as Bn}from"node:path";async function zn(e){try{return await Un(e,"utf8")}catch{return null}}i(zn,"readManifest");async function $(e,t){let r=[];for(let n of t){let o=await zn(Bn(e,n));o!==null&&r.push({file:n,content:o})}return r.length>0?{dir:e,manifest:r[0].file,files:r}:null}i($,"detectManifests");function M(e,t){return e.files.find(r=>r.file===t)?.content??null}i(M,"manifestContent");function w(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(w,"cleanName");function we(e){if(typeof e!="string")return;let t=e.search(/[<(]/);return w(t===-1?e:e.slice(0,t))}i(we,"personName");function X(e){try{return JSON.parse(e)}catch{return}}i(X,"parseJsonManifest");function*be(e,t){let r="";for(let n of e.split(/\r?\n/)){let o=n.trim();if(o.startsWith("[")){let s=o.match(/^\[([^[\]]+)\]/);r=s?s[1].split(".").map(a=>a.trim()).join("."):"";continue}r===t&&(yield o)}}i(be,"sectionLines");function Y(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*(?:"([^"\\\\]*)"|'([^']*)')`);for(let o of be(e,t)){let s=o.match(n);if(s)return w(s[1]??s[2])}}i(Y,"readTomlString");function Ee(e,t,r){let n=new RegExp(`^${r}\\s*[=:](.*)$`);for(let o of be(e,t)){let s=o.match(n);if(s)return w(s[1])}}i(Ee,"readIniValue");function Yn(e,t,r){let n=new RegExp(`^${r}\\s*=\\s*\\[`),o=null;for(let s of be(e,t)){if(o!==null){o.push(s);continue}let a=s.match(n);a&&(o=[s.slice(a[0].length)])}return o===null?null:o.join(`
|
|
2
|
+
`)}i(Yn,"tomlArrayText");function Gn(e,t){let r=t;for(;r<e.length;)if(e[r]==="#"){let n=e.indexOf(`
|
|
3
|
+
`,r);r=n===-1?e.length:n+1}else if(/\s/.test(e[r]))r+=1;else break;return r}i(Gn,"skipTomlSpace");function G(e,t){let r=Yn(e,t,"authors");if(r===null)return;let n=r.slice(Gn(r,0)),o=n.match(/^(?:"([^"\\\n]*)"|'([^'\n]*)')/);if(o)return we(o[1]??o[2]);let a=n.match(/^\{([^}\n]*)\}/)?.[1].match(/(?:^|,)\s*name\s*=\s*(?:"([^"\\\n]*)"|'([^'\n]*)')/);return a?w(a[1]??a[2]):void 0}i(G,"readTomlAuthor");var Yt=["go.mod"];function Wn(e){let t=e.match(/^\s*module\s+(.+)$/m);if(t)return w(t[1].replace(/\/\/.*$/,"").trim().replace(/^["`](.*)["`]$/,"$1"))}i(Wn,"readModulePath");var Gt={id:"go",languages:["go"],manifests:Yt,detect(e){return $(e,Yt)},read(e){return{name:Wn(e.files[0].content)}}};var Wt=["package.json"];function Vn(e){let t=w(e?.name),r=w(e?.publisher),n=typeof e?.engines?.vscode=="string";return t&&r&&n?`${r}.${t}`:t}i(Vn,"readPublishedName");function Jn(e){if(e!==null&&typeof e=="object"){let t=e;return w(t.company)??w(t.name)}return we(e)}i(Jn,"readAuthorCompany");var Vt={id:"node",languages:["node"],manifests:Wt,detect(e){return $(e,Wt)},read(e){let t=X(e.files[0].content);return{name:Vn(t),company:Jn(t?.author)}}};var Jt=["composer.json"],qt={id:"php",languages:["php"],manifests:Jt,detect(e){return $(e,Jt)},read(e){let t=X(e.files[0].content),r=t?.authors;return{name:w(t?.name),company:Array.isArray(r)?w(r[0]?.name):void 0}}};var Kt=["pyproject.toml","setup.cfg","setup.py"];function Xt(e,t){let r=e.indexOf("setup(");if(r===-1)return;let n=e.slice(r).match(new RegExp(`\\b${t}\\s*=\\s*(["'])([^"'\\n]+)\\1`));return n&&n[2].trim()||void 0}i(Xt,"readSetupPyArgument");function qn(e){let t=M(e,"pyproject.toml"),r=M(e,"setup.cfg"),n=M(e,"setup.py");return(t===null?void 0:Y(t,"project","name")??Y(t,"tool.poetry","name"))??(r===null?void 0:Ee(r,"metadata","name"))??(n===null?void 0:Xt(n,"name"))}i(qn,"readPythonName");function Kn(e){let t=M(e,"pyproject.toml"),r=M(e,"setup.cfg"),n=M(e,"setup.py");return(t===null?void 0:G(t,"project")??G(t,"tool.poetry"))??(r===null?void 0:Ee(r,"metadata","author"))??(n===null?void 0:Xt(n,"author"))}i(Kn,"readPythonCompany");var Zt={id:"python",languages:["python"],manifests:Kt,detect(e){return $(e,Kt)},read(e){return{name:qn(e),company:Kn(e)}}};var Qt=["Cargo.toml"],er={id:"rust",languages:["rust"],manifests:Qt,detect(e){return $(e,Qt)},read(e){let t=e.files[0].content;return{name:Y(t,"package","name"),company:G(t,"package")}}};var eo=[Vt,Zt,qt,er,Gt],or=["name","company"];async function Se(e,t,r){let o=(await Promise.all(t.map(async a=>({driver:a,detection:await a.detect(e)})))).filter(a=>a.detection!==null),s=o.filter(a=>typeof r=="string"&&a.driver.languages.includes(r));return[...s,...o.filter(a=>!s.includes(a))]}i(Se,"claimFolder");function to(e,t){let r=Zn(t,e);return r!==""&&r!==".."&&!r.startsWith(`..${Qn}`)&&!Xn(r)}i(to,"isStrictlyInside");async function ir(e,t={}){let r=Array.isArray(t.drivers)?t.drivers:eo,n=typeof t.scanRoot=="string"?nr(t.scanRoot):null,o=nr(e),s=await Se(o,r,t.language);for(;s.length===0;){if(await le(rr(o,".git")))return{root:o,marker:".git",drivers:[],fields:{},sources:{}};let f=tr(o);if(f===o)return null;o=f,s=await Se(o,r,t.language)}let a={},l={},c=o,u=s;for(;;){for(let{driver:p,detection:g}of u){let x=p.read(g);for(let d of or)a[d]===void 0&&x[d]!==void 0&&(a[d]=x[d],l[d]={driver:p.id,manifest:g.manifest,dir:c})}if(or.every(p=>a[p]!==void 0)||n===null||!to(c,n)||await le(rr(c,".git")))break;c=tr(c),u=await Se(c,r,t.language)}return{root:o,marker:s[0].detection.manifest,drivers:s.map(f=>f.driver.id),fields:a,sources:l}}i(ir,"resolveManifestProject");import{execFile as ro}from"node:child_process";import{basename as no,dirname as oo}from"node:path";import{promisify as io}from"node:util";var ke=io(ro);async function k(e,t){try{let{stdout:r}=await ke("git",t,{cwd:e}),n=r.trim();return n.length>0?n:null}catch{return null}}i(k,"runGit");function sr(e,t){let r=0;for(let n=t-1;n>=0&&e[n]==="\\";n--)r++;return r%2===1}i(sr,"isEscaped");function so(e){let t=e.trim();if(!t.endsWith(")")||sr(t,t.length-1))return t;let r=0;for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(o!=="("&&o!==")"||sr(t,n))&&(r+=o===")"?1:-1,r===0))return t.slice(0,n).trim()}return t}i(so,"stripUidComment");function ao(e){let t=e.trim();if(t.length===0)return{authorName:null,authorEmail:null};let r=t.match(/<([^>\n]+)>\s*$/),n=r?.[1]?.trim()||null,o=(r?t.slice(0,r.index):t).trim();return{authorName:so(o)||o||null,authorEmail:n}}i(ao,"parseSignerUid");async function co(e,t){try{let{stdout:r}=await ke(e,t),n=r.trim();return n.length>0?n:null}catch{return null}}i(co,"runProgram");function lo(e){return e.replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(Number.parseInt(r,16)))}i(lo,"decodeColonField");async function uo(e){let t=await k(e,["config","--get","gpg.format"]);if(t!==null&&t!=="openpgp")return null;let r=await k(e,["config","--get","user.signingkey"]);if(!r)return null;let n=await k(e,["config","--get","gpg.openpgp.program"])||await k(e,["config","--get","gpg.program"])||"gpg",o=await co(n,["--batch","--with-colons","--list-keys",r]);if(!o)return null;for(let s of o.split(`
|
|
4
|
+
`)){let a=s.split(":");if(a[0]==="uid"&&a[1]!=="r"&&a[1]!=="e"&&a[9])return lo(a[9])}return null}i(uo,"readSigningKeyUid");async function ar(e,t={}){let r=await k(e,["config","--get","user.name"]),n=await k(e,["config","--get","user.email"]);if(t.useGpgSignerAuthor===!0){let o=await uo(e)||await k(e,["log","-1","--format=%GS"]),s=ao(o||"");r=s.authorName||r,n=n||s.authorEmail}if(!r||!n){let o=await k(e,["log","-1","--format=%an|%ae"]);if(o){let[s,a]=o.split("|");r=r||s||null,n=n||a||null}}return{authorName:r,authorEmail:n}}i(ar,"detectGitAuthor");function cr(e){return e.replace(/z$/i,"+00:00")}i(cr,"canonicalGitDate");async function lr(e,t){let r=await k(e,["log","--follow","--format=%aI|%at","--reverse","--",t]);if(!r)return null;let n=r.split(`
|
|
5
|
+
`)[0],[o,s]=n.split("|");if(!o||!s)return null;let a=Number.parseInt(s,10);return Number.isNaN(a)?null:{date:cr(o),timestamp:a}}i(lr,"getGitCreationDate");async function ur(e,t){let r=await k(e,["log","-1","--format=%aI|%at","--",t]);if(!r)return null;let[n,o]=r.split("|");if(!n||!o)return null;let s=Number.parseInt(o,10);return Number.isNaN(s)?null:{date:cr(n),timestamp:s}}i(ur,"getGitLastModifiedDate");var fo=256*1024*1024;async function dr(e){let t=oo(e);if(await k(t,["rev-parse","--is-inside-work-tree"])!=="true")return{state:"no-git",content:null};try{let{stdout:r}=await ke("git",["show",`HEAD:./${no(e)}`],{cwd:t,encoding:"utf8",maxBuffer:fo});return{state:"tracked",content:r}}catch{return{state:"untracked",content:null}}}i(dr,"readGitHeadFile");function go(e){return mo(e)||"project"}i(go,"folderName");function yo(e,t){if(typeof t!="string")return e;let r=t.trim();return r.length===0||/<[^>]+>/.test(e)?e:`${e} <${r}>`}i(yo,"formatAuthorNameWithCompany");async function xo(e,t={}){let r=Array.isArray(t.detectors)?t.detectors:F(t),n=typeof t.preferredExtension=="string"?t.preferredExtension.trim().toLowerCase():"",o=n.length>0?r.find(u=>u.extensions.includes(n)):void 0,s=await ir(e,{drivers:t.drivers,language:o?.id,scanRoot:t.scanRoot}),a=s?s.root:De(e),l=s?.sources.name,c=s?.sources.company;return{language:o?.id??s?.drivers[0]??"unknown",rootDir:a,marker:s?s.marker:null,projectName:s?.fields.name??go(a),projectNameSource:l?{from:"manifest",...l}:{from:"folder",dir:a},companyName:s?.fields.company??null,companyNameSource:c?{from:"manifest",...c}:{from:"none"},drivers:s?s.drivers:[]}}i(xo,"detectProjectFromMarkers");async function $e(e={}){let t=e.targetFilePath||e.cwd||process.cwd(),r=De(t),n=F(e),o=e.targetFilePath?po(r):r,s=e.targetFilePath?ho(r).toLowerCase():"",a=De(e.projectRoot||e.cwd||process.cwd()),l=await xo(o,{detectors:n,preferredExtension:s,scanRoot:a}),c=await ar(l.rootDir,{useGpgSignerAuthor:e.useGpgSignerAuthor===!0}),u=e.authorName||c.authorName||"Unknown Author",f=typeof e.companyName=="string"?e.companyName.trim():"";return{projectName:e.projectName||l.projectName,projectNameSource:e.projectName?{from:"option"}:l.projectNameSource,language:e.language||l.language,projectRoot:e.projectRoot||l.rootDir,marker:e.marker===void 0?l.marker:e.marker,authorName:yo(u,e.company),authorEmail:e.authorEmail||c.authorEmail||"unknown@example.com",companyName:f||l.companyName,companyNameSource:f?{from:"option"}:l.companyNameSource,copyrightStartYear:Number.isInteger(e.copyrightStartYear)?Number(e.copyrightStartYear):null}}i($e,"resolveProjectMetadata");function wo(e){return Ae({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),offsetMinutes:-e.getTimezoneOffset()})}i(wo,"formatDateWithTimezone");function Ae(e){return`${hr(e," ")} ${gr(e.offsetMinutes)}`}i(Ae,"formatSpaceDate");function mr(e){if(typeof e!="string")throw new Error(`timezone must be an IANA time zone name string, such as "America/Los_Angeles" or "UTC" (got ${typeof e})`);try{pr(e)}catch(t){throw new Error(`Unknown time zone "${e}": expected an IANA time zone name, such as "America/Los_Angeles" or "UTC"`,{cause:t})}return e}i(mr,"assertTimeZone");var fr=new Map;function pr(e){let t=fr.get(e);return t||(t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),fr.set(e,t)),t}i(pr,"getZoneFormatter");function Ne(e,t){let r={};for(let o of pr(t).formatToParts(new Date(e*1e3)))r[o.type]=Number(o.value);let n=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)/1e3;return{year:r.year,month:r.month,day:r.day,hour:r.hour,minute:r.minute,second:r.second,offsetMinutes:(n-e)/60}}i(Ne,"toZonedDateParts");function hr(e,t){let r=i(n=>String(n).padStart(2,"0"),"pad");return`${String(e.year).padStart(4,"0")}-${r(e.month)}-${r(e.day)}${t}${r(e.hour)}:${r(e.minute)}:${r(e.second)}`}i(hr,"formatWallClock");function gr(e){let t=i(n=>String(n).padStart(2,"0"),"pad"),r=Math.abs(e);return`${e>=0?"+":"-"}${t(Math.floor(r/60))}:${t(r%60)}`}i(gr,"formatOffset");function Z(e=new Date){return{date:wo(e),timestamp:Math.floor(e.getTime()/1e3)}}i(Z,"toDatePayload");var bo=/^(\d{4})-(\d{2})-(\d{2})(?:T|\s+)(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?\s*(?:(Z)|([+-])(\d{2}):?(\d{2}))$/i;function P(e){let t=bo.exec(e.trim());if(!t)return null;let[r,n,o,s,a,l]=t.slice(1,7).map(Number),c=t[7]?0:Number(t[9])*60+Number(t[10]),u=t[8]==="-"?-c:c,f=new Date(Date.UTC(r,n-1,o,s,a,l));return!(f.getUTCFullYear()===r&&f.getUTCMonth()===n-1&&f.getUTCDate()===o&&f.getUTCHours()===s&&f.getUTCMinutes()===a&&f.getUTCSeconds()===l)||Number(t[10]??0)>59?null:{year:r,month:n,day:o,hour:s,minute:a,second:l,offsetMinutes:u,timestamp:Math.floor(f.getTime()/1e3)-u*60}}i(P,"parseHeaderDate");function Ce(e){return`${hr(e,"T")}${gr(e.offsetMinutes)}`}i(Ce,"formatIsoDate");var Eo={"git-created":"git first commit","filesystem-created":"filesystem creation time"};function yr(e,t){let r=e.match(new RegExp(`${t}:[^\\S\\n]*(.*)$`,"m"));return r?r[1].trim():null}i(yr,"readHeaderField");function ve(e){let t=null;for(let{source:r,payload:n}of e)n&&(!t||n.timestamp<t.payload.timestamp)&&(t={source:r,payload:n});return t}i(ve,"pickOldestDate");function wr({existing:e,gitCreated:t,filesystemCreated:r,fixCreatedDate:n=!1}){let o=[{source:"git-created",payload:t},{source:"filesystem-created",payload:r}];if(!e)return ve(o);if(!n)return{source:"existing-header",payload:e};let s=P(e.date)?e:null;return ve([{source:"existing-header",payload:s},...o])}i(wr,"resolveCreatedDate");function br(e,t=null){if(t)return Ne(e.timestamp,t).year;let r=P(e.date);return r?r.year:new Date(e.timestamp*1e3).getFullYear()}i(br,"dateYear");function xr(e,t,r,n){let o=e.match(/^(.+?)\s*\((\d+)\)$/),s=o?P(o[1]):null;if(!o||!s)return n.push({check:`${r}-format`,field:t,advisory:!1,value:e,message:`${t} value "${e}" is not a "<datetime> (<epoch>)" pair with a recognised datetime`}),null;let a=Number.parseInt(o[2],10);return a!==s.timestamp&&n.push({check:`${r}-epoch`,field:t,advisory:!1,value:e,expected:`${o[1]} (${s.timestamp})`,message:`${t} epoch ${a} does not match ${o[1]} (expected ${s.timestamp})`}),{text:o[1],timestamp:s.timestamp}}i(xr,"checkDateValue");function Er(e,t={},r={}){let n=[],o=yr(e,"@Date"),s=o===null?null:xr(o,"@Date","created",n),a=ve([{source:"git-created",payload:t.gitCreated},{source:"filesystem-created",payload:t.filesystemCreated}]);if(s&&a&&s.timestamp>a.payload.timestamp){let f=Eo[a.source];n.push({check:"created-newer-than-source",field:"@Date",advisory:r.strictCreatedDate!==!0,value:o,expected:`${a.payload.date} (${a.payload.timestamp})`,source:a.source,message:`@Date ${s.text} is later than the ${f} ${a.payload.date} (${a.payload.timestamp})`})}let l=yr(e,"@Last modified time"),c=l===null?null:xr(l,"@Last modified time","modified",n),u=t.gitLastModified;return c&&u&&c.timestamp!==u.timestamp&&n.push({check:"modified-git",field:"@Last modified time",advisory:!0,value:l,expected:`${u.date} (${u.timestamp})`,message:`@Last modified time ${c.text} does not match the git last commit ${u.date} (${u.timestamp})`}),n}i(Er,"checkHeaderDates");function Fe(e){if(!e)return null;let t=P(e.date);return t&&t.timestamp!==e.timestamp?{date:e.date,timestamp:t.timestamp}:e}i(Fe,"repairDateEpoch");function Sr(e){let t=P(e.date);return t?{date:Ce(t),timestamp:t.timestamp}:e}i(Sr,"normalizeDatePayload");function kr(e,t){let r=P(e.date);if(!r)return e;let n=Ne(r.timestamp,t);return n.offsetMinutes===r.offsetMinutes||!Number.isInteger(n.offsetMinutes)?e:{date:/^\d{4}-\d{2}-\d{2}T/i.test(e.date.trim())?Ce(n):Ae(n),timestamp:r.timestamp}}i(kr,"convertDatePayload");import{relative as ko}from"node:path";import{extname as So}from"node:path";function W(e,t={}){let r=So(e).toLowerCase(),n=L(t.spacing,"spacing",z);return r.length===0?{kind:"block",blockStart:"/**",blockLinePrefix:" * ",blockEnd:" */",spacing:n}:{...Nt(e,t),spacing:n}}i(W,"getHeaderSyntaxForFile");function Dr(e,t){let r=e.spacing??z;if(e.kind==="line"){let l=e.linePrefix||"#",c=typeof e.lineSeparator=="string"?e.lineSeparator:" ",u=Array.from({length:r},()=>l);return[...u,...t.map(f=>`${l}${c}${f}`),...u].join(`
|
|
6
|
+
`)}let n=e.blockStart||(e.kind==="html"?"<!--":"/**"),o=e.blockLinePrefix||(e.kind==="html"?" ":" * "),s=e.blockEnd||(e.kind==="html"?"-->":" */"),a=Array.from({length:r},()=>o.trimEnd());return[n,...a,...t.map(l=>`${o}${l}`),...a,s].join(`
|
|
7
|
+
`)}i(Dr,"renderHeaderLines");function $r(e){let t=`/${ko(e.projectRoot,e.absoluteFilePath).replace(/\\/g,"/")}`,r=W(e.absoluteFilePath,e.syntaxOptions||{language:e.language}),n=e.createdByName||e.authorName,o=e.createdByEmail||e.authorEmail,s=e.lastModifiedByName||e.authorName,a=e.lastModifiedByEmail||e.authorEmail,l=typeof e.companyName=="string"?e.companyName.trim():"",c=l.length>0?`${l} `:"",u=[`@Project: ${e.projectName}`,`@Filename: ${t}`,`@Date: ${e.createdAt.date} (${e.createdAt.timestamp})`,`@Author: ${n}`,`@Email: <${o}>`,"-----",`@Last modified by: ${s} (${a})`,`@Last modified time: ${e.lastModifiedAt.date} (${e.lastModifiedAt.timestamp})`,"-----",`@Copyright: Copyright (c) ${e.copyrightStartYear}-${e.currentYear} ${c}All rights reserved.`];return Dr(r,u)}i($r,"buildHeader");var Do=Object.freeze(["projectName","filename","createdAt","authorName","authorEmail","lastModifiedByName","lastModifiedByEmail","lastModifiedAt","copyrightStartYear","copyrightEndYear","companyName"]);function C(e,t){let r=e.match(new RegExp(`@${t}:[ \\t]*(.*)$`,"m")),n=r?r[1].trim():"";return n.length>0?n:null}i(C,"readTag");function $o(e){if(e===null)return{name:null,email:null};if(!e.endsWith(")"))return{name:e,email:null};let t=e.slice(0,-1),r=t.indexOf("(",t.lastIndexOf(")")+1);return r===-1?{name:e,email:null}:{name:t.slice(0,r).trimEnd()||null,email:t.slice(r+1)||null}}i($o,"splitLastModifiedBy");function Ao(e){let t={startYear:null,endYear:null,companyName:null},r=e?.match(/^Copyright\s+\(c\)\s+(\d{4})/i);if(!r)return t;let n=e.slice(r[0].length),o=n.match(/^\s*-\s*(\d{4})/);o&&(n=n.slice(o[0].length));let s=n.toLowerCase(),a=s.endsWith("all rights reserved.")?20:s.endsWith("all rights reserved")?19:0;return a===0||!/^\s/.test(n)?t:{startYear:r[1],endYear:o?o[1]:null,companyName:n.slice(0,-a).trim()||null}}i(Ao,"splitCopyright");function Ar(e){let t=$o(C(e,"Last modified by")),r=Ao(C(e,"Copyright")),n=C(e,"Email");return{projectName:C(e,"Project"),filename:C(e,"Filename"),createdAt:C(e,"Date"),authorName:C(e,"Author"),authorEmail:n===null?null:n.replace(/^<(.*)>$/,"$1"),lastModifiedByName:t.name,lastModifiedByEmail:t.email,lastModifiedAt:C(e,"Last modified time"),copyrightStartYear:r.startYear,copyrightEndYear:r.endYear,companyName:r.companyName}}i(Ar,"parseHeaderFields");function Nr(e,t){let r=Ar(e??""),n=Ar(t);return Do.filter(o=>r[o]!==n[o]).map(o=>({field:o,previous:r[o],detected:n[o]}))}i(Nr,"compareHeaderFields");function Q(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(Q,"escapeRegex");function Le(e,t,r={}){let n=Ct(e,t,r);return n.length===0?{prefix:"",body:t}:{prefix:n,body:t.slice(n.length)}}i(Le,"splitPreservedPrefix");function Cr(e,t){if(t.kind==="html"){let n=Q(t.blockStart||"<!--"),o=Q(t.blockEnd||"-->");return e.match(new RegExp(`^${n}[\\s\\S]*?${o}\\n*`))}if(t.kind==="line"){let n=Q(t.linePrefix||"#");return e.match(new RegExp(`^(?:${n}.*\\n)+\\n*`))}let r=Q((t.blockEnd||" */").trim());return e.match(new RegExp(`^/\\*[\\s\\S]*?${r}\\n*`))}i(Cr,"matchHeaderSegment");function ee(e,t="",r={}){let{prefix:n,body:o}=Le(t,e,r),s=o.split(`
|
|
8
|
+
`).slice(0,vt).join(`
|
|
9
|
+
`),a=W(t,r);if(!Cr(s,a))return null;let c=0,u=0;for(;;){let f=s.slice(c),p=Cr(f,a);if(!p||!p[0].includes("@Project:"))break;c+=p[0].length,u=c}return u===0?null:{start:n.length,end:n.length+u}}i(ee,"findProjectHeader");function Me(e,t,r="",n={}){let o=ee(e,r,n),s=L(n.margin,"margin",K),a=W(r,n).kind==="line"?Math.max(1,s):s,l=`
|
|
10
|
+
`.repeat(a+1),c=i(g=>g.trim()===""?`${t}
|
|
11
|
+
`:`${t}${l}${g}`,"join");if(!o){let{prefix:g,body:x}=Le(r,e,n),d=`${g}${c(x.replace(/^\n+/,""))}`;return{nextContent:d,changed:d!==e}}let u=e.slice(0,o.start),f=e.slice(o.end).replace(/^\n+/,""),p=`${u}${c(f)}`;return{nextContent:p,changed:p!==e}}i(Me,"replaceOrInsertHeader");function Pe(e,t="",r={}){let n=ee(e,t,r),{prefix:o,body:s}=n?{prefix:e.slice(0,n.start),body:e.slice(n.end)}:Le(t,e,r),a=s.replace(/^\n+/,"");return`${o}${a.trim()===""?"":a}`}i(Pe,"extractHeaderlessBody");function No(e,t){let r=e.length,n=t.length,o=Array.from({length:r+1},()=>new Array(n+1).fill(0));for(let c=r-1;c>=0;c-=1)for(let u=n-1;u>=0;u-=1)o[c][u]=e[c]===t[u]?o[c+1][u+1]+1:Math.max(o[c+1][u],o[c][u+1]);let s=[],a=0,l=0;for(;a<r&&l<n;)e[a]===t[l]?(s.push({type:" ",line:e[a]}),a+=1,l+=1):o[a+1][l]>=o[a][l+1]?(s.push({type:"-",line:e[a]}),a+=1):(s.push({type:"+",line:t[l]}),l+=1);for(;a<r;a+=1)s.push({type:"-",line:e[a]});for(;l<n;l+=1)s.push({type:"+",line:t[l]});return s}i(No,"diffLines");function vr(e,t){return`${t===0?e:e+1},${t}`}i(vr,"formatRange");function Fr(e,t,r={}){let n=e===null?[]:e.split(`
|
|
12
12
|
`),o=t.split(`
|
|
13
|
-
`),
|
|
14
|
-
`)}i(
|
|
15
|
-
`).length-1;
|
|
13
|
+
`),s=No(n,o),a=Math.max(0,r.context??3),l=r.lineOffset??0,c=[];if(s.forEach((g,x)=>{if(g.type===" ")return;let d=c[c.length-1];d&&x-d.last<=a*2+1?d.last=x:c.push({first:x,last:x})}),c.length===0)return"";let u=r.fromFile??"a",f=r.toFile??"b",p=[`--- ${e===null?"/dev/null":u}`,`+++ ${f}`];for(let g of c){let x=Math.max(0,g.first-a),d=Math.min(s.length,g.last+a+1),h=s.slice(0,x),b=s.slice(x,d),D=h.filter(E=>E.type!=="+").length+l,N=h.filter(E=>E.type!=="-").length+l,R=b.filter(E=>E.type!=="+").length,V=b.filter(E=>E.type!=="-").length;p.push(`@@ -${vr(D,R)} +${vr(N,V)} @@`);for(let E of b)p.push(`${E.type}${E.line}`)}return p.join(`
|
|
14
|
+
`)}i(Fr,"createUnifiedDiff");function Lo(e){return nt(e,"configFile")}i(Lo,"resolveRuntimeOptions");function Mo(e){if(e==null)return[];let t=Array.isArray(e)?e:[e];if(t.some(r=>typeof r!="string"))throw new Error(`input must be a path or an array of paths, got ${JSON.stringify(e)}`);return t.filter(r=>r.trim().length>0)}i(Mo,"resolveInputs");function Po(e){let t=e.match(/@Author:\s*(.+)$/m),r=e.match(/@Email:\s*<([^>\n]+)>/m);return{authorName:t?.[1]?.trim(),authorEmail:r?.[1]?.trim()}}i(Po,"extractHeaderAuthorIdentity");function Ro(e){let t=e.match(/@Last modified by:\s*(.+?)\s*\(([^)\n]+)\)\s*$/m);return{authorName:t?.[1]?.trim(),authorEmail:t?.[2]?.trim()}}i(Ro,"extractHeaderLastModifiedIdentity");function jo(e){let t=e.match(/@Date:\s*(.+?)\s*\((\d+)\)$/m);if(!t||!t[1]||!t[2])return null;let r=Number.parseInt(t[2],10);return Number.isNaN(r)?null:{date:t[1].trim(),timestamp:r}}i(jo,"extractHeaderCreatedAt");function Io(e){let t=e.match(/@Last modified time:\s*(.+?)\s*\((\d+)\)$/m);if(!t||!t[1]||!t[2])return null;let r=Number.parseInt(t[2],10);return Number.isNaN(r)?null:{date:t[1].trim(),timestamp:r}}i(Io,"extractHeaderLastModifiedAt");async function To(e,t,r){let n=await dr(t);return n.state!=="tracked"?{edited:n.state==="untracked",state:n.state}:{edited:Pe(n.content,t,r)!==Pe(e,t,r),state:"tracked"}}i(To,"detectContentEdit");async function Mr(e={}){let t=await Lo(e),r=t.timezone===void 0||t.timezone===null?null:mr(t.timezone),n=t.convertTimezone===!0;if(n&&!r)throw new Error("convertTimezone requires timezone: set timezone (CLI --timezone <name>) to the IANA zone to convert header dates into");let o=Dt(t.forcedDetectors),s=Lr(t.projectRoot||t.cwd||process.cwd()),a=await $e({...t,cwd:s});L(t.spacing,"spacing",z),L(t.margin,"margin",K);let l=t.check===!0,c=l||t.dryRun===!0,u=t.fixCreatedDate===!0,f=i(y=>y,"keepDate"),p=t.normalizeDateFormat===!0?Sr:f,g=r?y=>kr(y,r):f,x=n?g:f,d={language:a.language,enabledDetectors:t.enabledDetectors,disabledDetectors:t.disabledDetectors,forcedDetectors:o,includeFolders:t.includeFolders,excludeFolders:t.excludeFolders,includeExtensions:t.includeExtensions,gitignore:t.gitignore},h=Mo(t.input),b;if(h.length>0){let y=new Set;for(let j of h){let m=Lr(s,j),I=await vo(m).catch(()=>null);if(!I)throw new Error(`Input path does not exist: ${j}`);if(I.isFile())y.add(m);else if(I.isDirectory())for(let v of await xe({...d,projectRoot:m}))y.add(v);else throw new Error(`Input path must be a file or directory: ${j}`)}b=Array.from(y)}else b=await xe({...d,projectRoot:s});let D=new Date().getFullYear(),N=[],R=[],V=new Set,E=0,je=0,Ie=0;for(let y of b){let j=At(y,{enabledDetectors:t.enabledDetectors,disabledDetectors:t.disabledDetectors,forcedDetectors:o});if(j!==null){R.push({file:Re(s,y),reason:j});continue}let m=await $e({...t,cwd:s,targetFilePath:y});V.add(`${m.language}:${m.projectRoot}`);let I=Re(s,y),v=await Co(y,"utf8"),O={language:m.language,enabledDetectors:t.enabledDetectors,disabledDetectors:t.disabledDetectors,forcedDetectors:o,detectorSyntaxOverrides:t.detectorSyntaxOverrides,spacing:t.spacing,margin:t.margin},te=ee(v,y,O),S=te?v.slice(te.start,te.end):"",Te=S.length>0?Po(S):{},Oe=S.length>0?Ro(S):{},Pr=S.length>0?jo(S):null,Rr=S.length>0?Io(S):null,He=await Ft(y),_e=Re(m.projectRoot,y),Ue=await lr(m.projectRoot,_e),H=await ur(m.projectRoot,_e),Be=Z(He.createdAt),re=wr({existing:Fe(Pr),gitCreated:Ue,filesystemCreated:Be,fixCreatedDate:u}),_=Fe(Rr),ze=re.source,jr=_?"existing-header":H?"git-last-modified":"filesystem-updated",ne=p(ze==="existing-header"?x(re.payload):g(re.payload)),Ir=m.copyrightStartYear===null?"created-date":"option",Ye=m.copyrightStartYear??br(ne,r),Ge=p(_?x(_):g(H||Z(He.updatedAt))),We=t.forceAuthorUpdate===!0,Tr=t.forceLastModifiedAuthorUpdate===!0,Ve=await To(v,y,O),Je=Tr||Ve.edited,qe=i(A=>$r({absoluteFilePath:y,language:m.language,syntaxOptions:O,projectRoot:m.projectRoot,projectName:m.projectName,createdByName:We?m.authorName:Te.authorName||m.authorName,createdByEmail:We?m.authorEmail:Te.authorEmail||m.authorEmail,lastModifiedByName:Je?m.authorName:Oe.authorName||m.authorName,lastModifiedByEmail:Je?m.authorEmail:Oe.authorEmail||m.authorEmail,authorName:m.authorName,authorEmail:m.authorEmail,createdAt:ne,lastModifiedAt:A,copyrightStartYear:Ye,companyName:m.companyName,currentYear:D}),"renderHeader"),Ke=qe(Ge),Xe=Me(v,Ke,y,O),Or=Ve.edited&&_!==null&&H!==null&&_.timestamp<H.timestamp,J=Xe.changed||Or,Ze=J?p(g(Z(new Date))):Ge,Hr=J?"current-time-on-change":jr,U=J?qe(Ze):Ke,T=J?Me(v,U,y,O):Xe,oe={file:I,changed:T.changed};if(l){let A=Er(S,{gitCreated:Ue,gitLastModified:H,filesystemCreated:Be},{strictCreatedDate:t.strictCreatedDate===!0}),B=A.filter(ie=>ie.advisory).length;oe.dateIssues=A,Ie+=B,je+=A.length>B?1:0}if(t.sampleOutput===!0&&T.changed){let A=S.length>0?S.trimEnd():null,B=I.replace(/\\/g,"/"),ie=T.nextContent.slice(0,T.nextContent.indexOf(U)).split(`
|
|
15
|
+
`).length-1;oe.sample={previousValue:A,newValue:U,diff:Fr(A,U,{fromFile:`a/${B}`,toFile:`b/${B}`,lineOffset:ie}),issues:Nr(A,U),detectedValues:{projectName:m.projectName,projectNameSource:m.projectNameSource,language:m.language,projectRoot:m.projectRoot,marker:m.marker,authorName:m.authorName,authorEmail:m.authorEmail,companyName:m.companyName,companyNameSource:m.companyNameSource,copyrightStartYear:Ye,copyrightStartYearSource:Ir,createdAtSource:ze,lastModifiedAtSource:Hr,createdAt:ne,lastModifiedAt:Ze}}}N.push(oe),T.changed&&(E+=1,c||await Fo(y,T.nextContent,"utf8"))}return{metadata:a,detectedProjects:Array.from(V),filesScanned:b.length-R.length,filesUpdated:E,filesSkipped:R.length,dryRun:c,check:l,...l?{filesWithDateDrift:je,dateAdvisories:Ie}:{},changes:N,skipped:R}}i(Mr,"fixHeaders");function Oo(e){return Mr(e)}i(Oo,"fixHeaders");var Ca=Oo;export{Ca as default,Oo as fixHeaders};
|
|
16
16
|
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cldmv/fix-headers",
|
|
3
|
-
"version": "2.1
|
|
3
|
+
"version": "2.2.1",
|
|
4
4
|
"description": "Multi-language project header normalizer with auto-detection and override support.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"license": "Apache-2.0",
|
|
87
87
|
"sideEffects": false,
|
|
88
88
|
"devDependencies": {
|
|
89
|
-
"@cldmv/configs": "^1.2.
|
|
89
|
+
"@cldmv/configs": "^1.2.4",
|
|
90
90
|
"@cldmv/eslint-plugin-jsonv": "^1.0.10",
|
|
91
91
|
"@cldmv/jsonv": "^1.0.9",
|
|
92
92
|
"@cldmv/prettier-plugin-jsonv": "^1.0.6",
|
|
@@ -71,11 +71,11 @@ export type DateRewrite = (payload: {
|
|
|
71
71
|
* - `issues` - one `{ field, previous, detected }` entry per header field whose written value
|
|
72
72
|
* differs from the existing header. Values are the field text as written in the header
|
|
73
73
|
* (dates keep their `date (timestamp)` form; `previous` is null when the field was missing).
|
|
74
|
-
* Fields fix-headers preserves - the original `@Author`/`@Email`
|
|
75
|
-
*
|
|
76
|
-
* against what is actually written, so
|
|
77
|
-
*
|
|
78
|
-
* changed file that already had a header.
|
|
74
|
+
* Fields fix-headers preserves - the original `@Author`/`@Email` (unless `forceAuthorUpdate`)
|
|
75
|
+
* and the `@Last modified by` identity (unless the file's content was edited, or
|
|
76
|
+
* `forceLastModifiedAuthorUpdate` is set) - are compared against what is actually written, so
|
|
77
|
+
* they only appear when they really change. Because an updated file gets a fresh
|
|
78
|
+
* `@Last modified time`, `lastModifiedAt` is listed for every changed file that already had a header.
|
|
79
79
|
* - `detectedValues` - the metadata resolved for the file. `projectNameSource` says where
|
|
80
80
|
* `projectName` came from: `{ from: "manifest", driver, manifest, dir }`,
|
|
81
81
|
* `{ from: "folder", dir }` or `{ from: "option" }`. `companyName` is the `@Copyright` holder
|
|
@@ -49,3 +49,28 @@ export function replaceOrInsertHeader(content: string, newHeader: string, filePa
|
|
|
49
49
|
nextContent: string;
|
|
50
50
|
changed: boolean;
|
|
51
51
|
};
|
|
52
|
+
/**
|
|
53
|
+
* Returns a file's content with its project header taken out: the file as it would read
|
|
54
|
+
* with no header at all. Blank lines between the header and the next content, and a body
|
|
55
|
+
* that is only whitespace, are dropped, so two versions of a file that differ only in their
|
|
56
|
+
* header (its fields, framing, spacing or margin, or whether it has one) give the same body.
|
|
57
|
+
* @param {string} content - File content.
|
|
58
|
+
* @param {string} [filePath=""] - File path used for syntax selection.
|
|
59
|
+
* @param {{ language?: string, enabledDetectors?: string[], disabledDetectors?: string[], forcedDetectors?: string[], detectorSyntaxOverrides?: Record<string, { linePrefix?: string, lineSeparator?: string, blockStart?: string, blockLinePrefix?: string, blockEnd?: string }>, spacing?: number, margin?: number }} [syntaxOptions={}] - Syntax resolution options.
|
|
60
|
+
* @returns {string} The content outside the header.
|
|
61
|
+
*/
|
|
62
|
+
export function extractHeaderlessBody(content: string, filePath?: string, syntaxOptions?: {
|
|
63
|
+
language?: string;
|
|
64
|
+
enabledDetectors?: string[];
|
|
65
|
+
disabledDetectors?: string[];
|
|
66
|
+
forcedDetectors?: string[];
|
|
67
|
+
detectorSyntaxOverrides?: Record<string, {
|
|
68
|
+
linePrefix?: string;
|
|
69
|
+
lineSeparator?: string;
|
|
70
|
+
blockStart?: string;
|
|
71
|
+
blockLinePrefix?: string;
|
|
72
|
+
blockEnd?: string;
|
|
73
|
+
}>;
|
|
74
|
+
spacing?: number;
|
|
75
|
+
margin?: number;
|
|
76
|
+
}): string;
|
|
@@ -68,3 +68,20 @@ export function getGitLastModifiedDate(cwd: string, filePath: string): Promise<{
|
|
|
68
68
|
date: string;
|
|
69
69
|
timestamp: number;
|
|
70
70
|
} | null>;
|
|
71
|
+
/**
|
|
72
|
+
* Reads a file as it is at git `HEAD`, from the repository that contains it.
|
|
73
|
+
* @param {string} filePath - Absolute file path.
|
|
74
|
+
* @returns {Promise<{state: "no-git", content: null} | {state: "untracked", content: null} | {state: "tracked", content: string}>}
|
|
75
|
+
* `no-git` when the file is not inside a git work tree, `untracked` when `HEAD` has no such
|
|
76
|
+
* file (a new or ignored file, or a repository with no commits yet), otherwise the content at `HEAD`.
|
|
77
|
+
*/
|
|
78
|
+
export function readGitHeadFile(filePath: string): Promise<{
|
|
79
|
+
state: "no-git";
|
|
80
|
+
content: null;
|
|
81
|
+
} | {
|
|
82
|
+
state: "untracked";
|
|
83
|
+
content: null;
|
|
84
|
+
} | {
|
|
85
|
+
state: "tracked";
|
|
86
|
+
content: string;
|
|
87
|
+
}>;
|