paperlint 18.4.0 → 18.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CLAUDE.md +5 -1
  2. package/dist/adapters/latex/abstract.d.ts +11 -0
  3. package/dist/adapters/latex/abstract.d.ts.map +1 -1
  4. package/dist/adapters/latex/abstract.js +1 -1
  5. package/dist/adapters/latex/abstract.js.map +1 -1
  6. package/dist/adapters/latex/index.d.ts.map +1 -1
  7. package/dist/adapters/latex/index.js +3 -0
  8. package/dist/adapters/latex/index.js.map +1 -1
  9. package/dist/adapters/latex/macros.d.ts +6 -0
  10. package/dist/adapters/latex/macros.d.ts.map +1 -0
  11. package/dist/adapters/latex/macros.js +27 -0
  12. package/dist/adapters/latex/macros.js.map +1 -0
  13. package/dist/adapters/osf/host.io.d.ts +12 -0
  14. package/dist/adapters/osf/host.io.d.ts.map +1 -0
  15. package/dist/adapters/osf/host.io.js +119 -0
  16. package/dist/adapters/osf/host.io.js.map +1 -0
  17. package/dist/adapters/osf/index.d.ts +10 -0
  18. package/dist/adapters/osf/index.d.ts.map +1 -0
  19. package/dist/adapters/osf/index.js +10 -0
  20. package/dist/adapters/osf/index.js.map +1 -0
  21. package/dist/adapters/osf/response.d.ts +11 -0
  22. package/dist/adapters/osf/response.d.ts.map +1 -0
  23. package/dist/adapters/osf/response.js +87 -0
  24. package/dist/adapters/osf/response.js.map +1 -0
  25. package/dist/artifact-upload-rule.d.ts +66 -0
  26. package/dist/artifact-upload-rule.d.ts.map +1 -0
  27. package/dist/artifact-upload-rule.js +151 -0
  28. package/dist/artifact-upload-rule.js.map +1 -0
  29. package/dist/artifact.d.ts +35 -0
  30. package/dist/artifact.d.ts.map +1 -0
  31. package/dist/artifact.js +251 -0
  32. package/dist/artifact.js.map +1 -0
  33. package/dist/cli.d.ts +9 -1
  34. package/dist/cli.d.ts.map +1 -1
  35. package/dist/cli.js +136 -23
  36. package/dist/cli.js.map +1 -1
  37. package/dist/domain/artifact-upload.d.ts +44 -0
  38. package/dist/domain/artifact-upload.d.ts.map +1 -0
  39. package/dist/domain/artifact-upload.js +80 -0
  40. package/dist/domain/artifact-upload.js.map +1 -0
  41. package/dist/domain/paper-dirs.d.ts +16 -0
  42. package/dist/domain/paper-dirs.d.ts.map +1 -0
  43. package/dist/domain/paper-dirs.js +42 -0
  44. package/dist/domain/paper-dirs.js.map +1 -0
  45. package/dist/eslint-rules/CLAUDE.md.spec.d.ts.map +1 -1
  46. package/dist/eslint-rules/CLAUDE.md.spec.js +1 -0
  47. package/dist/eslint-rules/CLAUDE.md.spec.js.map +1 -1
  48. package/dist/paper-files.d.ts +25 -42
  49. package/dist/paper-files.d.ts.map +1 -1
  50. package/dist/paper-files.js +101 -9
  51. package/dist/paper-files.js.map +1 -1
  52. package/dist/ports/artifact-host.d.ts +54 -0
  53. package/dist/ports/artifact-host.d.ts.map +1 -0
  54. package/dist/ports/artifact-host.js +2 -0
  55. package/dist/ports/artifact-host.js.map +1 -0
  56. package/dist/ports/latex.d.ts +9 -0
  57. package/dist/ports/latex.d.ts.map +1 -1
  58. package/dist/submission-confirm-hook.d.ts +11 -1
  59. package/dist/submission-confirm-hook.d.ts.map +1 -1
  60. package/dist/submission-confirm-hook.js +83 -21
  61. package/dist/submission-confirm-hook.js.map +1 -1
  62. package/dist/types.d.ts +6 -0
  63. package/dist/types.d.ts.map +1 -1
  64. package/docs/artifact-upload.md +124 -0
  65. package/docs/optional-rules.md +1 -0
  66. package/docs/osf-artifact.md +4 -1
  67. package/docs/rules/artifact/upload-current.md +85 -0
  68. package/docs/rules.md +1 -0
  69. package/eslint-rules/CLAUDE.md +5 -1
  70. package/eslint-rules/CLAUDE.md.spec.ts +3 -0
  71. package/package.json +1 -1
  72. package/src/adapters/latex/abstract.ts +3 -1
  73. package/src/adapters/latex/index.ts +3 -0
  74. package/src/adapters/latex/macros.test.ts +31 -0
  75. package/src/adapters/latex/macros.ts +43 -0
  76. package/src/adapters/osf/cassette/README.md +20 -0
  77. package/src/adapters/osf/cassette/get-file.json +108 -0
  78. package/src/adapters/osf/cassette/get-listing.json +111 -0
  79. package/src/adapters/osf/cassette/get-missing.json +1 -0
  80. package/src/adapters/osf/cassette/put-new.json +31 -0
  81. package/src/adapters/osf/host.io.ts +156 -0
  82. package/src/adapters/osf/host.test.ts +274 -0
  83. package/src/adapters/osf/index.ts +14 -0
  84. package/src/adapters/osf/response.ts +105 -0
  85. package/src/artifact-upload-rule.test.ts +213 -0
  86. package/src/artifact-upload-rule.ts +213 -0
  87. package/src/artifact.test.ts +504 -0
  88. package/src/artifact.ts +402 -0
  89. package/src/cli.test.ts +271 -1
  90. package/src/cli.ts +168 -23
  91. package/src/domain/artifact-upload.test.ts +80 -0
  92. package/src/domain/artifact-upload.ts +111 -0
  93. package/src/domain/paper-dirs.test.ts +91 -0
  94. package/src/domain/paper-dirs.ts +62 -0
  95. package/src/new-paper.test.ts +8 -2
  96. package/src/paper-files.test.ts +88 -0
  97. package/src/paper-files.ts +98 -9
  98. package/src/paper-settings-commands.test.ts +18 -0
  99. package/src/ports/artifact-host.ts +65 -0
  100. package/src/ports/latex.ts +10 -0
  101. package/src/rule-cases.test.ts +44 -0
  102. package/src/submission-confirm-hook.test.ts +113 -1
  103. package/src/submission-confirm-hook.ts +120 -27
  104. package/src/types.ts +6 -0
