@tpmjs/official-tos-readability 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2025 TPMJS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,50 @@
1
+ import * as ai from 'ai';
2
+
3
+ /**
4
+ * ToS Readability Tool for TPMJS
5
+ * Analyzes Terms of Service for readability, complexity, and consumer-friendliness
6
+ */
7
+ /**
8
+ * Input interface for ToS readability analysis
9
+ */
10
+ interface TOSReadabilityInput {
11
+ tosText: string;
12
+ }
13
+ /**
14
+ * Represents a problematic section in the ToS
15
+ */
16
+ interface ProblematicSection {
17
+ text: string;
18
+ issue: string;
19
+ severity: 'low' | 'medium' | 'high';
20
+ suggestion: string;
21
+ }
22
+ /**
23
+ * Readability metrics for the ToS
24
+ */
25
+ interface ReadabilityMetrics {
26
+ fleschReadingEase: number;
27
+ fleschKincaidGrade: number;
28
+ averageSentenceLength: number;
29
+ averageWordLength: number;
30
+ complexWordPercentage: number;
31
+ }
32
+ /**
33
+ * Output interface for ToS analysis
34
+ */
35
+ interface TOSAnalysis {
36
+ metrics: ReadabilityMetrics;
37
+ overallScore: number;
38
+ readabilityLevel: 'excellent' | 'good' | 'fair' | 'poor' | 'very poor';
39
+ estimatedReadingTimeMinutes: number;
40
+ problematicSections: ProblematicSection[];
41
+ recommendations: string[];
42
+ summary: string;
43
+ }
44
+ /**
45
+ * ToS Readability Tool
46
+ * Analyzes Terms of Service for readability, complexity, and consumer-friendliness
47
+ */
48
+ declare const tosReadabilityTool: ai.Tool<TOSReadabilityInput, TOSAnalysis>;
49
+
50
+ export { type ProblematicSection, type ReadabilityMetrics, type TOSAnalysis, tosReadabilityTool as default, tosReadabilityTool };
package/dist/index.js ADDED
@@ -0,0 +1,200 @@
1
+ import { tool, jsonSchema } from 'ai';
2
+
3
+ // src/index.ts
4
+ function calculateFleschReadingEase(totalSentences, totalWords, totalSyllables) {
5
+ if (totalSentences === 0 || totalWords === 0) return 0;
6
+ const avgSentenceLength = totalWords / totalSentences;
7
+ const avgSyllablesPerWord = totalSyllables / totalWords;
8
+ return 206.835 - 1.015 * avgSentenceLength - 84.6 * avgSyllablesPerWord;
9
+ }
10
+ function calculateFleschKincaidGrade(totalSentences, totalWords, totalSyllables) {
11
+ if (totalSentences === 0 || totalWords === 0) return 0;
12
+ const avgSentenceLength = totalWords / totalSentences;
13
+ const avgSyllablesPerWord = totalSyllables / totalWords;
14
+ return 0.39 * avgSentenceLength + 11.8 * avgSyllablesPerWord - 15.59;
15
+ }
16
+ function countSyllables(word) {
17
+ word = word.toLowerCase().trim();
18
+ if (word.length <= 3) return 1;
19
+ word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, "");
20
+ word = word.replace(/^y/, "");
21
+ const matches = word.match(/[aeiouy]{1,2}/g);
22
+ return matches ? matches.length : 1;
23
+ }
24
+ function isComplexWord(word) {
25
+ return countSyllables(word) >= 3;
26
+ }
27
+ function identifyProblematicSections(text) {
28
+ const sections = [];
29
+ const sentences = text.match(/[^.!?]+[.!?]+/g) || [];
30
+ sentences.forEach((sentence) => {
31
+ const words = sentence.trim().split(/\s+/).filter((w) => w.length > 0);
32
+ if (words.length > 40) {
33
+ sections.push({
34
+ text: sentence.trim().substring(0, 200) + (sentence.length > 200 ? "..." : ""),
35
+ issue: "Excessively long sentence",
36
+ severity: "high",
37
+ suggestion: "Break this sentence into multiple shorter sentences for better clarity"
38
+ });
39
+ }
40
+ });
41
+ const problematicPatterns = [
42
+ {
43
+ pattern: /\b(notwithstanding|aforementioned|hereinafter|thereof|wherein)\b/gi,
44
+ issue: "Legal jargon",
45
+ severity: "medium",
46
+ suggestion: "Replace legal jargon with plain language"
47
+ },
48
+ {
49
+ pattern: /\b(may|might|could)\s+(?:be\s+)?(?:deemed|considered|interpreted)/gi,
50
+ issue: "Vague or ambiguous language",
51
+ severity: "high",
52
+ suggestion: "Use clear, definitive language instead of vague terms"
53
+ },
54
+ {
55
+ pattern: /\b(?:we|company)\s+(?:reserve|retain)\s+the\s+right\s+to\s+(?:change|modify|alter)/gi,
56
+ issue: "Unilateral modification clause",
57
+ severity: "high",
58
+ suggestion: "Specify conditions and notice requirements for changes"
59
+ },
60
+ {
61
+ pattern: /\b(?:you\s+agree\s+to\s+waive|waiver\s+of)/gi,
62
+ issue: "Rights waiver",
63
+ severity: "high",
64
+ suggestion: "Clearly explain what rights are being waived and why"
65
+ }
66
+ ];
67
+ problematicPatterns.forEach(({ pattern, issue, severity, suggestion }) => {
68
+ const matches = text.match(pattern);
69
+ if (matches) {
70
+ const context = text.substring(
71
+ Math.max(0, text.indexOf(matches[0]) - 50),
72
+ Math.min(text.length, text.indexOf(matches[0]) + 150)
73
+ );
74
+ sections.push({
75
+ text: context,
76
+ issue,
77
+ severity,
78
+ suggestion
79
+ });
80
+ }
81
+ });
82
+ return sections.slice(0, 10);
83
+ }
84
+ function analyzeToS(tosText) {
85
+ if (!tosText || tosText.trim().length === 0) {
86
+ throw new Error("ToS text cannot be empty");
87
+ }
88
+ const cleanText = tosText.replace(/\s+/g, " ").trim();
89
+ const sentences = cleanText.match(/[^.!?]+[.!?]+/g) || [cleanText];
90
+ const totalSentences = sentences.length;
91
+ const words = cleanText.split(/\s+/).filter((w) => w.length > 0);
92
+ const totalWords = words.length;
93
+ let totalSyllables = 0;
94
+ let complexWords = 0;
95
+ words.forEach((word) => {
96
+ const syllableCount = countSyllables(word);
97
+ totalSyllables += syllableCount;
98
+ if (isComplexWord(word)) {
99
+ complexWords++;
100
+ }
101
+ });
102
+ const fleschReadingEase = calculateFleschReadingEase(totalSentences, totalWords, totalSyllables);
103
+ const fleschKincaidGrade = calculateFleschKincaidGrade(
104
+ totalSentences,
105
+ totalWords,
106
+ totalSyllables
107
+ );
108
+ const averageSentenceLength = totalWords / totalSentences;
109
+ const averageWordLength = words.reduce((sum, word) => sum + word.length, 0) / totalWords;
110
+ const complexWordPercentage = complexWords / totalWords * 100;
111
+ let readabilityLevel;
112
+ if (fleschReadingEase >= 70) readabilityLevel = "excellent";
113
+ else if (fleschReadingEase >= 60) readabilityLevel = "good";
114
+ else if (fleschReadingEase >= 50) readabilityLevel = "fair";
115
+ else if (fleschReadingEase >= 30) readabilityLevel = "poor";
116
+ else readabilityLevel = "very poor";
117
+ const overallScore = Math.max(
118
+ 0,
119
+ Math.min(100, (fleschReadingEase + (100 - fleschKincaidGrade * 5)) / 2)
120
+ );
121
+ const estimatedReadingTimeMinutes = Math.ceil(totalWords / 200);
122
+ const problematicSections = identifyProblematicSections(cleanText);
123
+ const recommendations = [];
124
+ if (fleschKincaidGrade > 12) {
125
+ recommendations.push(
126
+ "Simplify language to reduce the required reading grade level (currently college-level)"
127
+ );
128
+ }
129
+ if (averageSentenceLength > 25) {
130
+ recommendations.push(
131
+ "Reduce sentence length for better readability (current average: " + Math.round(averageSentenceLength) + " words)"
132
+ );
133
+ }
134
+ if (complexWordPercentage > 20) {
135
+ recommendations.push(
136
+ "Reduce use of complex words (currently " + complexWordPercentage.toFixed(1) + "% of text)"
137
+ );
138
+ }
139
+ if (problematicSections.length > 0) {
140
+ recommendations.push(
141
+ "Address " + problematicSections.length + " identified problematic sections"
142
+ );
143
+ }
144
+ if (totalWords > 5e3) {
145
+ recommendations.push(
146
+ "Consider condensing the document (currently " + totalWords + " words, " + estimatedReadingTimeMinutes + " min read)"
147
+ );
148
+ }
149
+ if (recommendations.length === 0) {
150
+ recommendations.push("ToS is generally well-written and consumer-friendly");
151
+ }
152
+ const summary = `This Terms of Service document has a Flesch Reading Ease score of ${fleschReadingEase.toFixed(1)} (${readabilityLevel}) and requires a ${fleschKincaidGrade.toFixed(1)} grade reading level. The document contains ${totalWords} words with an estimated reading time of ${estimatedReadingTimeMinutes} minutes. ${problematicSections.length} potentially problematic sections were identified.`;
153
+ return {
154
+ metrics: {
155
+ fleschReadingEase: Math.round(fleschReadingEase * 10) / 10,
156
+ fleschKincaidGrade: Math.round(fleschKincaidGrade * 10) / 10,
157
+ averageSentenceLength: Math.round(averageSentenceLength * 10) / 10,
158
+ averageWordLength: Math.round(averageWordLength * 10) / 10,
159
+ complexWordPercentage: Math.round(complexWordPercentage * 10) / 10
160
+ },
161
+ overallScore: Math.round(overallScore),
162
+ readabilityLevel,
163
+ estimatedReadingTimeMinutes,
164
+ problematicSections,
165
+ recommendations,
166
+ summary
167
+ };
168
+ }
169
+ var tosReadabilityTool = tool({
170
+ description: "Analyzes Terms of Service documents for readability, complexity, and consumer-friendliness. Calculates Flesch Reading Ease score, Flesch-Kincaid Grade Level, and other readability metrics. Identifies problematic sections such as legal jargon, vague language, unilateral modification clauses, and rights waivers. Returns detailed analysis with recommendations for improving clarity and accessibility.",
171
+ inputSchema: jsonSchema({
172
+ type: "object",
173
+ properties: {
174
+ tosText: {
175
+ type: "string",
176
+ description: "The full Terms of Service text to analyze"
177
+ }
178
+ },
179
+ required: ["tosText"],
180
+ additionalProperties: false
181
+ }),
182
+ execute: async ({ tosText }) => {
183
+ if (typeof tosText !== "string") {
184
+ throw new Error("ToS text must be a string");
185
+ }
186
+ if (tosText.trim().length === 0) {
187
+ throw new Error("ToS text cannot be empty");
188
+ }
189
+ try {
190
+ return analyzeToS(tosText);
191
+ } catch (error) {
192
+ throw new Error(
193
+ `Failed to analyze ToS readability: ${error instanceof Error ? error.message : String(error)}`
194
+ );
195
+ }
196
+ }
197
+ });
198
+ var index_default = tosReadabilityTool;
199
+
200
+ export { index_default as default, tosReadabilityTool };
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@tpmjs/official-tos-readability",
3
+ "version": "0.1.0",
4
+ "description": "Analyzes Terms of Service for readability, complexity, and consumer-friendliness",
5
+ "type": "module",
6
+ "keywords": [
7
+ "tpmjs",
8
+ "legal",
9
+ "tos",
10
+ "readability",
11
+ "analysis"
12
+ ],
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "devDependencies": {
23
+ "tsup": "^8.3.5",
24
+ "typescript": "^5.9.3",
25
+ "@tpmjs/tsconfig": "0.0.0"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/anthropics/tpmjs.git",
33
+ "directory": "packages/tools/official/tos-readability"
34
+ },
35
+ "homepage": "https://tpmjs.com",
36
+ "license": "MIT",
37
+ "tpmjs": {
38
+ "category": "legal",
39
+ "frameworks": [
40
+ "vercel-ai"
41
+ ],
42
+ "tools": [
43
+ {
44
+ "name": "tosReadabilityTool",
45
+ "description": "Analyzes Terms of Service for readability, complexity, and consumer-friendliness",
46
+ "parameters": [
47
+ {
48
+ "name": "tosText",
49
+ "type": "string",
50
+ "description": "Terms of Service text",
51
+ "required": true
52
+ }
53
+ ],
54
+ "returns": {
55
+ "type": "TOSAnalysis",
56
+ "description": "Readability analysis with scores and recommendations"
57
+ }
58
+ }
59
+ ]
60
+ },
61
+ "dependencies": {
62
+ "ai": "6.0.0-beta.124"
63
+ },
64
+ "scripts": {
65
+ "build": "tsup",
66
+ "dev": "tsup --watch",
67
+ "type-check": "tsc --noEmit",
68
+ "clean": "rm -rf dist .turbo"
69
+ }
70
+ }