@mark1russell7/text 0.0.4 → 0.0.6

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @mark1russell7/text
2
2
 
3
- Plain text helpers in four groups. The groups are the escapes of a text for five targets, the English word forms, a word search and the removal of secrets.
3
+ Plain text helpers in six groups: the escapes of a text for five targets, the English word forms and a word search. The other three groups are the text of a thrown value, the removal of secrets, and lengths with cuts and padding.
4
4
 
5
5
  ```sh
6
6
  pnpm add @mark1russell7/text
@@ -53,6 +53,26 @@ wordSearch("istanbul")("İSTANBUL"); // false: "İ" keeps its dot as U+0307
53
53
  searchKey("file"); // "file"
54
54
  ```
55
55
 
56
+ ## The text of a thrown value
57
+
58
+ `errorMessage(error)` gives the text of a thrown value, for a log line or a message on a screen. It does not throw.
59
+
60
+ ```ts
61
+ import { errorMessage } from "@mark1russell7/text";
62
+
63
+ errorMessage(new Error("boom")); // "boom"
64
+ errorMessage("timeout"); // "timeout"
65
+ errorMessage(Object.create(null)); // "[object Object]"
66
+ ```
67
+
68
+ | Value | Text |
69
+ | --- | --- |
70
+ | An object with a `message` text, also an `Error` from a `vm` context or an `iframe` | The message |
71
+ | An `Error` of any realm with a `message` that is not a text | `String(message)` |
72
+ | Each other value | `String(value)` |
73
+ | A value that makes `String` throw | The tag of `Object.prototype.toString`, for example `[object Object]` |
74
+ | A revoked `Proxy` | `[object]` |
75
+
56
76
  ## The removal of secrets
57
77
 
58
78
  `redactSecrets(text, secrets, options?)` puts a mark in place of each secret in a text. Use it on an error message or a log line before it goes out. The function is in the entry `@mark1russell7/text/redact`, so the root entry stays small.
@@ -80,10 +100,56 @@ redactSecrets("token=k/y!", secrets, options); // "token=***"
80
100
 
81
101
  The function examines the text one time. At each position, it removes the longest form that agrees, so a secret in a secret gives one mark. It ignores an empty secret.
82
102
 