@@ -77,7 +77,9 @@ function defDefinition(m: Macro): readonly [string, Definition["body"]][] {
77
77
  }
78
78
 
79
79
  /** `\newcommand` and its kin, read by util-macros. */
80
- function definitionOf(m: Macro): readonly [string, Definition["body"]][] {
80
+ export function definitionOf(
81
+ m: Macro,
82
+ ): readonly [string, Definition["body"]][] {
81
83
  if (DEF_MACROS.has(m.content)) return defDefinition(m);
82
84
  // A \newcommand the parser gave no name has none here either: util-macros answers "".
83
85
  const name = newcommandMatcher(m) ? newcommandMacroToName(m) : "";
@@ -33,6 +33,7 @@ import {
33
33
  import { citeKeysOf, macroTextsOf, registeredNumbersOf } from "./facts.ts";
34
34
  import { captionProse } from "./captions.ts";
35
35
  import { headingsOf } from "./headings.ts";
36
+ import { macroValuesOf, macrosUsedOf } from "./macros.ts";
36
37
  import { documentBodyOf, includesOf } from "./includes.ts";
37
38
  import { outlineOf } from "./outline.ts";
38
39
  import { parseLatex } from "./parse.ts";
@@ -93,4 +94,6 @@ export const latexReader: LatexReader = {
93
94
  citeKeys: (src) => citeKeysOf(parseLatex(src)),
94
95
  registeredNumbers: registeredNumbersOf,
95
96
  macroTexts: macroTextsOf,
97
+ macroValues: macroValuesOf,
98
+ macrosUsed: macrosUsedOf,
96
99
  };
@@ -0,0 +1,31 @@
1
+ import { expect, test } from "vitest";
2
+ import { latexReader } from "./index.ts";
3
+
4
+ const NUMBERS = [
5
+ "\\newcommand{\\nRepos}{63}",
6
+ "\\newcommand*{\\pctPass}{ 41.2\\% }",
7
+ "\\def\\nRuns{7}",
8
+ "\\renewcommand\\nRepos{64}",
9
+ "\\newcommand{\\twice}[1]{#1#1}",
10
+ "% \\newcommand{\\commented}{1}",
11
+ ].join("\n");
12
+
13
+ test("macroValues: each argument-less definition with its body as written, in source order", () => {
14
+ // Guards: \newcommand, \newcommand*, \def and \renewcommand read; one with arguments and one in a comment not.
15
+ expect(latexReader.macroValues(NUMBERS)).toEqual([
16
+ { name: "nRepos", value: "63" },
17
+ { name: "pctPass", value: "41.2\\%" },
18
+ { name: "nRuns", value: "7" },
19
+ { name: "nRepos", value: "64" },
20
+ ]);
21
+ });
22
+
23
+ test("macrosUsed: a name counts where it is used, not where it is defined", () => {
24
+ const src =
25
+ "\\newcommand{\\local}{x}\\newcommand{\\pct}{\\nRuns\\%}\n\\begin{document}\nWe saw \\nRepos{} repos, \\pct.\n% \\pctPass\n\\end{document}\n";
26
+ // Guards: \local is only defined; \nRuns counts through \pct's body; a comment holds no use;
27
+ // the definers and \% are macros too, which no numbers file defines.
28
+ expect([...latexReader.macrosUsed(src)].sort()).toEqual(
29
+ ["%", "nRepos", "nRuns", "newcommand", "pct"].sort(),
30
+ );
31
+ });
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The author's own macros, read off the parse tree for `artifact/upload-current`: the value each
3
+ * argument-less one is defined to (`\newcommand`, `\newcommand*`, `\renewcommand`, `\providecommand`,
4
+ * `\def` and its kin), and the names a source uses. Pure.
5
+ *
6
+ * A value is the definition's body as written (`41.2\%`), not what TeX prints: two definitions that
7
+ * print alike but are written differently are two values. A name defined twice keeps its last value.
8
+ * A use is any occurrence of the name that is not its own definition, wherever it stands (a
9
+ * definition's body included): the name in `\newcommand{\x}` is not a use of `\x`.
10
+ */
11
+ import { printRaw } from "@unified-latex/unified-latex-util-print-raw";
12
+ import { countBy } from "remeda";
13
+ import type { MacroValue } from "../../ports/latex.ts";
14
+ import { definitionOf } from "./abstract.ts";
15
+ import { isNode, visited, type Macro } from "./nodes.ts";
16
+ import { parseLatex } from "./parse.ts";
17
+
18
+ /** Every macro node of the source, in document order. */
19
+ const macrosIn = (src: string): readonly Macro[] =>
20
+ visited(parseLatex(src).root, () => false).flatMap((v) =>
21
+ isNode(v) && v.type === "macro" ? [v] : [],
22
+ );
23
+
24
+ /** Each name `src` defines without arguments, and its body as written, in source order. */
25
+ export const macroValuesOf = (src: string): readonly MacroValue[] =>
26
+ macrosIn(src).flatMap((m) =>
27
+ definitionOf(m).flatMap(([name, body]) =>
28
+ body === null ? [] : [{ name, value: printRaw([...body]).trim() }],
29
+ ),
30
+ );
31
+
32
+ /** The names `src` uses: occurring more often than it defines them. */
33
+ export const macrosUsedOf = (src: string): readonly string[] => {
34
+ const macros = macrosIn(src);
35
+ const seen = countBy(macros, (m) => m.content);
36
+ const defined = countBy(
37
+ macros.flatMap((m) => definitionOf(m).map(([name]) => name)),
38
+ (n) => n,
39
+ );
40
+ return Object.entries(seen).flatMap(([n, c]) =>
41
+ c > (defined[n] ?? 0) ? [n] : [],
42
+ );
43
+ };
@@ -0,0 +1,20 @@
1
+ # OSF cassette
2
+
3
+ Answers to the requests `paperlint artifact upload|show` sends, replayed by `host.test.ts` from a
4
+ local server on 127.0.0.1 and parsed by the adapter's real schemas: no test reaches OSF.
5
+
6
+ Recorded from the live API on 2026-11-21 without a token, from a public project (`curl`, read-only).
7
+ Identifying values are replaced with fakes of the same type — the project's guid (`abcde`), the
8
+ file's id, guid, name, size, dates and hashes (the hashes are those of the 15 bytes
9
+ `artifact bytes\n`, which the tests upload); OSF's keys, value types and statuses are verbatim.
10
+
11
+ | file | request | HTTP | how |
12
+ | ------------------ | ------------------------------------------------------------------------------------------ | ---: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
13
+ | `get-file.json` | `GET https://api.osf.io/v2/files/<id>/` | 200 | recorded |
14
+ | `get-listing.json` | `GET https://api.osf.io/v2/nodes/<guid>/files/osfstorage/?filter[name]=<name>` | 200 | recorded; the file's `guid` is `null`, as OSF answered for it |
15
+ | `get-missing.json` | `GET https://api.osf.io/v2/files/000000000000000000000000/` | 404 | recorded verbatim |
16
+ | `put-new.json` | `PUT https://files.osf.io/v1/resources/<guid>/providers/osfstorage/?kind=file&name=<name>` | 201 | **not recorded** (it needs a token and writes): written from WaterButler's source — `{"data": <entity>}`, `id` = provider + path, `path` = `/<id>`, `extra.hashes` |
17
+
18
+ To re-record the three reads: `curl -sS -g -o <file> '<url>'` against a public project, then fake
19
+ every identifying value. Recording `put-new.json` needs a project of your own and a token with
20
+ `osf.full_write`; replace its values the same way.
@@ -0,0 +1,108 @@
1
+ {
2
+ "data": {
3
+ "id": "0123456789abcdef01234567",
4
+ "type": "files",
5
+ "attributes": {
6
+ "guid": "fgh12",
7
+ "checkout": null,
8
+ "name": "artifact.zip",
9
+ "kind": "file",
10
+ "path": "/0123456789abcdef01234567",
11
+ "size": 15,
12
+ "provider": "osfstorage",
13
+ "materialized_path": "/artifact.zip",
14
+ "last_touched": null,
15
+ "date_modified": "2026-11-01T10:00:00.000000",
16
+ "date_created": "2026-11-01T10:00:00.000000Z",
17
+ "extra": {
18
+ "hashes": {
19
+ "md5": "3f395fbbb68716f38f5ff7fa9d740e3b",
20
+ "sha256": "59bd16dfc39e768f82bb8ec74467e571e80ed284683b586f077dbf1aa2483ecd"
21
+ },
22
+ "downloads": 1
23
+ },
24
+ "tags": [],
25
+ "current_user_can_comment": false,
26
+ "current_version": 1,
27
+ "show_as_unviewed": false
28
+ },
29
+ "relationships": {
30
+ "parent_folder": {
31
+ "links": {
32
+ "related": {
33
+ "href": "https://api.osf.io/v2/files/0123456789abcdef00000000/",
34
+ "meta": {}
35
+ }
36
+ },
37
+ "data": {
38
+ "id": "0123456789abcdef00000000",
39
+ "type": "files"
40
+ }
41
+ },
42
+ "versions": {
43
+ "links": {
44
+ "related": {
45
+ "href": "https://api.osf.io/v2/files/0123456789abcdef01234567/versions/",
46
+ "meta": {}
47
+ }
48
+ }
49
+ },
50
+ "comments": {
51
+ "links": {
52
+ "related": {
53
+ "href": "https://api.osf.io/v2/nodes/abcde/comments/?filter%5Btarget%5D=fgh12",
54
+ "meta": {}
55
+ }
56
+ }
57
+ },
58
+ "node": {
59
+ "links": {
60
+ "related": {
61
+ "href": "https://api.osf.io/v2/nodes/abcde/",
62
+ "meta": {}
63
+ }
64
+ },
65
+ "data": {
66
+ "id": "abcde",
67
+ "type": "nodes"
68
+ }
69
+ },
70
+ "target": {
71
+ "links": {
72
+ "related": {
73
+ "href": "https://api.osf.io/v2/nodes/abcde/",
74
+ "meta": {
75
+ "type": "nodes"
76
+ }
77
+ }
78
+ },
79
+ "data": {
80
+ "type": "nodes",
81
+ "id": "abcde"
82
+ }
83
+ },
84
+ "cedar_metadata_records": {
85
+ "links": {
86
+ "related": {
87
+ "href": "https://api.osf.io/v2/files/0123456789abcdef01234567/cedar_metadata_records/",
88
+ "meta": {}
89
+ }
90
+ }
91
+ }
92
+ },
93
+ "links": {
94
+ "info": "https://api.osf.io/v2/files/0123456789abcdef01234567/",
95
+ "move": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
96
+ "upload": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
97
+ "delete": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
98
+ "download": "https://osf.io/download/fgh12/",
99
+ "render": "https://mfr.osf.io/render?url=https%3A%2F%2Fosf.io%2Fdownload%2Ffgh12%2F%3Fdirect%26mode%3Drender",
100
+ "html": "https://osf.io/abcde/files/osfstorage/0123456789abcdef01234567",
101
+ "self": "https://api.osf.io/v2/files/0123456789abcdef01234567/",
102
+ "iri": "https://osf.io/fgh12"
103
+ }
104
+ },
105
+ "meta": {
106
+ "version": "2.0"
107
+ }
108
+ }
@@ -0,0 +1,111 @@
1
+ {
2
+ "data": [
3
+ {
4
+ "id": "0123456789abcdef01234567",
5
+ "type": "files",
6
+ "attributes": {
7
+ "guid": null,
8
+ "checkout": null,
9
+ "name": "artifact.zip",
10
+ "kind": "file",
11
+ "path": "/0123456789abcdef01234567",
12
+ "size": 15,
13
+ "provider": "osfstorage",
14
+ "materialized_path": "/artifact.zip",
15
+ "last_touched": null,
16
+ "date_modified": "2026-11-01T10:00:00.000000",
17
+ "date_created": "2026-11-01T10:00:00.000000Z",
18
+ "extra": {
19
+ "hashes": {
20
+ "md5": "3f395fbbb68716f38f5ff7fa9d740e3b",
21
+ "sha256": "59bd16dfc39e768f82bb8ec74467e571e80ed284683b586f077dbf1aa2483ecd"
22
+ },
23
+ "downloads": 0
24
+ },
25
+ "tags": [],
26
+ "current_user_can_comment": false,
27
+ "current_version": 1,
28
+ "show_as_unviewed": false
29
+ },
30
+ "relationships": {
31
+ "parent_folder": {
32
+ "links": {
33
+ "related": {
34
+ "href": "https://api.osf.io/v2/files/0123456789abcdef00000000/",
35
+ "meta": {}
36
+ }
37
+ },
38
+ "data": {
39
+ "id": "0123456789abcdef00000000",
40
+ "type": "files"
41
+ }
42
+ },
43
+ "versions": {
44
+ "links": {
45
+ "related": {
46
+ "href": "https://api.osf.io/v2/files/0123456789abcdef01234567/versions/",
47
+ "meta": {}
48
+ }
49
+ }
50
+ },
51
+ "node": {
52
+ "links": {
53
+ "related": {
54
+ "href": "https://api.osf.io/v2/nodes/abcde/",
55
+ "meta": {}
56
+ }
57
+ },
58
+ "data": {
59
+ "id": "abcde",
60
+ "type": "nodes"
61
+ }
62
+ },
63
+ "target": {
64
+ "links": {
65
+ "related": {
66
+ "href": "https://api.osf.io/v2/nodes/abcde/",
67
+ "meta": {
68
+ "type": "nodes"
69
+ }
70
+ }
71
+ },
72
+ "data": {
73
+ "type": "nodes",
74
+ "id": "abcde"
75
+ }
76
+ },
77
+ "cedar_metadata_records": {
78
+ "links": {
79
+ "related": {
80
+ "href": "https://api.osf.io/v2/files/0123456789abcdef01234567/cedar_metadata_records/",
81
+ "meta": {}
82
+ }
83
+ }
84
+ }
85
+ },
86
+ "links": {
87
+ "info": "https://api.osf.io/v2/files/0123456789abcdef01234567/",
88
+ "move": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
89
+ "upload": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
90
+ "delete": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
91
+ "download": "https://osf.io/download/0123456789abcdef01234567/",
92
+ "render": "https://mfr.osf.io/render?url=https%3A%2F%2Fosf.io%2Fdownload%2F0123456789abcdef01234567%2F%3Fdirect%26mode%3Drender",
93
+ "html": "https://osf.io/abcde/files/osfstorage/0123456789abcdef01234567",
94
+ "self": "https://api.osf.io/v2/files/0123456789abcdef01234567/"
95
+ }
96
+ }
97
+ ],
98
+ "links": {
99
+ "first": null,
100
+ "last": null,
101
+ "prev": null,
102
+ "next": null,
103
+ "meta": {
104
+ "total": 1,
105
+ "per_page": 10
106
+ }
107
+ },
108
+ "meta": {
109
+ "version": "2.0"
110
+ }
111
+ }
@@ -0,0 +1 @@
1
+ { "errors": [{ "detail": "Not found." }], "meta": { "version": "2.0" } }
@@ -0,0 +1,31 @@
1
+ {
2
+ "data": {
3
+ "id": "osfstorage/0123456789abcdef01234567",
4
+ "type": "files",
5
+ "attributes": {
6
+ "extra": {
7
+ "guid": null,
8
+ "version": 1,
9
+ "downloads": 0,
10
+ "checkout": null,
11
+ "latestVersionSeen": null,
12
+ "hashes": {
13
+ "md5": "3f395fbbb68716f38f5ff7fa9d740e3b",
14
+ "sha256": "59bd16dfc39e768f82bb8ec74467e571e80ed284683b586f077dbf1aa2483ecd"
15
+ }
16
+ },
17
+ "kind": "file",
18
+ "name": "artifact.zip",
19
+ "path": "/0123456789abcdef01234567",
20
+ "provider": "osfstorage",
21
+ "materialized": "/artifact.zip",
22
+ "size": 15
23
+ },
24
+ "links": {
25
+ "move": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
26
+ "upload": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567?kind=file",
27
+ "delete": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567",
28
+ "download": "https://files.osf.io/v1/resources/abcde/providers/osfstorage/0123456789abcdef01234567"
29
+ }
30
+ }
31
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * OSF as the `ArtifactHost` port, over Node's `fetch`.
3
+ *
4
+ * Read: `GET <api>/files/<id>/` when the record has the file's id; else the project's listing
5
+ * filtered by name, `GET <api>/nodes/<guid>/files/osfstorage/?filter[name]=<file>` (the project's
6
+ * guid is the first segment of the record's `osf.io` url). Both answer `extra.hashes` with `md5` and
7
+ * `sha256` (recorded 2026-11-21, `cassette/`).
8
+ *
9
+ * Upload, through WaterButler (waterbutler.readthedocs.io, "Upload a file"): a new version of a file
10
+ * of the same name at the project's top level, `PUT <files>/resources/<guid>/providers/osfstorage/<id>?kind=file`;
11
+ * else a new file, `PUT <files>/resources/<guid>/providers/osfstorage/?kind=file&name=<name>`. The
12
+ * body is the bytes, not a form. Then the hashes are read back from `GET <api>/files/<id>/`, so the
13
+ * record holds what OSF says it holds, not what was sent.
14
+ *
15
+ * 🔴 THE TOKEN goes in the `Authorization` header and nowhere else: not into a URL, a message, or an
16
+ * error.
17
+ */
18
+ import { err, ok, type Result } from "../../domain/result.ts";
19
+ import { messageOf } from "../../domain/text.ts";
20
+ import type {
21
+ ArtifactHost,
22
+ HostedFile,
23
+ HostFailure,
24
+ Upload,
25
+ Where,
26
+ } from "../../ports/artifact-host.ts";
27
+ import { parseFile, parseListing, parseUploaded } from "./response.ts";
28
+
29
+ /** Where OSF answers: its API and WaterButler, no trailing slash. A test points them at itself. */
30
+ export interface OsfUrls {
31
+ readonly api: string;
32
+ readonly files: string;
33
+ /** The site whose urls name a project: `https://osf.io/<guid>/…`. */
34
+ readonly site: string;
35
+ }
36
+
37
+ export const OSF: OsfUrls = {
38
+ api: "https://api.osf.io/v2",
39
+ files: "https://files.osf.io/v1",
40
+ site: "https://osf.io",
41
+ };
42
+
43
+ const READ_TIMEOUT_MS = 60_000;
44
+ const WRITE_TIMEOUT_MS = 600_000;
45
+
46
+ type Answer = Result<
47
+ { readonly status: number; readonly body: unknown },
48
+ HostFailure
49
+ >;
50
+
51
+ /** One request → HTTP status and parsed JSON body, or why there is neither. */
52
+ async function call(
53
+ url: string,
54
+ token: string | null,
55
+ init: { readonly method: string; readonly body?: Uint8Array },
56
+ ): Promise<Answer> {
57
+ const auth = token === null ? {} : { Authorization: `Bearer ${token}` };
58
+ try {
59
+ const r = await fetch(url, {
60
+ method: init.method,
61
+ ...(init.body === undefined ? {} : { body: new Uint8Array(init.body) }),
62
+ headers: { ...auth, Accept: "application/json" },
63
+ signal: AbortSignal.timeout(
64
+ init.method === "GET" ? READ_TIMEOUT_MS : WRITE_TIMEOUT_MS,
65
+ ),
66
+ });
67
+ const text = await r.text();
68
+ try {
69
+ return { ok: true, value: { status: r.status, body: JSON.parse(text) } };
70
+ } catch {
71
+ return err({
72
+ kind: "malformed",
73
+ detail: `HTTP ${String(r.status)}: the answer is not JSON`,
74
+ });
75
+ }
76
+ } catch (e) {
77
+ return err({ kind: "unreachable", detail: messageOf(e) });
78
+ }
79
+ }
80
+
81
+ /** The project's guid in an `osf.io` url: its first path segment, five letters and digits. */
82
+ const guidOf = (site: string, url: string): string | null =>
83
+ URL.canParse(url) && new URL(url).host === new URL(site).host
84
+ ? (/^\/([a-z0-9]{5})(?:\/|$)/u.exec(new URL(url).pathname)?.[1] ?? null)
85
+ : null;
86
+
87
+ type Found = Promise<Result<HostedFile, HostFailure>>;
88
+
89
+ /** The file OSF holds under `id`. */
90
+ async function fileById(u: OsfUrls, id: string, token: string | null): Found {
91
+ const a = await call(`${u.api}/files/${encodeURIComponent(id)}/`, token, {
92
+ method: "GET",
93
+ });
94
+ return a.ok ? parseFile(a.value.status, a.value.body) : a;
95
+ }
96
+
97
+ /** The file called `name` at the top level of the project `guid`, or null when there is none. */
98
+ async function byName(
99
+ u: OsfUrls,
100
+ guid: string,
101
+ name: string,
102
+ token: string | null,
103
+ ): Promise<Result<HostedFile | null, HostFailure>> {
104
+ const q = new URLSearchParams({ "filter[name]": name });
105
+ const url = `${u.api}/nodes/${guid}/files/osfstorage/?${q.toString()}`;
106
+ const a = await call(url, token, { method: "GET" });
107
+ return a.ok ? parseListing(a.value.status, a.value.body, name) : a;
108
+ }
109
+
110
+ /** The file a record names: by its id, else by its name in the project its url names. */
111
+ async function read(u: OsfUrls, where: Where, token: string | null): Found {
112
+ if (where.id !== null) return fileById(u, where.id, token);
113
+ const guid = guidOf(u.site, where.url);
114
+ if (guid === null)
115
+ return err({
116
+ kind: "not-found",
117
+ detail: `the record has no file id and its url names no ${u.site} project`,
118
+ });
119
+ const f = await byName(u, guid, where.file, token);
120
+ if (!f.ok) return f;
121
+ return f.value === null
122
+ ? err({
123
+ kind: "not-found",
124
+ detail: `the project ${guid} holds no file ${where.file} at its top level`,
125
+ })
126
+ : ok(f.value);
127
+ }
128
+
129
+ /** Put the file: a new version of the one of the same name, else a new file; then read it back. */
130
+ async function upload(u: OsfUrls, up: Upload, token: string): Found {
131
+ const existing = await byName(u, up.target, up.name, token);
132
+ if (!existing.ok) return existing;
133
+ const base = `${u.files}/resources/${up.target}/providers/osfstorage/`;
134
+ const query = new URLSearchParams({ kind: "file", name: up.name });
135
+ const url =
136
+ existing.value === null
137
+ ? `${base}?${query.toString()}`
138
+ : `${base}${existing.value.id}?kind=file`;
139
+ const put = await call(url, token, { method: "PUT", body: up.bytes });
140
+ if (!put.ok) return put;
141
+ const id = parseUploaded(put.value.status, put.value.body);
142
+ return id.ok ? fileById(u, id.value, token) : id;
143
+ }
144
+
145
+ /** OSF at `u`: the project's files read, and a file put there. */
146
+ export const osfHost = (u: OsfUrls = OSF): ArtifactHost => ({
147
+ can: { upload: true, hashes: ["sha256", "md5"] },
148
+ token: {
149
+ variable: "OSF_TOKEN_OSF_IO",
150
+ siteLess: "OSF_TOKEN",
151
+ help: `${u.site}/settings/tokens (Settings → Personal access tokens), scope osf.full_write to upload; osf.full_read is enough for show on a project that is not public`,
152
+ },
153
+ targetOf: (url) => guidOf(u.site, url),
154
+ read: (where, token) => read(u, where, token),
155
+ upload: (up, token) => upload(u, up, token),
156
+ });