@domandigital/sanity-copy 0.2.1 → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # @domandigital/sanity-copy
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3eb1560: CommonJS consumers now get the CommonJS type declarations. The `exports` map put a top-level `types` (the ESM `.d.ts`) ahead of `require`, so TypeScript resolving a `require` under `node16` stopped at the ESM file ("Masquerading as ESM" in @arethetypeswrong/cli). `types` now sits inside `import` and `require` separately. Runtime behaviour is unchanged.
8
+
9
+ Requires Node 22.12 or later (`engines.node`). Node 20 reached end of life on 2026-04-30. Also declares `sideEffects` so bundlers can tree-shake (craft keeps its CSS).
10
+
11
+ - a5868b0: Localised content, hidden fields, and an opt-in publish guard.
12
+
13
+ - `languages` option (e.g. `["en"]`): copy in other languages is skipped. The language comes from an internationalized-array item's `language` field (plugin v5), or from its `_key` (v4); from a field-level translation object whose keys are all two-letter language tags; or from a document's `language` field. `"en"` covers `en-GB` and `en_US`. Unset: unchanged.
14
+ - `withCopyGuard(publishAction)`: opt-in. Publishing stays disabled while the document has a blocking-tier finding, and the finding shows as the tooltip. It returns the Studio's own action type. No Sanity import.
15
+ - `withCopyCheck` never reads fields the schema hides with a static `hidden: true`, inline or through a named object type (new `hiddenPaths` option underneath). `hidden` functions are not evaluated.
16
+ - `language` and `locale` are skipped fields; mixed-case locale tags such as `nb_NO` are no longer read as copy; `assist.instruction.context` (AI Assist instructions) is an excluded type.
17
+ - The Studio validation cache is keyed on the collected copy, so editing a link or a slug no longer re-runs the check.
18
+
19
+ ### Patch Changes
20
+
21
+ - Updated dependencies [e2ea0e8]
22
+ - Updated dependencies [3eb1560]
23
+ - @domandigital/craft@0.11.0
24
+
25
+ ## 0.3.0
26
+
27
+ ### Minor Changes
28
+
29
+ - cd13c94: `sanity-copy --claims` lists every price, figure, date and named source in a dataset, on its field, marked sourced or UNSOURCED, for a person to check against the primary source. `documentClaims(doc)` does the same in code.
30
+
31
+ ### Patch Changes
32
+
33
+ - cd13c94: `withCopyCheck` accepts a real Studio's schema types. Sanity declares its definitions as interfaces, which have no index signature, so the old `SchemaTypeLike` made `tsc` fail in the first Studio it was installed in.
34
+ - Updated dependencies [cd13c94]
35
+ - Updated dependencies [cd13c94]
36
+ - @domandigital/craft@0.10.0
37
+
3
38
  ## 0.2.1
4
39
 
5
40
  ### Patch Changes
package/README.md CHANGED
@@ -11,8 +11,11 @@ belongs.
11
11
 
12
12
  ## In a Studio
13
13
 
14
- Works in any Sanity Studio, v3 or later. Nothing in it is specific to one
15
- site. Two steps:
14
+ Works in any Sanity Studio, v3 or later. It uses only `Rule.custom()`,
15
+ `Rule.warning()` and plain document-action functions, and imports nothing from
16
+ Sanity, so no Studio version is pinned. Its tests run against stand-ins for
17
+ those shapes, not a live Studio. Nothing in it is specific to one site. Two
18
+ steps:
16
19
 
17
20
  1. `pnpm add @domandigital/sanity-copy` (or npm, or yarn) in the Studio's app.
18
21
  2. Wrap the types array in `sanity.config.ts`, as below.
@@ -40,13 +43,53 @@ Options, all optional:
40
43
 
41
44
  | Option | Default | What it does |
42
45
  | --- | --- | --- |
43
- | `excludeTypes` | `testimonial`, `review`, `proofQuote`, `quote` | Never checked. A person's own words are exempt from every house rule. |
44
- | `skipFields` | `slug`, `url`, `href`, `link`, `email`, `phone`, ids, enums | Never read, at any depth. |
46
+ | `excludeTypes` | `testimonial`, `review`, `proofQuote`, `quote`, `assist.instruction.context` | Never checked. A person's own words are exempt from every house rule, and AI Assist instruction documents are prompts, not copy. |
47
+ | `skipFields` | `slug`, `url`, `href`, `link`, `email`, `phone`, `language`, `locale`, ids, enums | Never read, at any depth. |
45
48
  | `review` | `true` | Show the review and density tiers as well as the house rules. |
49
+ | `languages` | every language | Check only these, e.g. `["en"]`. See below. |
50
+ | `hiddenPaths` | from the schema | Dot paths never read. `withCopyCheck` fills this in from every static `hidden: true`. |
46
51
 
47
52
  What is read: strings, Portable Text (a block's spans joined, so a template
48
53
  split across spans is still caught), and the alt text and caption of images.
49
- What is not: slugs, links, references, enum values, asset data.
54
+ What is not: slugs, links, references, enum values, language tags, asset data,
55
+ and fields the schema hides with `hidden: true`. A `hidden` function is not
56
+ evaluated: it is decided per document and per editor, and the check has no way
57
+ to know the answer for a nested field, so those fields are still read.
58
+
59
+ ### Localised content
60
+
61
+ The rules are English. On a localised Studio, pass `languages: ["en"]` so the
62
+ other languages are left alone (`"en"` also covers `en-GB` and `en_US`). Four
63
+ shapes are recognised:
64
+
65
+ | Shape | Example | How the language is found |
66
+ | --- | --- | --- |
67
+ | sanity-plugin-internationalized-array v5 | `[{ _key: "k8f2a", language: "fr", value }]` | the item's `language` field |
68
+ | the same plugin, v4 and earlier | `[{ _key: "fr", value }]` | the item's `_key` |
69
+ | field-level translation | `{ en: "...", fr: "..." }` | the object key, when every key is a two-letter language tag |
70
+ | @sanity/document-internationalization | `{ _type: "page", language: "fr" }` | the document's `language` field |
71
+
72
+ ### Blocking publish (opt-in)
73
+
74
+ Everything above warns. A Studio that wants the house rules enforced can wrap
75
+ the publish action, which then stays disabled while the document has a
76
+ blocking-tier finding, with the finding as its tooltip. The review tier never
77
+ blocks.
78
+
79
+ ```ts
80
+ import { withCopyCheck, withCopyGuard } from "@domandigital/sanity-copy";
81
+
82
+ export default defineConfig({
83
+ schema: { types: withCopyCheck(schemaTypes) },
84
+ document: {
85
+ actions: (prev) => prev.map((a) => (a.action === "publish" ? withCopyGuard(a) : a)),
86
+ },
87
+ });
88
+ ```
89
+
90
+ The original action is always called, so its behaviour is unchanged apart from
91
+ `disabled` and the tooltip. Excluded types (testimonials and the rest) are never
92
+ blocked.
50
93
 