103
+ ## Lengths, truncation and padding
104
+
105
+ The entry `@mark1russell7/text/length` has three functions. Each function counts in the unit that you give. The default unit is `code-unit`.
106
+
107
+ | Unit | One unit | Length of the family emoji 👨‍👩‍👧‍👦 | Length of `e` and U+0301 (é) |
108
+ | --- | --- | --- | --- |
109
+ | `code-unit` | One UTF-16 code unit, as in `String.prototype.length` | 11 | 2 |
110
+ | `code-point` | One Unicode code point. A surrogate pair is one unit | 7 | 2 |
111
+ | `grapheme` | One extended grapheme cluster of `Intl.Segmenter` (UAX #29) | 1 | 1 |
112
+
113
+ - `textLength(text, unit?)` gives the length of a text in a unit.
114
+ - `truncate(text, max, options?)` cuts a text to `max` units or fewer, with a mark at the end. The default mark is "…".
115
+ - `pad(text, width, options?)` adds a fill at the start, at the end or at the two sides, to `width` units or fewer.
116
+
117
+ ```ts
118
+ import { pad, textLength, truncate } from "@mark1russell7/text/length";
119
+
120
+ textLength("🇯🇵 ok", "grapheme"); // 4
121
+ truncate("Water main break on Elm Road", 12); // "Water main …"
122
+ truncate(title, 250, { unit: "code-point" }); // 250 code points or fewer, with "…" at the end
123
+ truncate("ab🇯🇵cd", 5); // "ab…": the cut does not break the flag
124
+ truncate("ab🇯🇵cd", 5, { boundary: "code-point" }); // "ab🇯…"
125
+ truncate("hello", 2, { mark: "..." }); // "he": the mark is longer than max, so the result has no mark
126
+ pad("7", 3, { side: "start", fill: "0" }); // "007"
127
+ pad("ab", 7, { fill: "-=" }); // "ab-=-=-"
128
+ pad("ab", 5, { fill: "😀" }); // "ab😀": the emoji has two code units, so one half does not go in
129
+ ```
130
+
131
+ `truncate` obeys these rules:
132
+
133
+ - A text with `max` units or fewer comes back as it is, with no mark.
134
+ - The cut keeps each grapheme whole by default. With `boundary: "code-point"`, the cut keeps only each surrogate pair whole. The unit `grapheme` always keeps each grapheme whole.
135
+ - The result has `max` units or fewer, with the mark. A grapheme that does not fit goes out, so the result can be shorter than `max`.
136
+ - When the mark has more units than `max`, the result has no mark. It is the start of the text, with `max` units or fewer. Thus `truncate("hello", 0)` gives "".
137
+ - A `max` that is not an integer of 0 or more gives a `RangeError`. A unit or a boundary that is not in its type also gives a `RangeError`.
138
+
139
+ `pad` obeys these rules:
140
+
141
+ - A text with `width` units or more comes back as it is. The function does not cut a text.
142
+ - The fill goes again and again from its start, as in `padStart` and `padEnd`. The last copy can be a part of the fill.
143
+ - That part keeps each grapheme whole by default. Thus the result can be shorter than `width`.
144
+ - The side `both` puts the half of the fill at the start and the other half at the end. For an odd count, the end gets one more unit.
145
+ - An empty fill, a bad side and a `width` that is not an integer of 0 or more give a `RangeError`.
146
+
83
147
  ## The copies that this package replaces
84
148
 
85
149
  The tests run 58 copies of these functions from other repositories of the owner. Each copy comes from a list of the duplication atlas, at a pinned commit. The file `test/copies.json` has each copy, and `test/differences.ts` has each difference from the function of this package, with its reason. A copy that is not in the list gives the same output on each of the 1000 test strings.
86
150
 
151
+ The tests also examine 18 copies of a cut with a mark, from a later list of the atlas. The file `test/cut-copies.json` has each copy and the call of `truncate` that replaces it. The file `test/cut-differences.ts` has each difference, with its reason. Most copies cut at a code unit, so they can break a surrogate pair or a grapheme. The atlas has no copy of a padding function. The repositories call `padStart` and `padEnd` directly.
152
+
87
153
  ## Limits
88
154
 
89
155
  - `escapeHtml` does not escape quotes. For an attribute value, use `escapeAttribute`.
@@ -91,4 +157,8 @@ The tests run 58 copies of these functions from other repositories of the owner.
91
157
  - `escapeMarkdown` does not change spaces. Four spaces at the start of a line make a code block.
92
158
  - `wordSearch` keeps accents, so "cafe" does not find "café".
93
159
  - `countOf` knows no irregular plural. Give the plural noun for each noun that does not add "s".
160
+ - `errorMessage` gives only the message. It does not add the name of the error, its `cause` or its stack.
94
161
  - `redactSecrets` removes only the forms in its table. A secret in a JSON string with escapes, or in a different encoding, stays.
162
+ - `textLength`, `truncate` and `pad` count graphemes with the `Intl.Segmenter` of the runtime. An old runtime can count a new emoji as more than one grapheme.
163
+ - In `pad`, a grapheme of the fill can join the text or the next copy of the fill. A combining mark and a lone regional indicator do this. Then the result has fewer graphemes than the width.
164
+ - The three functions count units, not the width on a screen. A wide character, for example 日, is one unit, as a narrow character is.
package/build/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
- * The entry of `@mark1russell7/text`: plain text helpers. The groups are the escapes for HTML, attributes, regular
3
- * expressions, Markdown and GitHub Actions workflow commands, the English word forms and a word search. The entry
4
- * `@mark1russell7/text/redact` removes secrets from a text.
2
+ * The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes, regular
3
+ * expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
4
+ * search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text.
5
5
  */
6
6
  /**
7
7
  * This module has the English word forms.
@@ -17,6 +17,24 @@
17
17
  * @returns The count, a space and the noun.
18
18
  */
19
19
  export declare function countOf(count: number, noun: string, plural?: string): string;
20
+ /**
21
+ * This module has the text of a thrown value.
22
+ */
23
+ /**
24
+ * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.
25
+ *
26
+ * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error
27
+ * from another realm (a `vm` context or an `iframe`) also gives its message.
28
+ * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of
29
+ * `Object.prototype.toString` finds an `Error` of each realm.
30
+ * - Each other value gives `String(value)`.
31
+ * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.
32
+ * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.
33
+ *
34
+ * @param error - The thrown value. It can be any value.
35
+ * @returns The text of the value.
36
+ */
37
+ export declare function errorMessage(error: unknown): string;
20
38
  /**
21
39
  * This function escapes a text for the content of an HTML element. It changes `&`, `<` and `>` to named character
22
40
  * references. The quotes stay, because they have no meaning in element content.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/english.ts","../src/escape.ts","../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;;;wBAcgB,QAAQ,eAAe,cAAc;;;;;;;;wBCCrC,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB;;;;;;;;;;;;;;;;;wBCnDvB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/english.ts","../src/error.ts","../src/escape.ts","../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;;;wBAcgB,QAAQ,eAAe,cAAc;;;;;;;;;;;;;;;;;;wBCIrC,aAAa;;;;;;;;wBCHb,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB;;;;;;;;;;;;;;;;;wBCnDvB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB"}
package/build/index.js CHANGED
@@ -16,6 +16,40 @@ import { a as escapeWorkflowData, i as escapeRegExp, n as escapeHtml, o as escap
16
16
  function countOf(count, noun, plural = `${noun}s`) {
17
17
  return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
18
18
  }
19
+ // src/error.ts
20
+ /**
21
+ * This module has the text of a thrown value.
22
+ */
23
+ /**
24
+ * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.
25
+ *
26
+ * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error
27
+ * from another realm (a `vm` context or an `iframe`) also gives its message.
28
+ * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of
29
+ * `Object.prototype.toString` finds an `Error` of each realm.
30
+ * - Each other value gives `String(value)`.
31
+ * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.
32
+ * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.
33
+ *
34
+ * @param error - The thrown value. It can be any value.
35
+ * @returns The text of the value.
36
+ */
37
+ function errorMessage(error) {
38
+ try {
39
+ if (typeof error === "object" && error !== null && "message" in error) {
40
+ const message = error.message;
41
+ if (typeof message === "string") return message;
42
+ if (Object.prototype.toString.call(error) === "[object Error]") return String(message);
43
+ }
44
+ return String(error);
45
+ } catch {
46
+ try {
47
+ return Object.prototype.toString.call(error);
48
+ } catch {
49
+ return `[${typeof error}]`;
50
+ }
51
+ }
52
+ }
19
53
  // src/search.ts
20
54
  /**
21
55
  * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,
@@ -56,6 +90,6 @@ function wordSearch(query) {
56
90
  const words = searchKey(query).split(/\s+/u).filter((word) => word !== "");
57
91
  return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));
58
92
  }
59
- export { countOf, escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty, searchKey, wordSearch };
93
+ export { countOf, errorMessage, escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty, searchKey, wordSearch };
60
94
 
61
95
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/english.ts","../src/search.ts"],"sourcesContent":["/**\n * This module has the English word forms.\n */\n\n/**\n * This function gives a count with a noun, for example \"1 site\" or \"1,024 sites\". Only the count 1 takes the singular\n * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most\n * three decimal places.\n *\n * @param count - The number of things.\n * @param noun - The singular noun.\n * @param plural - The plural noun. The default is the singular noun with the letter \"s\" at the end.\n * @returns The count, a space and the noun.\n */\nexport function countOf(count: number, noun: string, plural = `${noun}s`): string {\n return `${count.toLocaleString(\"en\")} ${count === 1 ? noun : plural}`;\n}\n","/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,QAAQ,OAAe,MAAc,SAAS,GAAG,KAAK,IAAY;CAChF,OAAO,GAAG,MAAM,eAAe,IAAI,EAAE,GAAG,UAAU,IAAI,OAAO;AAC/D;;;;;;;ACVA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/english.ts","../src/error.ts","../src/search.ts"],"sourcesContent":["/**\n * This module has the English word forms.\n */\n\n/**\n * This function gives a count with a noun, for example \"1 site\" or \"1,024 sites\". Only the count 1 takes the singular\n * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most\n * three decimal places.\n *\n * @param count - The number of things.\n * @param noun - The singular noun.\n * @param plural - The plural noun. The default is the singular noun with the letter \"s\" at the end.\n * @returns The count, a space and the noun.\n */\nexport function countOf(count: number, noun: string, plural = `${noun}s`): string {\n return `${count.toLocaleString(\"en\")} ${count === 1 ? noun : plural}`;\n}\n","/**\n * This module has the text of a thrown value.\n */\n\n/**\n * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.\n *\n * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error\n * from another realm (a `vm` context or an `iframe`) also gives its message.\n * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of\n * `Object.prototype.toString` finds an `Error` of each realm.\n * - Each other value gives `String(value)`.\n * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.\n * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.\n *\n * @param error - The thrown value. It can be any value.\n * @returns The text of the value.\n */\nexport function errorMessage(error: unknown): string {\n try {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message: unknown = error.message;\n if (typeof message === \"string\") return message;\n if (Object.prototype.toString.call(error) === \"[object Error]\") return String(message);\n }\n return String(error);\n } catch {\n // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.\n try {\n return Object.prototype.toString.call(error);\n } catch {\n // A revoked Proxy throws also here. The operator typeof never throws.\n return `[${typeof error}]`;\n }\n }\n}\n","/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,QAAQ,OAAe,MAAc,SAAS,GAAG,KAAK,IAAY;CAChF,OAAO,GAAG,MAAM,eAAe,IAAI,EAAE,GAAG,UAAU,IAAI,OAAO;AAC/D;;;;;;;;;;;;;;;;;;;ACEA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,OAAO;GACrE,MAAM,UAAmB,MAAM;GAC/B,IAAI,OAAO,YAAY,UAAU,OAAO;GACxC,IAAI,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,kBAAkB,OAAO,OAAO,OAAO;EACvF;EACA,OAAO,OAAO,KAAK;CACrB,QAAQ;EAEN,IAAI;GACF,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK;EAC7C,QAAQ;GAEN,OAAO,IAAI,OAAO,MAAM;EAC1B;CACF;AACF;;;;;;;AC7BA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F"}
@@ -0,0 +1,91 @@
1
+ /**
2
+ * This module has three functions for a text: its length in a unit, a cut to a length and padding to a width. The
3
+ * unit is a UTF-16 code unit, a Unicode code point or a grapheme. A grapheme is one character as a person sees it, for
4
+ * example a letter with an accent, a flag or an emoji sequence.
5
+ */
6
+ /**
7
+ * The unit of a length. `code-unit` is the unit of `String.prototype.length`. `code-point` is one Unicode code point,
8
+ * so a surrogate pair is one unit. `grapheme` is one extended grapheme cluster of Unicode (UAX #29).
9
+ */
10
+ export type TextUnit = "code-unit" | "code-point" | "grapheme";
11
+ /**
12
+ * The smallest part of a text that a cut or a fill keeps whole. The function uses the larger of this part and the unit,
13
+ * so the unit `grapheme` keeps each grapheme whole with each boundary.
14
+ */
15
+ export type TextBoundary = "code-point" | "grapheme";
16
+ /** The options of `truncate`. */
17
+ export interface TruncateOptions {
18
+ /** The unit of the length `max`. The default is `code-unit`. */
19
+ readonly unit?: TextUnit;
20
+ /** The part of the text that the cut keeps whole. The default is `grapheme`. */
21
+ readonly boundary?: TextBoundary;
22
+ /** The text at the end of a text that the function cuts. The default is the ellipsis "…" (U+2026). */
23
+ readonly mark?: string;
24
+ }
25
+ /** The options of `pad`. */
26
+ export interface PadOptions {
27
+ /** The unit of the width. The default is `code-unit`. */
28
+ readonly unit?: TextUnit;
29
+ /** The part of the fill that the function keeps whole. The default is `grapheme`. */
30
+ readonly boundary?: TextBoundary;
31
+ /** The text that the function adds. It can have more than one unit. The default is one space. */
32
+ readonly fill?: string;
33
+ /**
34
+ * The side of the fill. `both` puts the half of the fill at each side. For an odd count, the end gets one more unit.
35
+ * The default is `end`.
36
+ */
37
+ readonly side?: "start" | "end" | "both";
38
+ }
39
+ /**
40
+ * This function gives the length of a text in a unit.
41
+ *
42
+ * - `code-unit` gives `text.length`.
43
+ * - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.
44
+ * - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the
45
+ * locale.
46
+ *
47
+ * @param text - The text.
48
+ * @param unit - The unit of the length. The default is `code-unit`.
49
+ * @returns The count of units in the text.
50
+ * @throws RangeError for a unit that is not in the type `TextUnit`.
51
+ */
52
+ export declare function textLength(text: string, unit?: TextUnit): number;
53
+ /**
54
+ * This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or
55
+ * fewer, with the mark.
56
+ *
57
+ * - A text with `max` units or fewer comes back as it is, with no mark.
58
+ * - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,
59
+ * an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair
60
+ * whole.
61
+ * - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter
62
+ * than `max`.
63
+ * - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units
64
+ * or fewer.
65
+ *
66
+ * @param text - The text to cut.
67
+ * @param max - The most units in the result. It is an integer of 0 or more.
68
+ * @param options - The unit, the boundary and the mark.
69
+ * @returns The text, or the start of the text with the mark at the end.
70
+ * @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.
71
+ */
72
+ export declare function truncate(text: string, max: number, options?: TruncateOptions): string;
73
+ /**
74
+ * This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`
75
+ * units or fewer.
76
+ *
77
+ * - A text with `width` units or more comes back as it is. The function does not cut a text.
78
+ * - The fill goes again and again. The last copy of the fill can be a part of the fill, as in
79
+ * `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a
80
+ * grapheme by default.
81
+ * - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.
82
+ *
83
+ * @param text - The text.
84
+ * @param width - The length of the result with the fill. It is an integer of 0 or more.
85
+ * @param options - The unit, the boundary, the fill and the side.
86
+ * @returns The text with the fill.
87
+ * @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary
88
+ * or side.
89
+ */
90
+ export declare function pad(text: string, width: number, options?: PadOptions): string;
91
+ //# sourceMappingURL=length.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"length.d.ts","names":[],"sources":["../src/length.ts"],"mappings":";;;;;;;;;YAUY;;;;;YAMA;;iBAGK;;WAEN,OAAO;;WAEP,WAAW;;WAEX;;;iBAIM;;WAEN,OAAO;;WAEP,WAAW;;WAEX;;;;;WAKA;;;;;;;;;;;;;;;wBAwDK,WAAW,cAAc,OAAM;;;;;;;;;;;;;;;;;;;;wBA2B/B,SAAS,cAAc,aAAa,UAAS;;;;;;;;;;;;;;;;;;wBA4B7C,IAAI,cAAc,eAAe,UAAS"}
@@ -0,0 +1,118 @@
1
+ // src/length.ts
2
+ let segmenter;
3
+ /** This function gives the parts of a text at a boundary, in their order. */
4
+ function* partsOf(text, boundary) {
5
+ if (boundary === "code-point") yield* text;
6
+ else for (const { segment } of (segmenter ??= new Intl.Segmenter(void 0, { granularity: "grapheme" })).segment(text)) yield segment;
7
+ }
8
+ /** This function stops a bad option with a `RangeError` and its message. */
9
+ function check(good, message) {
10
+ if (!good) throw new RangeError(message);
11
+ }
12
+ /** This function stops a count that is not an integer of 0 or more. */
13
+ function checkCount(value, name) {
14
+ check(Number.isInteger(value) && value >= 0, `${name} is ${String(value)}, not an integer of 0 or more`);
15
+ }
16
+ /** This function stops a unit and a boundary that are not in their types, and gives the boundary to use. */
17
+ function boundaryOf(unit, boundary) {
18
+ check(unit === "code-unit" || unit === "code-point" || unit === "grapheme", `unit is ${String(unit)}, not code-unit, code-point or grapheme`);
19
+ check(boundary === "code-point" || boundary === "grapheme", `boundary is ${String(boundary)}, not code-point or grapheme`);
20
+ return unit === "grapheme" ? unit : boundary;
21
+ }
22
+ /**
23
+ * This function gives the end of the longest start of a text that has `room` units or fewer. The end is at a boundary,
24
+ * as an index of code units.
25
+ */
26
+ function endOf(text, room, unit, boundary) {
27
+ let size = 0;
28
+ let end = 0;
29
+ for (const part of partsOf(text, boundary)) {
30
+ size += unit === "code-unit" ? part.length : unit === "code-point" ? [...part].length : 1;
31
+ if (size > room) break;
32
+ end += part.length;
33
+ }
34
+ return end;
35
+ }
36
+ /**
37
+ * This function gives the length of a text in a unit.
38
+ *
39
+ * - `code-unit` gives `text.length`.
40
+ * - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.
41
+ * - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the
42
+ * locale.
43
+ *
44
+ * @param text - The text.
45
+ * @param unit - The unit of the length. The default is `code-unit`.
46
+ * @returns The count of units in the text.
47
+ * @throws RangeError for a unit that is not in the type `TextUnit`.
48
+ */
49
+ function textLength(text, unit = "code-unit") {
50
+ boundaryOf(unit, "code-point");
51
+ if (unit === "code-unit") return text.length;
52
+ let count = 0;
53
+ for (const _ of partsOf(text, unit)) count += 1;
54
+ return count;
55
+ }
56
+ /**
57
+ * This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or
58
+ * fewer, with the mark.
59
+ *
60
+ * - A text with `max` units or fewer comes back as it is, with no mark.
61
+ * - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,
62
+ * an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair
63
+ * whole.
64
+ * - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter
65
+ * than `max`.
66
+ * - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units
67
+ * or fewer.
68
+ *
69
+ * @param text - The text to cut.
70
+ * @param max - The most units in the result. It is an integer of 0 or more.
71
+ * @param options - The unit, the boundary and the mark.
72
+ * @returns The text, or the start of the text with the mark at the end.
73
+ * @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.
74
+ */
75
+ function truncate(text, max, options = {}) {
76
+ const { unit = "code-unit", mark = "…" } = options;
77
+ const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
78
+ checkCount(max, "max");
79
+ if (text.length <= max || unit !== "code-unit" && endOf(text, max, unit, unit) === text.length) return text;
80
+ const end = textLength(mark, unit) <= max ? mark : "";
81
+ return text.slice(0, endOf(text, max - textLength(end, unit), unit, boundary)) + end;
82
+ }
83
+ /**
84
+ * This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`
85
+ * units or fewer.
86
+ *
87
+ * - A text with `width` units or more comes back as it is. The function does not cut a text.
88
+ * - The fill goes again and again. The last copy of the fill can be a part of the fill, as in
89
+ * `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a
90
+ * grapheme by default.
91
+ * - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.
92
+ *
93
+ * @param text - The text.
94
+ * @param width - The length of the result with the fill. It is an integer of 0 or more.
95
+ * @param options - The unit, the boundary, the fill and the side.
96
+ * @returns The text with the fill.
97
+ * @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary
98
+ * or side.
99
+ */
100
+ function pad(text, width, options = {}) {
101
+ const { unit = "code-unit", fill = " ", side = "end" } = options;
102
+ const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
103
+ checkCount(width, "width");
104
+ check(side === "start" || side === "end" || side === "both", `side is ${String(side)}, not start, end or both`);
105
+ const size = textLength(fill, unit);
106
+ check(size > 0, "fill is an empty text");
107
+ const missing = width - textLength(text, unit);
108
+ if (missing <= 0) return text;
109
+ const fillOf = (count) => {
110
+ const copies = Math.floor(count / size);
111
+ return fill.repeat(copies) + fill.slice(0, endOf(fill, count - copies * size, unit, boundary));
112
+ };
113
+ const start = side === "start" ? missing : side === "end" ? 0 : Math.floor(missing / 2);
114
+ return fillOf(start) + text + fillOf(missing - start);
115
+ }
116
+ export { pad, textLength, truncate };
117
+
118
+ //# sourceMappingURL=length.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"length.js","names":[],"sources":["../src/length.ts"],"sourcesContent":["/**\n * This module has three functions for a text: its length in a unit, a cut to a length and padding to a width. The\n * unit is a UTF-16 code unit, a Unicode code point or a grapheme. A grapheme is one character as a person sees it, for\n * example a letter with an accent, a flag or an emoji sequence.\n */\n\n/**\n * The unit of a length. `code-unit` is the unit of `String.prototype.length`. `code-point` is one Unicode code point,\n * so a surrogate pair is one unit. `grapheme` is one extended grapheme cluster of Unicode (UAX #29).\n */\nexport type TextUnit = \"code-unit\" | \"code-point\" | \"grapheme\";\n\n/**\n * The smallest part of a text that a cut or a fill keeps whole. The function uses the larger of this part and the unit,\n * so the unit `grapheme` keeps each grapheme whole with each boundary.\n */\nexport type TextBoundary = \"code-point\" | \"grapheme\";\n\n/** The options of `truncate`. */\nexport interface TruncateOptions {\n /** The unit of the length `max`. The default is `code-unit`. */\n readonly unit?: TextUnit;\n /** The part of the text that the cut keeps whole. The default is `grapheme`. */\n readonly boundary?: TextBoundary;\n /** The text at the end of a text that the function cuts. The default is the ellipsis \"…\" (U+2026). */\n readonly mark?: string;\n}\n\n/** The options of `pad`. */\nexport interface PadOptions {\n /** The unit of the width. The default is `code-unit`. */\n readonly unit?: TextUnit;\n /** The part of the fill that the function keeps whole. The default is `grapheme`. */\n readonly boundary?: TextBoundary;\n /** The text that the function adds. It can have more than one unit. The default is one space. */\n readonly fill?: string;\n /**\n * The side of the fill. `both` puts the half of the fill at each side. For an odd count, the end gets one more unit.\n * The default is `end`.\n */\n readonly side?: \"start\" | \"end\" | \"both\";\n}\n\nlet segmenter: Intl.Segmenter | undefined;\n\n/** This function gives the parts of a text at a boundary, in their order. */\nfunction* partsOf(text: string, boundary: TextBoundary): Generator<string> {\n if (boundary === \"code-point\") yield* text;\n else for (const { segment } of (segmenter ??= new Intl.Segmenter(undefined, { granularity: \"grapheme\" })).segment(text)) yield segment;\n}\n\n/** This function stops a bad option with a `RangeError` and its message. */\nfunction check(good: boolean, message: string): void {\n if (!good) throw new RangeError(message);\n}\n\n/** This function stops a count that is not an integer of 0 or more. */\nfunction checkCount(value: number, name: string): void {\n check(Number.isInteger(value) && value >= 0, `${name} is ${String(value)}, not an integer of 0 or more`);\n}\n\n/** This function stops a unit and a boundary that are not in their types, and gives the boundary to use. */\nfunction boundaryOf(unit: TextUnit, boundary: TextBoundary): TextBoundary {\n check(unit === \"code-unit\" || unit === \"code-point\" || unit === \"grapheme\", `unit is ${String(unit)}, not code-unit, code-point or grapheme`);\n check(boundary === \"code-point\" || boundary === \"grapheme\", `boundary is ${String(boundary)}, not code-point or grapheme`);\n return unit === \"grapheme\" ? unit : boundary;\n}\n\n/**\n * This function gives the end of the longest start of a text that has `room` units or fewer. The end is at a boundary,\n * as an index of code units.\n */\nfunction endOf(text: string, room: number, unit: TextUnit, boundary: TextBoundary): number {\n let size = 0;\n let end = 0;\n for (const part of partsOf(text, boundary)) {\n size += unit === \"code-unit\" ? part.length : unit === \"code-point\" ? [...part].length : 1;\n if (size > room) break;\n end += part.length;\n }\n return end;\n}\n\n/**\n * This function gives the length of a text in a unit.\n *\n * - `code-unit` gives `text.length`.\n * - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.\n * - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the\n * locale.\n *\n * @param text - The text.\n * @param unit - The unit of the length. The default is `code-unit`.\n * @returns The count of units in the text.\n * @throws RangeError for a unit that is not in the type `TextUnit`.\n */\nexport function textLength(text: string, unit: TextUnit = \"code-unit\"): number {\n boundaryOf(unit, \"code-point\");\n if (unit === \"code-unit\") return text.length;\n let count = 0;\n for (const _ of partsOf(text, unit)) count += 1;\n return count;\n}\n\n/**\n * This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or\n * fewer, with the mark.\n *\n * - A text with `max` units or fewer comes back as it is, with no mark.\n * - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,\n * an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair\n * whole.\n * - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter\n * than `max`.\n * - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units\n * or fewer.\n *\n * @param text - The text to cut.\n * @param max - The most units in the result. It is an integer of 0 or more.\n * @param options - The unit, the boundary and the mark.\n * @returns The text, or the start of the text with the mark at the end.\n * @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.\n */\nexport function truncate(text: string, max: number, options: TruncateOptions = {}): string {\n const { unit = \"code-unit\", mark = \"…\" } = options;\n const boundary = boundaryOf(unit, options.boundary ?? \"grapheme\");\n checkCount(max, \"max\");\n // The count of code units is the largest count. Thus a text with `max` code units or fewer fits in each unit.\n if (text.length <= max || (unit !== \"code-unit\" && endOf(text, max, unit, unit) === text.length)) return text;\n const end = textLength(mark, unit) <= max ? mark : \"\";\n // A grapheme of the text can join a grapheme of the mark. A join gives fewer graphemes, never more (UAX #29).\n return text.slice(0, endOf(text, max - textLength(end, unit), unit, boundary)) + end;\n}\n\n/**\n * This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`\n * units or fewer.\n *\n * - A text with `width` units or more comes back as it is. The function does not cut a text.\n * - The fill goes again and again. The last copy of the fill can be a part of the fill, as in\n * `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a\n * grapheme by default.\n * - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.\n *\n * @param text - The text.\n * @param width - The length of the result with the fill. It is an integer of 0 or more.\n * @param options - The unit, the boundary, the fill and the side.\n * @returns The text with the fill.\n * @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary\n * or side.\n */\nexport function pad(text: string, width: number, options: PadOptions = {}): string {\n const { unit = \"code-unit\", fill = \" \", side = \"end\" } = options;\n const boundary = boundaryOf(unit, options.boundary ?? \"grapheme\");\n checkCount(width, \"width\");\n check(side === \"start\" || side === \"end\" || side === \"both\", `side is ${String(side)}, not start, end or both`);\n const size = textLength(fill, unit);\n check(size > 0, \"fill is an empty text\");\n const missing = width - textLength(text, unit);\n if (missing <= 0) return text;\n const fillOf = (count: number): string => {\n const copies = Math.floor(count / size);\n return fill.repeat(copies) + fill.slice(0, endOf(fill, count - copies * size, unit, boundary));\n };\n const start = side === \"start\" ? missing : side === \"end\" ? 0 : Math.floor(missing / 2);\n return fillOf(start) + text + fillOf(missing - start);\n}\n"],"mappings":";AA2CA,IAAI;;AAGJ,UAAU,QAAQ,MAAc,UAA2C;CACzE,IAAI,aAAa,cAAc,OAAO;MACjC,KAAK,MAAM,EAAE,cAAc,cAAc,IAAI,KAAK,UAAU,KAAA,GAAW,EAAE,aAAa,WAAW,CAAC,EAAA,CAAG,QAAQ,IAAI,GAAG,MAAM;AACjI;;AAGA,SAAS,MAAM,MAAe,SAAuB;CACnD,IAAI,CAAC,MAAM,MAAM,IAAI,WAAW,OAAO;AACzC;;AAGA,SAAS,WAAW,OAAe,MAAoB;CACrD,MAAM,OAAO,UAAU,KAAK,KAAK,SAAS,GAAG,GAAG,KAAK,MAAM,OAAO,KAAK,EAAE,8BAA8B;AACzG;;AAGA,SAAS,WAAW,MAAgB,UAAsC;CACxE,MAAM,SAAS,eAAe,SAAS,gBAAgB,SAAS,YAAY,WAAW,OAAO,IAAI,EAAE,wCAAwC;CAC5I,MAAM,aAAa,gBAAgB,aAAa,YAAY,eAAe,OAAO,QAAQ,EAAE,6BAA6B;CACzH,OAAO,SAAS,aAAa,OAAO;AACtC;;;;;AAMA,SAAS,MAAM,MAAc,MAAc,MAAgB,UAAgC;CACzF,IAAI,OAAO;CACX,IAAI,MAAM;CACV,KAAK,MAAM,QAAQ,QAAQ,MAAM,QAAQ,GAAG;EAC1C,QAAQ,SAAS,cAAc,KAAK,SAAS,SAAS,eAAe,CAAC,GAAG,IAAI,CAAC,CAAC,SAAS;EACxF,IAAI,OAAO,MAAM;EACjB,OAAO,KAAK;CACd;CACA,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,WAAW,MAAc,OAAiB,aAAqB;CAC7E,WAAW,MAAM,YAAY;CAC7B,IAAI,SAAS,aAAa,OAAO,KAAK;CACtC,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,QAAQ,MAAM,IAAI,GAAG,SAAS;CAC9C,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SAAS,MAAc,KAAa,UAA2B,CAAC,GAAW;CACzF,MAAM,EAAE,OAAO,aAAa,OAAO,QAAQ;CAC3C,MAAM,WAAW,WAAW,MAAM,QAAQ,YAAY,UAAU;CAChE,WAAW,KAAK,KAAK;CAErB,IAAI,KAAK,UAAU,OAAQ,SAAS,eAAe,MAAM,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,QAAS,OAAO;CACzG,MAAM,MAAM,WAAW,MAAM,IAAI,KAAK,MAAM,OAAO;CAEnD,OAAO,KAAK,MAAM,GAAG,MAAM,MAAM,MAAM,WAAW,KAAK,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI;AACnF;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,IAAI,MAAc,OAAe,UAAsB,CAAC,GAAW;CACjF,MAAM,EAAE,OAAO,aAAa,OAAO,KAAK,OAAO,UAAU;CACzD,MAAM,WAAW,WAAW,MAAM,QAAQ,YAAY,UAAU;CAChE,WAAW,OAAO,OAAO;CACzB,MAAM,SAAS,WAAW,SAAS,SAAS,SAAS,QAAQ,WAAW,OAAO,IAAI,EAAE,yBAAyB;CAC9G,MAAM,OAAO,WAAW,MAAM,IAAI;CAClC,MAAM,OAAO,GAAG,uBAAuB;CACvC,MAAM,UAAU,QAAQ,WAAW,MAAM,IAAI;CAC7C,IAAI,WAAW,GAAG,OAAO;CACzB,MAAM,UAAU,UAA0B;EACxC,MAAM,SAAS,KAAK,MAAM,QAAQ,IAAI;EACtC,OAAO,KAAK,OAAO,MAAM,IAAI,KAAK,MAAM,GAAG,MAAM,MAAM,QAAQ,SAAS,MAAM,MAAM,QAAQ,CAAC;CAC/F;CACA,MAAM,QAAQ,SAAS,UAAU,UAAU,SAAS,QAAQ,IAAI,KAAK,MAAM,UAAU,CAAC;CACtF,OAAO,OAAO,KAAK,IAAI,OAAO,OAAO,UAAU,KAAK;AACtD"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/text",
4
- "version": "0.0.4",
5
- "description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf), a word search (wordSearch) and the removal of secrets (redactSecrets).",
4
+ "version": "0.0.6",
5
+ "description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf), a word search (wordSearch), the text of a thrown value (errorMessage), the removal of secrets (redactSecrets), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad).",
6
6
  "keywords": [
7
7
  "text",
8
8
  "escape",
@@ -13,6 +13,11 @@
13
13
  "plural",
14
14
  "redact",
15
15
  "secrets",
16
+ "error",
17
+ "truncate",
18
+ "pad",
19
+ "grapheme",
20
+ "unicode",
16
21
  "typescript"
17
22
  ],
18
23
  "homepage": "https://github.com/mark1russell7/text#readme",
@@ -39,6 +44,10 @@
39
44
  "types": "./build/redact.d.ts",
40
45
  "default": "./build/redact.js"
41
46
  },
47
+ "./length": {
48
+ "types": "./build/length.d.ts",
49
+ "default": "./build/length.js"
50
+ },
42
51
  "./package.json": "./package.json"
43
52
  },
44
53
  "files": [
package/src/error.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * This module has the text of a thrown value.
3
+ */
4
+
5
+ /**
6
+ * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.
7
+ *
8
+ * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error
9
+ * from another realm (a `vm` context or an `iframe`) also gives its message.
10
+ * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of
11
+ * `Object.prototype.toString` finds an `Error` of each realm.
12
+ * - Each other value gives `String(value)`.
13
+ * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.
14
+ * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.
15
+ *
16
+ * @param error - The thrown value. It can be any value.
17
+ * @returns The text of the value.
18
+ */
19
+ export function errorMessage(error: unknown): string {
20
+ try {
21
+ if (typeof error === "object" && error !== null && "message" in error) {
22
+ const message: unknown = error.message;
23
+ if (typeof message === "string") return message;
24
+ if (Object.prototype.toString.call(error) === "[object Error]") return String(message);
25
+ }
26
+ return String(error);
27
+ } catch {
28
+ // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.
29
+ try {
30
+ return Object.prototype.toString.call(error);
31
+ } catch {
32
+ // A revoked Proxy throws also here. The operator typeof never throws.
33
+ return `[${typeof error}]`;
34
+ }
35
+ }
36
+ }
package/src/index.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
- * The entry of `@mark1russell7/text`: plain text helpers. The groups are the escapes for HTML, attributes, regular
3
- * expressions, Markdown and GitHub Actions workflow commands, the English word forms and a word search. The entry
4
- * `@mark1russell7/text/redact` removes secrets from a text.
2
+ * The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes, regular
3
+ * expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
4
+ * search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text.
5
5
  */
6
6
  export { countOf } from "./english.ts";
7
+ export { errorMessage } from "./error.ts";
7
8
  export { escapeAttribute, escapeHtml, escapeMarkdown, escapeRegExp, escapeWorkflowData, escapeWorkflowProperty } from "./escape.ts";
8
9
  export { searchKey, wordSearch } from "./search.ts";
package/src/length.ts ADDED
@@ -0,0 +1,167 @@
1
+ /**
2
+ * This module has three functions for a text: its length in a unit, a cut to a length and padding to a width. The
3
+ * unit is a UTF-16 code unit, a Unicode code point or a grapheme. A grapheme is one character as a person sees it, for
4
+ * example a letter with an accent, a flag or an emoji sequence.
5
+ */
6
+
7
+ /**
8
+ * The unit of a length. `code-unit` is the unit of `String.prototype.length`. `code-point` is one Unicode code point,
9
+ * so a surrogate pair is one unit. `grapheme` is one extended grapheme cluster of Unicode (UAX #29).
10
+ */
11
+ export type TextUnit = "code-unit" | "code-point" | "grapheme";
12
+
13
+ /**
14
+ * The smallest part of a text that a cut or a fill keeps whole. The function uses the larger of this part and the unit,
15
+ * so the unit `grapheme` keeps each grapheme whole with each boundary.
16
+ */
17
+ export type TextBoundary = "code-point" | "grapheme";
18
+
19
+ /** The options of `truncate`. */
20
+ export interface TruncateOptions {
21
+ /** The unit of the length `max`. The default is `code-unit`. */
22
+ readonly unit?: TextUnit;
23
+ /** The part of the text that the cut keeps whole. The default is `grapheme`. */
24
+ readonly boundary?: TextBoundary;
25
+ /** The text at the end of a text that the function cuts. The default is the ellipsis "…" (U+2026). */
26
+ readonly mark?: string;
27
+ }
28
+
29
+ /** The options of `pad`. */
30
+ export interface PadOptions {
31
+ /** The unit of the width. The default is `code-unit`. */
32
+ readonly unit?: TextUnit;
33
+ /** The part of the fill that the function keeps whole. The default is `grapheme`. */
34
+ readonly boundary?: TextBoundary;
35
+ /** The text that the function adds. It can have more than one unit. The default is one space. */
36
+ readonly fill?: string;
37
+ /**
38
+ * The side of the fill. `both` puts the half of the fill at each side. For an odd count, the end gets one more unit.
39
+ * The default is `end`.
40
+ */
41
+ readonly side?: "start" | "end" | "both";
42
+ }
43
+
44
+ let segmenter: Intl.Segmenter | undefined;
45
+
46
+ /** This function gives the parts of a text at a boundary, in their order. */
47
+ function* partsOf(text: string, boundary: TextBoundary): Generator<string> {
48
+ if (boundary === "code-point") yield* text;
49
+ else for (const { segment } of (segmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" })).segment(text)) yield segment;
50
+ }
51
+
52
+ /** This function stops a bad option with a `RangeError` and its message. */
53
+ function check(good: boolean, message: string): void {
54
+ if (!good) throw new RangeError(message);
55
+ }
56
+
57
+ /** This function stops a count that is not an integer of 0 or more. */
58
+ function checkCount(value: number, name: string): void {
59
+ check(Number.isInteger(value) && value >= 0, `${name} is ${String(value)}, not an integer of 0 or more`);
60
+ }
61
+
62
+ /** This function stops a unit and a boundary that are not in their types, and gives the boundary to use. */
63
+ function boundaryOf(unit: TextUnit, boundary: TextBoundary): TextBoundary {
64
+ check(unit === "code-unit" || unit === "code-point" || unit === "grapheme", `unit is ${String(unit)}, not code-unit, code-point or grapheme`);
65
+ check(boundary === "code-point" || boundary === "grapheme", `boundary is ${String(boundary)}, not code-point or grapheme`);
66
+ return unit === "grapheme" ? unit : boundary;
67
+ }
68
+
69
+ /**
70
+ * This function gives the end of the longest start of a text that has `room` units or fewer. The end is at a boundary,
71
+ * as an index of code units.
72
+ */
73
+ function endOf(text: string, room: number, unit: TextUnit, boundary: TextBoundary): number {
74
+ let size = 0;
75
+ let end = 0;
76
+ for (const part of partsOf(text, boundary)) {
77
+ size += unit === "code-unit" ? part.length : unit === "code-point" ? [...part].length : 1;
78
+ if (size > room) break;
79
+ end += part.length;
80
+ }
81
+ return end;
82
+ }
83
+
84
+ /**
85
+ * This function gives the length of a text in a unit.
86
+ *
87
+ * - `code-unit` gives `text.length`.
88
+ * - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.
89
+ * - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the
90
+ * locale.
91
+ *
92
+ * @param text - The text.
93
+ * @param unit - The unit of the length. The default is `code-unit`.
94
+ * @returns The count of units in the text.
95
+ * @throws RangeError for a unit that is not in the type `TextUnit`.
96
+ */
97
+ export function textLength(text: string, unit: TextUnit = "code-unit"): number {
98
+ boundaryOf(unit, "code-point");
99
+ if (unit === "code-unit") return text.length;
100
+ let count = 0;
101
+ for (const _ of partsOf(text, unit)) count += 1;
102
+ return count;
103
+ }
104
+
105
+ /**
106
+ * This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or
107
+ * fewer, with the mark.
108
+ *
109
+ * - A text with `max` units or fewer comes back as it is, with no mark.
110
+ * - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,
111
+ * an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair
112
+ * whole.
113
+ * - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter
114
+ * than `max`.
115
+ * - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units
116
+ * or fewer.
117
+ *
118
+ * @param text - The text to cut.
119
+ * @param max - The most units in the result. It is an integer of 0 or more.
120
+ * @param options - The unit, the boundary and the mark.
121
+ * @returns The text, or the start of the text with the mark at the end.
122
+ * @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.
123
+ */
124
+ export function truncate(text: string, max: number, options: TruncateOptions = {}): string {
125
+ const { unit = "code-unit", mark = "…" } = options;
126
+ const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
127
+ checkCount(max, "max");
128
+ // The count of code units is the largest count. Thus a text with `max` code units or fewer fits in each unit.
129
+ if (text.length <= max || (unit !== "code-unit" && endOf(text, max, unit, unit) === text.length)) return text;
130
+ const end = textLength(mark, unit) <= max ? mark : "";
131
+ // A grapheme of the text can join a grapheme of the mark. A join gives fewer graphemes, never more (UAX #29).
132
+ return text.slice(0, endOf(text, max - textLength(end, unit), unit, boundary)) + end;
133
+ }
134
+
135
+ /**
136
+ * This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`
137
+ * units or fewer.
138
+ *
139
+ * - A text with `width` units or more comes back as it is. The function does not cut a text.
140
+ * - The fill goes again and again. The last copy of the fill can be a part of the fill, as in
141
+ * `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a
142
+ * grapheme by default.
143
+ * - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.
144
+ *
145
+ * @param text - The text.
146
+ * @param width - The length of the result with the fill. It is an integer of 0 or more.
147
+ * @param options - The unit, the boundary, the fill and the side.
148
+ * @returns The text with the fill.
149
+ * @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary
150
+ * or side.
151
+ */
152
+ export function pad(text: string, width: number, options: PadOptions = {}): string {
153
+ const { unit = "code-unit", fill = " ", side = "end" } = options;
154
+ const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
155
+ checkCount(width, "width");
156
+ check(side === "start" || side === "end" || side === "both", `side is ${String(side)}, not start, end or both`);
157
+ const size = textLength(fill, unit);
158
+ check(size > 0, "fill is an empty text");
159
+ const missing = width - textLength(text, unit);
160
+ if (missing <= 0) return text;
161
+ const fillOf = (count: number): string => {
162
+ const copies = Math.floor(count / size);
163
+ return fill.repeat(copies) + fill.slice(0, endOf(fill, count - copies * size, unit, boundary));
164
+ };
165
+ const start = side === "start" ? missing : side === "end" ? 0 : Math.floor(missing / 2);
166
+ return fillOf(start) + text + fillOf(missing - start);
167
+ }