51
94
  ## Sweeping a whole dataset
52
95
 
@@ -60,6 +103,19 @@ Findings are listed per document and field. Exit **0** no house-rule finding,
60
103
  **1** at least one, **2** nothing was checked. A token is read from the
61
104
  environment, never a flag. It reports and changes nothing.
62
105
 
106
+ ## The claims list
107
+
108
+ ```bash
109
+ npx @domandigital/sanity-copy --project <id> --claims
110
+ ```
111
+
112
+ No style rule can say whether a figure is true. `--claims` lists every
113
+ sentence holding a price, a figure, a date or a named source, on its field,
114
+ marked `sourced` (a source is named, in the sentence or a footnote) or
115
+ `UNSOURCED`. Check each against its primary source, then source it, correct it
116
+ or cut it. It always exits 0: a checklist, not a verdict. `documentClaims(doc)`
117
+ does the same in code.
118
+
63
119
  ## In code
64
120
 
65
121
  ```ts
package/dist/cli.js CHANGED
@@ -4,8 +4,8 @@
4
4
  import { readFileSync } from "fs";
5
5
 
6
6
  // src/core.ts
7
- import { applyHouseGate, checkCopy } from "@domandigital/craft";
8
- var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
7
+ import { applyHouseGate, checkCopy, findClaims } from "@domandigital/craft";
8
+ var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote", "assist.instruction.context"];
9
9
  var DEFAULT_SKIP_FIELDS = [
10
10
  "slug",
11
11
  "url",
@@ -29,17 +29,35 @@ var DEFAULT_SKIP_FIELDS = [
29
29
  "script",
30
30
  "schema",
31
31
  "jsonLd",
32
- "canonical"
32
+ "canonical",
33
+ "language",
34
+ "locale"
33
35
  ];
34
36
  var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
35
37
  var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
36
38
  var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
37
39
  var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
40
+ var LANGUAGE_TAG = /^[a-z]{2,3}(?:[_-][A-Za-z]{2,4})?$/;
41
+ var LANGUAGE_KEY = /^[a-z]{2}(?:[_-][A-Za-z]{2,4})?$/;
42
+ function languageWanted(tag, wanted) {
43
+ const t = tag.toLowerCase().replace(/_/g, "-");
44
+ return wanted.some((w) => {
45
+ const base = w.toLowerCase().replace(/_/g, "-");
46
+ return t === base || t.startsWith(`${base}-`);
47
+ });
48
+ }
49
+ function itemLanguage(item) {
50
+ if (typeof item.language === "string") return item.language;
51
+ const keyed = typeof item._type === "string" && item._type.startsWith("internationalizedArray") || "value" in item;
52
+ if (keyed && typeof item._key === "string" && LANGUAGE_TAG.test(item._key)) return item._key;
53
+ return void 0;
54
+ }
38
55
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
39
56
  function notCopy(text) {
40
57
  const t = text.trim();
41
58
  if (!t) return true;
42
59
  if (/^[a-z0-9_-]+$/.test(t)) return true;
60
+ if (LANGUAGE_TAG.test(t)) return true;
43
61
  if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
44
62
  if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
45
63
  if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
@@ -58,7 +76,13 @@ function blockText(block) {
58
76
  var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
59
77
  function collectCopy(doc, options = {}) {
60
78
  const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
79
+ const hidden = new Set(options.hiddenPaths ?? []);
80
+ const languages = options.languages;
61
81
  const pieces = [];
82
+ if (languages && isRecord(doc) && typeof doc.language === "string" && !languageWanted(doc.language, languages)) {
83
+ return pieces;
84
+ }
85
+ const fieldPath = (path) => path.every((s) => typeof s === "string") ? path.join(".") : void 0;
62
86
  const walk = (value, path) => {
63
87
  if (typeof value === "string") {
64
88
  if (!notCopy(value)) pieces.push({ path, text: value });
@@ -66,6 +90,10 @@ function collectCopy(doc, options = {}) {
66
90
  }
67
91
  if (Array.isArray(value)) {
68
92
  value.forEach((item, i) => {
93
+ if (languages && isRecord(item)) {
94
+ const language = itemLanguage(item);
95
+ if (language && !languageWanted(language, languages)) return;
96
+ }
69
97
  if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
70
98
  const text = blockText(item);
71
99
  if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
@@ -78,9 +106,15 @@ function collectCopy(doc, options = {}) {
78
106
  if (!isRecord(value)) return;
79
107
  if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
80
108
  const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
109
+ const fields = Object.keys(value).filter((k) => !k.startsWith("_"));
110
+ const localeMap = languages !== void 0 && fields.length > 0 && fields.every((k) => LANGUAGE_KEY.test(k)) && fields.some((k) => languageWanted(k, languages));
81
111
  for (const [key, child] of Object.entries(value)) {
82
112
  if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
83
- walk(child, [...path, key]);
113
+ if (localeMap && !languageWanted(key, languages)) continue;
114
+ const childPath = [...path, key];
115
+ const dotted = fieldPath(childPath);
116
+ if (dotted !== void 0 && hidden.has(dotted)) continue;
117
+ walk(child, childPath);
84
118
  }
85
119
  };
86
120
  walk(doc, []);
@@ -113,6 +147,17 @@ function checkDocumentCopy(doc, options = {}) {
113
147
  }
114
148
  return findings;
115
149
  }
150
+ function documentClaims(doc, options = {}) {
151
+ if (!isRecord(doc)) return [];
152
+ const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
153
+ if (typeof doc._type === "string" && excluded.has(doc._type)) return [];
154
+ const pieces = collectCopy(doc, options);
155
+ const { claims } = findClaims(pieces.map((p, i) => ({ path: fileFor(i), text: p.text })));
156
+ return claims.flatMap(({ path, line: _line, ...claim }) => {
157
+ const piece = pieces[Number(/^field-(\d+)\.md$/.exec(path)?.[1])];
158
+ return piece ? [{ ...claim, path: piece.path }] : [];
159
+ });
160
+ }
116
161
  function describeFinding(f) {
117
162
  const lead = f.tier === "block" ? "House rule" : "Worth a look";
118
163
  return `${lead} (${f.name}): ${f.message}. ${f.fix}`;
@@ -123,7 +168,7 @@ function pathToString(path) {
123
168
 
124
169
  // src/cli.ts
125
170
  function parse(argv) {
126
- const args = { dataset: "production", json: false };
171
+ const args = { dataset: "production", json: false, claims: false };
127
172
  for (let i = 0; i < argv.length; i += 1) {
128
173
  const a = argv[i];
129
174
  const value = () => {
@@ -136,6 +181,7 @@ function parse(argv) {
136
181
  else if (a === "--types") args.types = value().split(",").map((t) => t.trim()).filter(Boolean);
137
182
  else if (a === "--file") args.file = value();
138
183
  else if (a === "--json") args.json = true;
184
+ else if (a === "--claims") args.claims = true;
139
185
  else if (a === "--help" || a === "-h") return "help";
140
186
  else return `unknown option ${a}`;
141
187
  }
@@ -171,7 +217,9 @@ var label = (doc) => {
171
217
  async function main(argv, out = console.log, err = console.error) {
172
218
  const args = parse(argv);
173
219
  if (args === "help") {
174
- out("usage: sanity-copy --project <id> [--dataset production] [--types a,b] [--json]\n sanity-copy --file export.json [--json]");
220
+ out(
221
+ "usage: sanity-copy --project <id> [--dataset production] [--types a,b] [--claims] [--json]\n sanity-copy --file export.json [--claims] [--json]\n--claims lists every price, figure, date and named source, sourced or UNSOURCED, to check by hand."
222
+ );
175
223
  return 0;
176
224
  }
177
225
  if (typeof args === "string") {
@@ -189,6 +237,7 @@ async function main(argv, out = console.log, err = console.error) {
189
237
  err("sanity-copy: the dataset returned 0 documents. Nothing was checked.");
190
238
  return 2;
191
239
  }
240
+ if (args.claims) return reportClaims(docs, args.json, out);
192
241
  const results = [];
193
242
  for (const doc of docs) {
194
243
  const findings = checkDocumentCopy(doc);
@@ -209,6 +258,35 @@ sanity-copy: ${docs.length} documents, ${block} house-rule finding${block === 1
209
258
  }
210
259
  return block > 0 ? 1 : 0;
211
260
  }
261
+ function reportClaims(docs, json, out) {
262
+ const results = [];
263
+ for (const doc of docs) {
264
+ const claims = documentClaims(doc);
265
+ if (claims.length) results.push({ doc: label(doc), claims });
266
+ }
267
+ const all = results.flatMap((r) => r.claims);
268
+ const unsourced = all.filter((c) => c.sources.length === 0).length;
269
+ if (json) {
270
+ out(JSON.stringify({ documents: docs.length, claims: all.length, unsourced, results }, null, 2));
271
+ return 0;
272
+ }
273
+ for (const r of results) {
274
+ out(r.doc);
275
+ for (const c of r.claims) {
276
+ const what = [
277
+ ...c.facts.map((f) => f.value),
278
+ ...c.sources.map((s) => `source: ${s}`),
279
+ ...c.nearby ? [`${c.nearby.join(", ")} named earlier in the paragraph: does it cover this?`] : []
280
+ ].join(" \xB7 ");
281
+ out(` ${pathToString(c.path)} ${c.sources.length ? "sourced " : "UNSOURCED"} ${what}`);
282
+ out(` ${c.sentence}`);
283
+ }
284
+ }
285
+ out(`
286
+ sanity-copy --claims: ${docs.length} documents, ${all.length} claim${all.length === 1 ? "" : "s"} to check, ${unsourced} with no source named.`);
287
+ out("Check each against its primary source. Sourced means a source is named, not that it agrees.");
288
+ return 0;
289
+ }
212
290
  var invoked = process.argv[1] ?? "";
213
291
  if (/sanity-copy|cli\.(?:c?js|ts)$/.test(invoked)) {
214
292
  main(process.argv.slice(2)).then((code) => process.exit(code));
package/dist/index.cjs CHANGED
@@ -26,14 +26,16 @@ __export(index_exports, {
26
26
  collectCopy: () => collectCopy,
27
27
  copyCheckRule: () => copyCheckRule,
28
28
  describeFinding: () => describeFinding,
29
+ documentClaims: () => documentClaims,
29
30
  pathToString: () => pathToString,
30
- withCopyCheck: () => withCopyCheck
31
+ withCopyCheck: () => withCopyCheck,
32
+ withCopyGuard: () => withCopyGuard
31
33
  });
32
34
  module.exports = __toCommonJS(index_exports);
33
35
 
34
36
  // src/core.ts
35
37
  var import_craft = require("@domandigital/craft");
36
- var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
38
+ var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote", "assist.instruction.context"];
37
39
  var DEFAULT_SKIP_FIELDS = [
38
40
  "slug",
39
41
  "url",
@@ -57,17 +59,35 @@ var DEFAULT_SKIP_FIELDS = [
57
59
  "script",
58
60
  "schema",
59
61
  "jsonLd",
60
- "canonical"
62
+ "canonical",
63
+ "language",
64
+ "locale"
61
65
  ];
62
66
  var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
63
67
  var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
64
68
  var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
65
69
  var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
70
+ var LANGUAGE_TAG = /^[a-z]{2,3}(?:[_-][A-Za-z]{2,4})?$/;
71
+ var LANGUAGE_KEY = /^[a-z]{2}(?:[_-][A-Za-z]{2,4})?$/;
72
+ function languageWanted(tag, wanted) {
73
+ const t = tag.toLowerCase().replace(/_/g, "-");
74
+ return wanted.some((w) => {
75
+ const base = w.toLowerCase().replace(/_/g, "-");
76
+ return t === base || t.startsWith(`${base}-`);
77
+ });
78
+ }
79
+ function itemLanguage(item) {
80
+ if (typeof item.language === "string") return item.language;
81
+ const keyed = typeof item._type === "string" && item._type.startsWith("internationalizedArray") || "value" in item;
82
+ if (keyed && typeof item._key === "string" && LANGUAGE_TAG.test(item._key)) return item._key;
83
+ return void 0;
84
+ }
66
85
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
67
86
  function notCopy(text) {
68
87
  const t = text.trim();
69
88
  if (!t) return true;
70
89
  if (/^[a-z0-9_-]+$/.test(t)) return true;
90
+ if (LANGUAGE_TAG.test(t)) return true;
71
91
  if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
72
92
  if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
73
93
  if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
@@ -86,7 +106,13 @@ function blockText(block) {
86
106
  var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
87
107
  function collectCopy(doc, options = {}) {
88
108
  const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
109
+ const hidden = new Set(options.hiddenPaths ?? []);
110
+ const languages = options.languages;
89
111
  const pieces = [];
112
+ if (languages && isRecord(doc) && typeof doc.language === "string" && !languageWanted(doc.language, languages)) {
113
+ return pieces;
114
+ }
115
+ const fieldPath = (path) => path.every((s) => typeof s === "string") ? path.join(".") : void 0;
90
116
  const walk = (value, path) => {
91
117
  if (typeof value === "string") {
92
118
  if (!notCopy(value)) pieces.push({ path, text: value });
@@ -94,6 +120,10 @@ function collectCopy(doc, options = {}) {
94
120
  }
95
121
  if (Array.isArray(value)) {
96
122
  value.forEach((item, i) => {
123
+ if (languages && isRecord(item)) {
124
+ const language = itemLanguage(item);
125
+ if (language && !languageWanted(language, languages)) return;
126
+ }
97
127
  if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
98
128
  const text = blockText(item);
99
129
  if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
@@ -106,9 +136,15 @@ function collectCopy(doc, options = {}) {
106
136
  if (!isRecord(value)) return;
107
137
  if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
108
138
  const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
139
+ const fields = Object.keys(value).filter((k) => !k.startsWith("_"));
140
+ const localeMap = languages !== void 0 && fields.length > 0 && fields.every((k) => LANGUAGE_KEY.test(k)) && fields.some((k) => languageWanted(k, languages));
109
141
  for (const [key, child] of Object.entries(value)) {
110
142
  if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
111
- walk(child, [...path, key]);
143
+ if (localeMap && !languageWanted(key, languages)) continue;
144
+ const childPath = [...path, key];
145
+ const dotted = fieldPath(childPath);
146
+ if (dotted !== void 0 && hidden.has(dotted)) continue;
147
+ walk(child, childPath);
112
148
  }
113
149
  };
114
150
  walk(doc, []);
@@ -141,6 +177,17 @@ function checkDocumentCopy(doc, options = {}) {
141
177
  }
142
178
  return findings;
143
179
  }
180
+ function documentClaims(doc, options = {}) {
181
+ if (!isRecord(doc)) return [];
182
+ const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
183
+ if (typeof doc._type === "string" && excluded.has(doc._type)) return [];
184
+ const pieces = collectCopy(doc, options);
185
+ const { claims } = (0, import_craft.findClaims)(pieces.map((p, i) => ({ path: fileFor(i), text: p.text })));
186
+ return claims.flatMap(({ path, line: _line, ...claim }) => {
187
+ const piece = pieces[Number(/^field-(\d+)\.md$/.exec(path)?.[1])];
188
+ return piece ? [{ ...claim, path: piece.path }] : [];
189
+ });
190
+ }
144
191
  function describeFinding(f) {
145
192
  const lead = f.tier === "block" ? "House rule" : "Worth a look";
146
193
  return `${lead} (${f.name}): ${f.message}. ${f.fix}`;
@@ -151,10 +198,11 @@ function pathToString(path) {
151
198
 
152
199
  // src/schema.ts
153
200
  function copyCheckRule(rule, options = {}) {
154
- let lastInput = "";
201
+ let lastInput;
155
202
  let lastResult = true;
156
203
  return rule.custom((doc) => {
157
- const input = JSON.stringify(doc ?? null);
204
+ const type = doc !== null && typeof doc === "object" ? doc._type : void 0;
205
+ const input = JSON.stringify([type, collectCopy(doc, options)]);
158
206
  if (input === lastInput) return lastResult;
159
207
  lastInput = input;
160
208
  const findings = checkDocumentCopy(doc, options);
@@ -162,19 +210,60 @@ function copyCheckRule(rule, options = {}) {
162
210
  return lastResult;
163
211
  }).warning();
164
212
  }
213
+ function staticHiddenPaths(type, byName, prefix = "", seen = /* @__PURE__ */ new Set()) {
214
+ const own = Array.isArray(type.fields) ? type.fields : void 0;
215
+ const named = typeof type.type === "string" ? byName.get(type.type) : void 0;
216
+ const fields = own ?? (named && Array.isArray(named.fields) ? named.fields : []);
217
+ if (!own && named && typeof type.type === "string") {
218
+ if (seen.has(type.type)) return [];
219
+ seen = new Set(seen).add(type.type);
220
+ }
221
+ const paths = [];
222
+ for (const field of fields) {
223
+ if (typeof field?.name !== "string") continue;
224
+ const path = prefix ? `${prefix}.${field.name}` : field.name;
225
+ if (field.hidden === true) paths.push(path);
226
+ else paths.push(...staticHiddenPaths(field, byName, path, seen));
227
+ }
228
+ return paths;
229
+ }
165
230
  var asArray = (v) => v === void 0 || v === null ? [] : Array.isArray(v) ? v : [v];
166
231
  function withCopyCheck(types, options = {}) {
167
232
  const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
233
+ const byName = new Map(types.map((t) => [t.name, t]));
168
234
  return types.map((t) => {
169
235
  if (t.type !== "document" || excluded.has(t.name)) return t;
236
+ const hiddenPaths = [...options.hiddenPaths ?? [], ...staticHiddenPaths({ fields: t.fields }, byName)];
237
+ const typeOptions = hiddenPaths.length > 0 ? { ...options, hiddenPaths } : options;
170
238
  const existing = t.validation;
171
239
  const validation = (rule, context) => [
172
240
  ...asArray(typeof existing === "function" ? existing(rule, context) : existing),
173
- copyCheckRule(rule, options)
241
+ copyCheckRule(rule, typeOptions)
174
242
  ];
175
243
  return { ...t, validation };
176
244
  });
177
245
  }
246
+ function withCopyGuard(action, options = {}) {
247
+ let lastDoc;
248
+ let lastBlocking = [];
249
+ const call = action;
250
+ const guarded = (props) => {
251
+ const result = call(props);
252
+ if (!result) return result;
253
+ const doc = props.draft ?? props.published;
254
+ if (doc !== lastDoc) {
255
+ lastDoc = doc;
256
+ lastBlocking = checkDocumentCopy(doc, { ...options, review: false }).filter((f) => f.tier === "block");
257
+ }
258
+ if (lastBlocking.length === 0) return result;
259
+ const more = lastBlocking.length > 1 ? ` (and ${lastBlocking.length - 1} more)` : "";
260
+ return { ...result, disabled: true, title: `${describeFinding(lastBlocking[0])}${more}` };
261
+ };
262
+ const tagged = guarded;
263
+ if (action.action !== void 0) tagged.action = action.action;
264
+ tagged.displayName = `withCopyGuard(${action.displayName ?? "action"})`;
265
+ return tagged;
266
+ }
178
267
  // Annotate the CommonJS export names for ESM import in node:
179
268
  0 && (module.exports = {
180
269
  DEFAULT_EXCLUDED_TYPES,
@@ -183,6 +272,8 @@ function withCopyCheck(types, options = {}) {
183
272
  collectCopy,
184
273
  copyCheckRule,
185
274
  describeFinding,
275
+ documentClaims,
186
276
  pathToString,
187
- withCopyCheck
277
+ withCopyCheck,
278
+ withCopyGuard
188
279
  });
package/dist/index.d.cts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Claim } from '@domandigital/craft';
2
+
1
3
  /**
2
4
  * The house copy check over a Sanity document.
3
5
  *
@@ -6,6 +8,7 @@
6
8
  * the same answer in all three. The rules are craft's: this file only decides
7
9
  * which strings in a document are copy, and where each finding belongs.
8
10
  */
11
+
9
12
  /** A Studio path: field names, array indices, or `{ _key }` for keyed array items. */
10
13
  type PathSegment = string | number | {
11
14
  _key: string;
@@ -37,6 +40,30 @@ interface CopyCheckOptions {
37
40
  * Studio shows every finding as a warning and blocks nothing either way.
38
41
  */
39
42
  review?: boolean;
43
+ /**
44
+ * Check only these languages, e.g. `["en"]`. The rules are English, so on
45
+ * a French field they are noise. `"en"` also matches `en-GB` and `en_US`.
46
+ * When set, copy is skipped when it sits:
47
+ *
48
+ * - in an array item whose `language` field is another language
49
+ * (sanity-plugin-internationalized-array v5), or whose `_key` is
50
+ * (v4 and earlier: an `internationalizedArray*` item, or one with a
51
+ * `value` field);
52
+ * - under an object key that is another language, in an object whose keys
53
+ * are all two-letter language tags (field-level translation, e.g.
54
+ * `{ en, fr }` or `{ en_GB, nb_NO }`);
55
+ * - in a document whose own `language` field is another language
56
+ * (@sanity/document-internationalization).
57
+ *
58
+ * Unset: every language is checked, as before.
59
+ */
60
+ languages?: string[];
61
+ /**
62
+ * Dot paths of fields an editor never sees (`hidden: true` in the schema),
63
+ * e.g. `["seo.internalNotes"]`. Never read. `withCopyCheck` fills this in
64
+ * from the schema; pass it yourself only when calling the check directly.
65
+ */
66
+ hiddenPaths?: string[];
40
67
  }
41
68
  declare const DEFAULT_EXCLUDED_TYPES: string[];
42
69
  declare const DEFAULT_SKIP_FIELDS: string[];
@@ -48,6 +75,17 @@ interface Piece {
48
75
  declare function collectCopy(doc: unknown, options?: CopyCheckOptions): Piece[];
49
76
  /** Check one document. Returns nothing for an excluded type. */
50
77
  declare function checkDocumentCopy(doc: unknown, options?: CopyCheckOptions): CopyFinding[];
78
+ interface DocumentClaim extends Omit<Claim, "path" | "line"> {
79
+ /** The field the sentence is in. */
80
+ path: Path;
81
+ }
82
+ /**
83
+ * Every sentence in a document holding a price, figure, date or named source,
84
+ * for a person to check against the primary source. craft's claims list, with
85
+ * each claim on the field an editor would open. Excluded types are skipped, as
86
+ * for the copy check: a client's own words are verified with them, not here.
87
+ */
88
+ declare function documentClaims(doc: unknown, options?: CopyCheckOptions): DocumentClaim[];
51
89
  /** One line an editor can act on. */
52
90
  declare function describeFinding(f: CopyFinding): string;
53
91
  /** A path as text, for a report: `hero.title`, `body[_key=="a1"]`. */
@@ -97,5 +135,42 @@ interface SchemaTypeLike {
97
135
  declare function copyCheckRule(rule: RuleLike, options?: CopyCheckOptions): RuleLike;
98
136
  /** Every document type gains the copy check as a warning, beside the validation it already has. */
99
137
  declare function withCopyCheck<T extends SchemaTypeLike>(types: T[], options?: CopyCheckOptions): T[];
138
+ /** The part of a Studio document action's props this reads. */
139
+ interface DocumentActionPropsLike {
140
+ draft?: unknown;
141
+ published?: unknown;
142
+ }
143
+ /** The part of a document action's result this changes. */
144
+ interface DocumentActionResultLike {
145
+ disabled?: boolean;
146
+ title?: unknown;
147
+ }
148
+ /**
149
+ * A document action: a function from props to a description, with an
150
+ * optional `action` tag (`"publish"` on the built-in one). The props
151
+ * parameter is `never` so Sanity's own, narrower props type fits.
152
+ */
153
+ type DocumentActionLike = ((props: never) => DocumentActionResultLike | null | undefined) & {
154
+ action?: string;
155
+ displayName?: string;
156
+ };
157
+ /**
158
+ * Opt-in: the publish action, disabled while the document has a house-rule
159
+ * (blocking tier) finding. The review tier never blocks.
160
+ *
161
+ * document: {
162
+ * actions: (prev) => prev.map((a) => (a.action === "publish" ? withCopyGuard(a) : a)),
163
+ * }
164
+ *
165
+ * The original action is always called first, with the same props, so any
166
+ * hooks it uses run in the same order on every render. Its result is
167
+ * returned as it is, except for `disabled` and the `title` tooltip naming
168
+ * the first finding. Everything else in the package warns and never blocks;
169
+ * this is the one place that can, and only where a Studio adds it.
170
+ *
171
+ * Returns the caller's own action type, so the Studio's `actions` array
172
+ * keeps its type.
173
+ */
174
+ declare function withCopyGuard<A extends DocumentActionLike>(action: A, options?: CopyCheckOptions): A;
100
175
 
101
- export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, pathToString, withCopyCheck };
176
+ export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type DocumentActionLike, type DocumentActionPropsLike, type DocumentActionResultLike, type DocumentClaim, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, documentClaims, pathToString, withCopyCheck, withCopyGuard };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Claim } from '@domandigital/craft';
2
+
1
3
  /**
2
4
  * The house copy check over a Sanity document.
3
5
  *
@@ -6,6 +8,7 @@
6
8
  * the same answer in all three. The rules are craft's: this file only decides
7
9
  * which strings in a document are copy, and where each finding belongs.
8
10
  */
11
+
9
12
  /** A Studio path: field names, array indices, or `{ _key }` for keyed array items. */
10
13
  type PathSegment = string | number | {
11
14
  _key: string;
@@ -37,6 +40,30 @@ interface CopyCheckOptions {
37
40
  * Studio shows every finding as a warning and blocks nothing either way.
38
41
  */
39
42
  review?: boolean;
43
+ /**
44
+ * Check only these languages, e.g. `["en"]`. The rules are English, so on
45
+ * a French field they are noise. `"en"` also matches `en-GB` and `en_US`.
46
+ * When set, copy is skipped when it sits:
47
+ *
48
+ * - in an array item whose `language` field is another language
49
+ * (sanity-plugin-internationalized-array v5), or whose `_key` is
50
+ * (v4 and earlier: an `internationalizedArray*` item, or one with a
51
+ * `value` field);
52
+ * - under an object key that is another language, in an object whose keys
53
+ * are all two-letter language tags (field-level translation, e.g.
54
+ * `{ en, fr }` or `{ en_GB, nb_NO }`);
55
+ * - in a document whose own `language` field is another language
56
+ * (@sanity/document-internationalization).
57
+ *
58
+ * Unset: every language is checked, as before.
59
+ */
60
+ languages?: string[];
61
+ /**
62
+ * Dot paths of fields an editor never sees (`hidden: true` in the schema),
63
+ * e.g. `["seo.internalNotes"]`. Never read. `withCopyCheck` fills this in
64
+ * from the schema; pass it yourself only when calling the check directly.
65
+ */
66
+ hiddenPaths?: string[];
40
67
  }
41
68
  declare const DEFAULT_EXCLUDED_TYPES: string[];
42
69
  declare const DEFAULT_SKIP_FIELDS: string[];
@@ -48,6 +75,17 @@ interface Piece {
48
75
  declare function collectCopy(doc: unknown, options?: CopyCheckOptions): Piece[];
49
76
  /** Check one document. Returns nothing for an excluded type. */
50
77
  declare function checkDocumentCopy(doc: unknown, options?: CopyCheckOptions): CopyFinding[];
78
+ interface DocumentClaim extends Omit<Claim, "path" | "line"> {
79
+ /** The field the sentence is in. */
80
+ path: Path;
81
+ }
82
+ /**
83
+ * Every sentence in a document holding a price, figure, date or named source,
84
+ * for a person to check against the primary source. craft's claims list, with
85
+ * each claim on the field an editor would open. Excluded types are skipped, as
86
+ * for the copy check: a client's own words are verified with them, not here.
87
+ */
88
+ declare function documentClaims(doc: unknown, options?: CopyCheckOptions): DocumentClaim[];
51
89
  /** One line an editor can act on. */
52
90
  declare function describeFinding(f: CopyFinding): string;
53
91
  /** A path as text, for a report: `hero.title`, `body[_key=="a1"]`. */
@@ -97,5 +135,42 @@ interface SchemaTypeLike {
97
135
  declare function copyCheckRule(rule: RuleLike, options?: CopyCheckOptions): RuleLike;
98
136
  /** Every document type gains the copy check as a warning, beside the validation it already has. */
99
137
  declare function withCopyCheck<T extends SchemaTypeLike>(types: T[], options?: CopyCheckOptions): T[];
138
+ /** The part of a Studio document action's props this reads. */
139
+ interface DocumentActionPropsLike {
140
+ draft?: unknown;
141
+ published?: unknown;
142
+ }
143
+ /** The part of a document action's result this changes. */
144
+ interface DocumentActionResultLike {
145
+ disabled?: boolean;
146
+ title?: unknown;
147
+ }
148
+ /**
149
+ * A document action: a function from props to a description, with an
150
+ * optional `action` tag (`"publish"` on the built-in one). The props
151
+ * parameter is `never` so Sanity's own, narrower props type fits.
152
+ */
153
+ type DocumentActionLike = ((props: never) => DocumentActionResultLike | null | undefined) & {
154
+ action?: string;
155
+ displayName?: string;
156
+ };
157
+ /**
158
+ * Opt-in: the publish action, disabled while the document has a house-rule
159
+ * (blocking tier) finding. The review tier never blocks.
160
+ *
161
+ * document: {
162
+ * actions: (prev) => prev.map((a) => (a.action === "publish" ? withCopyGuard(a) : a)),
163
+ * }
164
+ *
165
+ * The original action is always called first, with the same props, so any
166
+ * hooks it uses run in the same order on every render. Its result is
167
+ * returned as it is, except for `disabled` and the `title` tooltip naming
168
+ * the first finding. Everything else in the package warns and never blocks;
169
+ * this is the one place that can, and only where a Studio adds it.
170
+ *
171
+ * Returns the caller's own action type, so the Studio's `actions` array
172
+ * keeps its type.
173
+ */
174
+ declare function withCopyGuard<A extends DocumentActionLike>(action: A, options?: CopyCheckOptions): A;
100
175
 
101
- export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, pathToString, withCopyCheck };
176
+ export { type CopyCheckOptions, type CopyFinding, DEFAULT_EXCLUDED_TYPES, DEFAULT_SKIP_FIELDS, type DocumentActionLike, type DocumentActionPropsLike, type DocumentActionResultLike, type DocumentClaim, type Path, type PathSegment, type RuleLike, type SchemaTypeLike, type Tier, checkDocumentCopy, collectCopy, copyCheckRule, describeFinding, documentClaims, pathToString, withCopyCheck, withCopyGuard };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/core.ts
2
- import { applyHouseGate, checkCopy } from "@domandigital/craft";
3
- var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote"];
2
+ import { applyHouseGate, checkCopy, findClaims } from "@domandigital/craft";
3
+ var DEFAULT_EXCLUDED_TYPES = ["testimonial", "review", "proofQuote", "quote", "assist.instruction.context"];
4
4
  var DEFAULT_SKIP_FIELDS = [
5
5
  "slug",
6
6
  "url",
@@ -24,17 +24,35 @@ var DEFAULT_SKIP_FIELDS = [
24
24
  "script",
25
25
  "schema",
26
26
  "jsonLd",
27
- "canonical"
27
+ "canonical",
28
+ "language",
29
+ "locale"
28
30
  ];
29
31
  var NOT_COPY_TYPES = /* @__PURE__ */ new Set(["slug", "reference", "geopoint", "color", "sanity.imageAsset", "sanity.fileAsset", "code"]);
30
32
  var MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file"]);
31
33
  var MEDIA_COPY = /* @__PURE__ */ new Set(["alt", "caption", "title", "description"]);
32
34
  var DENSITY_TELLS = ["phrase-density", "aphorism-density", "contraction-scarcity", "sentence-rhythm", "repeated-sentence", "heading-shape", "heading-echo"];
35
+ var LANGUAGE_TAG = /^[a-z]{2,3}(?:[_-][A-Za-z]{2,4})?$/;
36
+ var LANGUAGE_KEY = /^[a-z]{2}(?:[_-][A-Za-z]{2,4})?$/;
37
+ function languageWanted(tag, wanted) {
38
+ const t = tag.toLowerCase().replace(/_/g, "-");
39
+ return wanted.some((w) => {
40
+ const base = w.toLowerCase().replace(/_/g, "-");
41
+ return t === base || t.startsWith(`${base}-`);
42
+ });
43
+ }
44
+ function itemLanguage(item) {
45
+ if (typeof item.language === "string") return item.language;
46
+ const keyed = typeof item._type === "string" && item._type.startsWith("internationalizedArray") || "value" in item;
47
+ if (keyed && typeof item._key === "string" && LANGUAGE_TAG.test(item._key)) return item._key;
48
+ return void 0;
49
+ }
33
50
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
34
51
  function notCopy(text) {
35
52
  const t = text.trim();
36
53
  if (!t) return true;
37
54
  if (/^[a-z0-9_-]+$/.test(t)) return true;
55
+ if (LANGUAGE_TAG.test(t)) return true;
38
56
  if (/^(?:https?:\/\/|www\.|mailto:|tel:|\/)\S*$/i.test(t)) return true;
39
57
  if (/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/.test(t)) return true;
40
58
  if (/^#[0-9a-f]{3,8}$/i.test(t)) return true;
@@ -53,7 +71,13 @@ function blockText(block) {
53
71
  var segment = (item, index) => isRecord(item) && typeof item._key === "string" ? { _key: item._key } : index;
54
72
  function collectCopy(doc, options = {}) {
55
73
  const skip = new Set(options.skipFields ?? DEFAULT_SKIP_FIELDS);
74
+ const hidden = new Set(options.hiddenPaths ?? []);
75
+ const languages = options.languages;
56
76
  const pieces = [];
77
+ if (languages && isRecord(doc) && typeof doc.language === "string" && !languageWanted(doc.language, languages)) {
78
+ return pieces;
79
+ }
80
+ const fieldPath = (path) => path.every((s) => typeof s === "string") ? path.join(".") : void 0;
57
81
  const walk = (value, path) => {
58
82
  if (typeof value === "string") {
59
83
  if (!notCopy(value)) pieces.push({ path, text: value });
@@ -61,6 +85,10 @@ function collectCopy(doc, options = {}) {
61
85
  }
62
86
  if (Array.isArray(value)) {
63
87
  value.forEach((item, i) => {
88
+ if (languages && isRecord(item)) {
89
+ const language = itemLanguage(item);
90
+ if (language && !languageWanted(language, languages)) return;
91
+ }
64
92
  if (isRecord(item) && item._type === "block" && Array.isArray(item.children)) {
65
93
  const text = blockText(item);
66
94
  if (text.trim()) pieces.push({ path: [...path, segment(item, i)], text });
@@ -73,9 +101,15 @@ function collectCopy(doc, options = {}) {
73
101
  if (!isRecord(value)) return;
74
102
  if (typeof value._type === "string" && NOT_COPY_TYPES.has(value._type)) return;
75
103
  const media = typeof value._type === "string" && MEDIA_TYPES.has(value._type);
104
+ const fields = Object.keys(value).filter((k) => !k.startsWith("_"));
105
+ const localeMap = languages !== void 0 && fields.length > 0 && fields.every((k) => LANGUAGE_KEY.test(k)) && fields.some((k) => languageWanted(k, languages));
76
106
  for (const [key, child] of Object.entries(value)) {
77
107
  if (key.startsWith("_") || skip.has(key) || media && !MEDIA_COPY.has(key)) continue;
78
- walk(child, [...path, key]);
108
+ if (localeMap && !languageWanted(key, languages)) continue;
109
+ const childPath = [...path, key];
110
+ const dotted = fieldPath(childPath);
111
+ if (dotted !== void 0 && hidden.has(dotted)) continue;
112
+ walk(child, childPath);
79
113
  }
80
114
  };
81
115
  walk(doc, []);
@@ -108,6 +142,17 @@ function checkDocumentCopy(doc, options = {}) {
108
142
  }
109
143
  return findings;
110
144
  }
145
+ function documentClaims(doc, options = {}) {
146
+ if (!isRecord(doc)) return [];
147
+ const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
148
+ if (typeof doc._type === "string" && excluded.has(doc._type)) return [];
149
+ const pieces = collectCopy(doc, options);
150
+ const { claims } = findClaims(pieces.map((p, i) => ({ path: fileFor(i), text: p.text })));
151
+ return claims.flatMap(({ path, line: _line, ...claim }) => {
152
+ const piece = pieces[Number(/^field-(\d+)\.md$/.exec(path)?.[1])];
153
+ return piece ? [{ ...claim, path: piece.path }] : [];
154
+ });
155
+ }
111
156
  function describeFinding(f) {
112
157
  const lead = f.tier === "block" ? "House rule" : "Worth a look";
113
158
  return `${lead} (${f.name}): ${f.message}. ${f.fix}`;
@@ -118,10 +163,11 @@ function pathToString(path) {
118
163
 
119
164
  // src/schema.ts
120
165
  function copyCheckRule(rule, options = {}) {
121
- let lastInput = "";
166
+ let lastInput;
122
167
  let lastResult = true;
123
168
  return rule.custom((doc) => {
124
- const input = JSON.stringify(doc ?? null);
169
+ const type = doc !== null && typeof doc === "object" ? doc._type : void 0;
170
+ const input = JSON.stringify([type, collectCopy(doc, options)]);
125
171
  if (input === lastInput) return lastResult;
126
172
  lastInput = input;
127
173
  const findings = checkDocumentCopy(doc, options);
@@ -129,19 +175,60 @@ function copyCheckRule(rule, options = {}) {
129
175
  return lastResult;
130
176
  }).warning();
131
177
  }
178
+ function staticHiddenPaths(type, byName, prefix = "", seen = /* @__PURE__ */ new Set()) {
179
+ const own = Array.isArray(type.fields) ? type.fields : void 0;
180
+ const named = typeof type.type === "string" ? byName.get(type.type) : void 0;
181
+ const fields = own ?? (named && Array.isArray(named.fields) ? named.fields : []);
182
+ if (!own && named && typeof type.type === "string") {
183
+ if (seen.has(type.type)) return [];
184
+ seen = new Set(seen).add(type.type);
185
+ }
186
+ const paths = [];
187
+ for (const field of fields) {
188
+ if (typeof field?.name !== "string") continue;
189
+ const path = prefix ? `${prefix}.${field.name}` : field.name;
190
+ if (field.hidden === true) paths.push(path);
191
+ else paths.push(...staticHiddenPaths(field, byName, path, seen));
192
+ }
193
+ return paths;
194
+ }
132
195
  var asArray = (v) => v === void 0 || v === null ? [] : Array.isArray(v) ? v : [v];
133
196
  function withCopyCheck(types, options = {}) {
134
197
  const excluded = new Set(options.excludeTypes ?? DEFAULT_EXCLUDED_TYPES);
198
+ const byName = new Map(types.map((t) => [t.name, t]));
135
199
  return types.map((t) => {
136
200
  if (t.type !== "document" || excluded.has(t.name)) return t;
201
+ const hiddenPaths = [...options.hiddenPaths ?? [], ...staticHiddenPaths({ fields: t.fields }, byName)];
202
+ const typeOptions = hiddenPaths.length > 0 ? { ...options, hiddenPaths } : options;
137
203
  const existing = t.validation;
138
204
  const validation = (rule, context) => [
139
205
  ...asArray(typeof existing === "function" ? existing(rule, context) : existing),
140
- copyCheckRule(rule, options)
206
+ copyCheckRule(rule, typeOptions)
141
207
  ];
142
208
  return { ...t, validation };
143
209
  });
144
210
  }
211
+ function withCopyGuard(action, options = {}) {
212
+ let lastDoc;
213
+ let lastBlocking = [];
214
+ const call = action;
215
+ const guarded = (props) => {
216
+ const result = call(props);
217
+ if (!result) return result;
218
+ const doc = props.draft ?? props.published;
219
+ if (doc !== lastDoc) {
220
+ lastDoc = doc;
221
+ lastBlocking = checkDocumentCopy(doc, { ...options, review: false }).filter((f) => f.tier === "block");
222
+ }
223
+ if (lastBlocking.length === 0) return result;
224
+ const more = lastBlocking.length > 1 ? ` (and ${lastBlocking.length - 1} more)` : "";
225
+ return { ...result, disabled: true, title: `${describeFinding(lastBlocking[0])}${more}` };
226
+ };
227
+ const tagged = guarded;
228
+ if (action.action !== void 0) tagged.action = action.action;
229
+ tagged.displayName = `withCopyGuard(${action.displayName ?? "action"})`;
230
+ return tagged;
231
+ }
145
232
  export {
146
233
  DEFAULT_EXCLUDED_TYPES,
147
234
  DEFAULT_SKIP_FIELDS,
@@ -149,6 +236,8 @@ export {
149
236
  collectCopy,
150
237
  copyCheckRule,
151
238
  describeFinding,
239
+ documentClaims,
152
240
  pathToString,
153
- withCopyCheck
241
+ withCopyCheck,
242
+ withCopyGuard
154
243
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@domandigital/sanity-copy",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "description": "The Doman Digital house copy check in Sanity Studio: every document type gains craft's copy rules as validation warnings on the field that caused them. Also a pure checker for a document or an export. No Sanity dependency.",
6
6
  "license": "Apache-2.0",
@@ -8,10 +8,13 @@
8
8
  "main": "dist/index.cjs",
9
9
  "module": "dist/index.js",
10
10
  "types": "dist/index.d.ts",
11
+ "sideEffects": false,
11
12
  "exports": {
12
13
  ".": {
13
- "types": "./dist/index.d.ts",
14
- "import": "./dist/index.js",
14
+ "import": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
15
18
  "require": {
16
19
  "types": "./dist/index.d.cts",
17
20
  "default": "./dist/index.cjs"
@@ -31,7 +34,7 @@
31
34
  "vitest": "^2.1.9"
32
35
  },
33
36
  "engines": {
34
- "node": ">=20"
37
+ "node": ">=22.12"
35
38
  },
36
39
  "repository": {
37
40
  "type": "git",
@@ -47,7 +50,7 @@
47
50
  "provenance": true
48
51
  },
49
52
  "dependencies": {
50
- "@domandigital/craft": "^0.9.0"
53
+ "@domandigital/craft": "^0.11.0"
51
54
  },
52
55
  "keywords": [
53
56
  "sanity",