cletter 0.2.1__tar.gz

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.
@@ -0,0 +1,10 @@
1
+ /target/
2
+ node_modules/
3
+
4
+ # Generated release outputs
5
+ **/dist/
6
+ **/LICENSES/
7
+ !LICENSES/
8
+ *.tgz
9
+ __pycache__/
10
+ *.egg-info/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Julian Y. Richard Corbet
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.
cletter-0.2.1/PKG-INFO ADDED
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.5
2
+ Name: cletter
3
+ Version: 0.2.1
4
+ Summary: Locale-correct business correspondence: composes cgreet, cfarewell, cink and cdate
5
+ Project-URL: Homepage, https://github.com/corbet-labs/cletter#readme
6
+ Project-URL: Repository, https://github.com/corbet-labs/cletter
7
+ Project-URL: Issues, https://github.com/corbet-labs/cletter/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSES/Apache-2.0.txt
10
+ License-File: LICENSES/MIT.txt
11
+ Keywords: correspondence,i18n,locale
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: cdate<0.3,>=0.2.1
16
+ Requires-Dist: cfarewell<0.3,>=0.2.1
17
+ Requires-Dist: cgreet<0.3,>=0.2.1
18
+ Requires-Dist: cink<0.2,>=0.1.4
19
+ Description-Content-Type: text/markdown
20
+
21
+ # cletter
22
+
23
+ **Locale-correct correspondence, from salutation to closing.**
24
+
25
+ [![crates.io](https://img.shields.io/crates/v/cletter.svg)](https://crates.io/crates/cletter) [![npm](https://img.shields.io/npm/v/@corbet-labs/cletter.svg)](https://www.npmjs.com/package/@corbet-labs/cletter) [![Rust API](https://docs.rs/cletter/badge.svg)](https://docs.rs/cletter)
26
+
27
+ Compose a formal letter from deterministic rules: resolve a document locale, address a recipient, write an application subject, format the date, choose a closing, and prepare a handwritten signature image. Rust, JavaScript, and Python share the same conformance vectors.
28
+
29
+ ```js
30
+ import { salutation } from '@corbet-labs/cletter';
31
+
32
+ salutation('de-ch', 'Frau Dr. Müller');
33
+ // Sehr geehrte Frau Dr. Müller
34
+ ```
35
+
36
+ ## Install
37
+
38
+ | Environment | Command |
39
+ | --- | --- |
40
+ | Rust / Cargo | `cargo add cletter` |
41
+ | Node.js / npm | `npm install @corbet-labs/cletter` |
42
+ | pnpm | `pnpm add @corbet-labs/cletter` |
43
+ | Yarn | `yarn add @corbet-labs/cletter` |
44
+ | Bun | `bun add @corbet-labs/cletter` |
45
+ | Deno | `deno add npm:@corbet-labs/cletter` |
46
+
47
+ The 0.2.1 JavaScript distribution includes compiled ESM, CommonJS,
48
+ TypeScript declarations, and a standalone browser module. Node.js 20+ is
49
+ supported; no TypeScript loader is required.
50
+
51
+ ```js
52
+ // CommonJS
53
+ const { salutation } = require('@corbet-labs/cletter');
54
+ ```
55
+
56
+ ```html
57
+ <script type="module">
58
+ import { salutation } from 'https://cdn.jsdelivr.net/npm/@corbet-labs/cletter@0.2.1/dist/browser.js';
59
+ console.log(salutation('de-ch', 'Frau Dr. Müller'));
60
+ </script>
61
+ ```
62
+
63
+ Python wheels, source distributions, and CLI instructions are in the
64
+ [installation guide](https://github.com/corbet-labs/cletter/blob/main/docs/installation.md).
65
+ JSR publication and Typst availability are listed there explicitly.
66
+
67
+ ## Rust
68
+
69
+ ```rust
70
+ use cletter::{closing, long_date, resolve_locale, salutation};
71
+
72
+ let locale = resolve_locale(Some("de"), Some("Zürich, Zug"));
73
+ assert_eq!(salutation(&locale, "Frau Dr. Müller"), "Sehr geehrte Frau Dr. Müller");
74
+ assert_eq!(closing(&locale, None), "Freundliche Grüsse");
75
+ assert_eq!(long_date(&locale, 2026, 9, 7).as_deref(), Some("7. September 2026"));
76
+ ```
77
+
78
+ ## Python
79
+
80
+ ```python
81
+ from cletter import salutation
82
+
83
+ assert salutation("de-ch", "Frau Dr. Müller") == 'Sehr geehrte Frau Dr. Müller'
84
+ ```
85
+
86
+ ## API
87
+
88
+ | JavaScript / Python or Rust | Purpose |
89
+ | --- | --- |
90
+ | `resolveLocale` / `resolve_locale` | Language and location → document locale |
91
+ | `salutation`, `opening` | Recipient address or formal opening |
92
+ | `subject` | Application subject with optional prefix override |
93
+ | `closing` | Locale-specific valediction |
94
+ | `longDate` / `long_date` and other date helpers | Gregorian datelines |
95
+ | `applyOrtho` / `apply_ortho` | Explicit `ß` → `ss`, `ẞ` → `SS` for caller-selected `de-ch`/`de-li` prose |
96
+ | `orthographyIssues` / `orthography_issues` | Non-mutating matched source/replacement pairs |
97
+ | `orthographyReplacements` / `orthography_replacements` | Applicable spelling pairs from the shared table |
98
+ | `normalize`, `signatureSize` / `signature_size` | Signature-image preparation |
99
+ | `warnings` | Advisories for incomplete recipient details |
100
+
101
+ Openings and closings have 40 locale entries. Date formatting currently covers German and English variants; other dates fall back to English. Locale IDs are lowercase in tables and outputs; lookups accept mixed case and explicit overrides win. Subject defaults are for job applications; supply a prefix override for other correspondence. The library produces letter components; your application owns the body, layout, and PDF rendering. Spelling transformations require caller-selected prose: preserve exact names, quotations, URLs and source material; use diagnostics when those boundaries are unavailable.
102
+
103
+ The self-contained [Typst facade](https://github.com/corbet-labs/cletter/blob/main/typst/README.md) consumes the same greeting, closing and date helpers as the other ports.
104
+
105
+ ## Correspondence family
106
+
107
+ | Library | Responsibility |
108
+ | --- | --- |
109
+ | [cletter](https://github.com/corbet-labs/cletter) | Compose the correspondence helpers |
110
+ | [cgreet](https://github.com/corbet-labs/cgreet) | German salutations and titles |
111
+ | [cfarewell](https://github.com/corbet-labs/cfarewell) | Locale-specific closings |
112
+ | [cdate](https://github.com/corbet-labs/cdate) | Calendar-date formatting |
113
+ | [cink](https://github.com/corbet-labs/cink) | Handwritten signature images |
114
+
115
+
116
+ ## Development
117
+
118
+ Behavior is defined by [the locale tables](https://github.com/corbet-labs/cletter/tree/main/tables)
119
+ and [shared conformance vectors](https://github.com/corbet-labs/cletter/tree/main/tests/vectors).
120
+ Rust, JavaScript, and Python run the same vectors. Selected CI checks exercise
121
+ installed JavaScript tarballs, Python wheels and command-line entrypoints, and
122
+ Typst packages. Release validation records the actual runtime and platform;
123
+ Linux results do not establish native Windows or macOS coverage.
124
+ All five Rust crates forbid unsafe code in their own source.
125
+
126
+ See [the release guide](https://github.com/corbet-labs/cletter/blob/main/docs/releasing.md)
127
+ for generation, verification, and publication commands.
128
+
129
+ ## License
130
+
131
+ Copyright 2026 Julian Y. Richard Corbet. Licensed under [Apache-2.0](LICENSES/Apache-2.0.txt). Vendored dependencies retain their notices; `typst/vendor/cgreet/` offers MIT OR Apache-2.0 and the other components use Apache-2.0.
@@ -0,0 +1,111 @@
1
+ # cletter
2
+
3
+ **Locale-correct correspondence, from salutation to closing.**
4
+
5
+ [![crates.io](https://img.shields.io/crates/v/cletter.svg)](https://crates.io/crates/cletter) [![npm](https://img.shields.io/npm/v/@corbet-labs/cletter.svg)](https://www.npmjs.com/package/@corbet-labs/cletter) [![Rust API](https://docs.rs/cletter/badge.svg)](https://docs.rs/cletter)
6
+
7
+ Compose a formal letter from deterministic rules: resolve a document locale, address a recipient, write an application subject, format the date, choose a closing, and prepare a handwritten signature image. Rust, JavaScript, and Python share the same conformance vectors.
8
+
9
+ ```js
10
+ import { salutation } from '@corbet-labs/cletter';
11
+
12
+ salutation('de-ch', 'Frau Dr. Müller');
13
+ // Sehr geehrte Frau Dr. Müller
14
+ ```
15
+
16
+ ## Install
17
+
18
+ | Environment | Command |
19
+ | --- | --- |
20
+ | Rust / Cargo | `cargo add cletter` |
21
+ | Node.js / npm | `npm install @corbet-labs/cletter` |
22
+ | pnpm | `pnpm add @corbet-labs/cletter` |
23
+ | Yarn | `yarn add @corbet-labs/cletter` |
24
+ | Bun | `bun add @corbet-labs/cletter` |
25
+ | Deno | `deno add npm:@corbet-labs/cletter` |
26
+
27
+ The 0.2.1 JavaScript distribution includes compiled ESM, CommonJS,
28
+ TypeScript declarations, and a standalone browser module. Node.js 20+ is
29
+ supported; no TypeScript loader is required.
30
+
31
+ ```js
32
+ // CommonJS
33
+ const { salutation } = require('@corbet-labs/cletter');
34
+ ```
35
+
36
+ ```html
37
+ <script type="module">
38
+ import { salutation } from 'https://cdn.jsdelivr.net/npm/@corbet-labs/cletter@0.2.1/dist/browser.js';
39
+ console.log(salutation('de-ch', 'Frau Dr. Müller'));
40
+ </script>
41
+ ```
42
+
43
+ Python wheels, source distributions, and CLI instructions are in the
44
+ [installation guide](https://github.com/corbet-labs/cletter/blob/main/docs/installation.md).
45
+ JSR publication and Typst availability are listed there explicitly.
46
+
47
+ ## Rust
48
+
49
+ ```rust
50
+ use cletter::{closing, long_date, resolve_locale, salutation};
51
+
52
+ let locale = resolve_locale(Some("de"), Some("Zürich, Zug"));
53
+ assert_eq!(salutation(&locale, "Frau Dr. Müller"), "Sehr geehrte Frau Dr. Müller");
54
+ assert_eq!(closing(&locale, None), "Freundliche Grüsse");
55
+ assert_eq!(long_date(&locale, 2026, 9, 7).as_deref(), Some("7. September 2026"));
56
+ ```
57
+
58
+ ## Python
59
+
60
+ ```python
61
+ from cletter import salutation
62
+
63
+ assert salutation("de-ch", "Frau Dr. Müller") == 'Sehr geehrte Frau Dr. Müller'
64
+ ```
65
+
66
+ ## API
67
+
68
+ | JavaScript / Python or Rust | Purpose |
69
+ | --- | --- |
70
+ | `resolveLocale` / `resolve_locale` | Language and location → document locale |
71
+ | `salutation`, `opening` | Recipient address or formal opening |
72
+ | `subject` | Application subject with optional prefix override |
73
+ | `closing` | Locale-specific valediction |
74
+ | `longDate` / `long_date` and other date helpers | Gregorian datelines |
75
+ | `applyOrtho` / `apply_ortho` | Explicit `ß` → `ss`, `ẞ` → `SS` for caller-selected `de-ch`/`de-li` prose |
76
+ | `orthographyIssues` / `orthography_issues` | Non-mutating matched source/replacement pairs |
77
+ | `orthographyReplacements` / `orthography_replacements` | Applicable spelling pairs from the shared table |
78
+ | `normalize`, `signatureSize` / `signature_size` | Signature-image preparation |
79
+ | `warnings` | Advisories for incomplete recipient details |
80
+
81
+ Openings and closings have 40 locale entries. Date formatting currently covers German and English variants; other dates fall back to English. Locale IDs are lowercase in tables and outputs; lookups accept mixed case and explicit overrides win. Subject defaults are for job applications; supply a prefix override for other correspondence. The library produces letter components; your application owns the body, layout, and PDF rendering. Spelling transformations require caller-selected prose: preserve exact names, quotations, URLs and source material; use diagnostics when those boundaries are unavailable.
82
+
83
+ The self-contained [Typst facade](https://github.com/corbet-labs/cletter/blob/main/typst/README.md) consumes the same greeting, closing and date helpers as the other ports.
84
+
85
+ ## Correspondence family
86
+
87
+ | Library | Responsibility |
88
+ | --- | --- |
89
+ | [cletter](https://github.com/corbet-labs/cletter) | Compose the correspondence helpers |
90
+ | [cgreet](https://github.com/corbet-labs/cgreet) | German salutations and titles |
91
+ | [cfarewell](https://github.com/corbet-labs/cfarewell) | Locale-specific closings |
92
+ | [cdate](https://github.com/corbet-labs/cdate) | Calendar-date formatting |
93
+ | [cink](https://github.com/corbet-labs/cink) | Handwritten signature images |
94
+
95
+
96
+ ## Development
97
+
98
+ Behavior is defined by [the locale tables](https://github.com/corbet-labs/cletter/tree/main/tables)
99
+ and [shared conformance vectors](https://github.com/corbet-labs/cletter/tree/main/tests/vectors).
100
+ Rust, JavaScript, and Python run the same vectors. Selected CI checks exercise
101
+ installed JavaScript tarballs, Python wheels and command-line entrypoints, and
102
+ Typst packages. Release validation records the actual runtime and platform;
103
+ Linux results do not establish native Windows or macOS coverage.
104
+ All five Rust crates forbid unsafe code in their own source.
105
+
106
+ See [the release guide](https://github.com/corbet-labs/cletter/blob/main/docs/releasing.md)
107
+ for generation, verification, and publication commands.
108
+
109
+ ## License
110
+
111
+ Copyright 2026 Julian Y. Richard Corbet. Licensed under [Apache-2.0](LICENSES/Apache-2.0.txt). Vendored dependencies retain their notices; `typst/vendor/cgreet/` offers MIT OR Apache-2.0 and the other components use Apache-2.0.
@@ -0,0 +1,120 @@
1
+ """Locale-correct correspondence, composed from four focused libraries."""
2
+
3
+ import re
4
+ from cdate import is_valid_date, long_date, medium_date, month_year, short_date
5
+ from cfarewell import available_locales, closing
6
+ from cgreet import (Region, de_honorific_warning, de_salutation, parse_region,
7
+ recipient_salutation_warning, region_uses_comma,
8
+ salutation_honorific, salutation_last_name, salutation_surname,
9
+ salutation_titles)
10
+ from cink import (DecodedImage, default_max_pixels, exceeds_limits, image_snippet,
11
+ normalize, scale_to_fit, signature_size, supported_formats)
12
+ from ._tables import TABLES
13
+
14
+ _LOCALES = TABLES["locales"]
15
+ _COUNTRIES = TABLES["countries"]
16
+ __all__ = ["normalize_language", "country_from_location", "resolve_locale", "region_for",
17
+ "opening", "subject", "salutation", "apply_ortho", "orthography_replacements", "orthography_issues", "warnings",
18
+ "is_valid_date", "long_date", "medium_date", "month_year", "short_date",
19
+ "available_locales", "closing", "de_honorific_warning", "de_salutation",
20
+ "parse_region", "recipient_salutation_warning", "region_uses_comma",
21
+ "salutation_honorific", "salutation_last_name", "salutation_surname",
22
+ "salutation_titles", "default_max_pixels", "exceeds_limits", "image_snippet",
23
+ "normalize", "scale_to_fit", "signature_size", "supported_formats"]
24
+
25
+
26
+ def normalize_language(value: str) -> str | None:
27
+ """Normalize mixed case and underscores to a supported lowercase locale ID."""
28
+ lower = value.strip().replace("_", "-").lower()
29
+ if lower in _LOCALES["supported"]:
30
+ return lower
31
+ base = lower.split("-", 1)[0]
32
+ return base if base in _LOCALES["supported"] else None
33
+
34
+
35
+ def country_from_location(location: str) -> str | None:
36
+ """Look up country keywords, then Swiss canton names in a location."""
37
+ text = location.lower().strip()
38
+ if not text:
39
+ return None
40
+ for keyword, code in _COUNTRIES["keywords"].items():
41
+ if keyword in text:
42
+ return code
43
+ for part in re.split("[,;]", text):
44
+ if part.strip() in _COUNTRIES["cantons"]:
45
+ return "CH"
46
+ return None
47
+
48
+
49
+ def resolve_locale(language: str | None = None, location: str | None = None) -> str:
50
+ """Resolve language and an optional location into one document locale."""
51
+ normalized = normalize_language(language) if language is not None else None
52
+ normalized = normalized or "en"
53
+ base = normalized.split("-", 1)[0]
54
+ country = country_from_location(location) if location is not None else None
55
+ return normalized if country is None else _LOCALES["variants"].get(base, {}).get(country, base)
56
+
57
+
58
+ def _entry(locale: str) -> dict:
59
+ lower = locale.lower()
60
+ key = lower if lower in _LOCALES["locales"] else lower.split("-", 1)[0]
61
+ if key not in _LOCALES["locales"]:
62
+ key = _LOCALES["fallback"]
63
+ return _LOCALES["locales"][key]
64
+
65
+
66
+ def region_for(locale: str) -> Region | None:
67
+ """cgreet region for a German-language locale, otherwise None."""
68
+ return parse_region(_entry(locale).get("region", ""))
69
+
70
+
71
+ def opening(locale: str, name: str | None = None, override_opening: str | None = None) -> str:
72
+ """Named opening or formal address; an explicit override always wins."""
73
+ if override_opening is not None:
74
+ return override_opening
75
+ entry = _entry(locale)
76
+ clean = name.strip() if name is not None else ""
77
+ return entry["named"].replace("{name}", clean) if clean else entry["formal"]
78
+
79
+
80
+ def subject(locale: str, title: str | None = None, prefix_override: str | None = None) -> str:
81
+ """Subject prefix plus title, or the locale's unsolicited-application subject."""
82
+ entry = _entry(locale)
83
+ clean = title.strip() if title is not None else ""
84
+ prefix = entry["subject_prefix"] if prefix_override is None else prefix_override
85
+ return prefix + " " + clean if clean else entry["subject_unsolicited"]
86
+
87
+
88
+ def salutation(locale: str, name: str) -> str:
89
+ """Use cgreet for German locales and the named opening elsewhere."""
90
+ region = region_for(locale)
91
+ return de_salutation(name, region) if region is not None else opening(locale, name)
92
+
93
+
94
+ def orthography_replacements(locale: str) -> list[list[str]]:
95
+ """Return a copy of the locale's literal replacement pairs in table order."""
96
+ return [pair.copy() for pair in _LOCALES["orthography_replacements"]] if _entry(locale)["use_ss"] else []
97
+
98
+
99
+ def orthography_issues(locale: str, text: str) -> list[list[str]]:
100
+ """Report applicable pairs once, without changing caller-selected prose."""
101
+ return [pair for pair in orthography_replacements(locale) if pair[0] in text]
102
+
103
+
104
+ def apply_ortho(locale: str, text: str) -> str:
105
+ """Apply spelling substitutions to prose; callers exclude names/quotes/URLs/sources.
106
+
107
+ Opening, subject, closing and overrides are never transformed implicitly.
108
+ Use orthography_issues when a protected-content boundary is not available.
109
+ """
110
+ for source, replacement in orthography_replacements(locale):
111
+ text = text.replace(source, replacement)
112
+ return text
113
+
114
+
115
+ def warnings(location: str, locale: str, name: str) -> list[str]:
116
+ """Nonblocking advisories for a recipient name."""
117
+ items = [recipient_salutation_warning(location, name)]
118
+ if region_for(locale) is not None:
119
+ items.append(de_honorific_warning(location, name))
120
+ return [item for item in items if item is not None]
@@ -0,0 +1,50 @@
1
+ """JSON command-line bridge for callers in any programming language."""
2
+ import argparse
3
+ import base64
4
+ import dataclasses
5
+ import json
6
+ import sys
7
+ import cletter as api
8
+
9
+
10
+ def _json_default(value):
11
+ if dataclasses.is_dataclass(value):
12
+ return dataclasses.asdict(value)
13
+ if isinstance(value, bytes):
14
+ return base64.b64encode(value).decode("ascii")
15
+ raise TypeError(f"Cannot serialize {type(value).__name__}")
16
+
17
+
18
+ def _reject_constant(value):
19
+ raise ValueError(f"{value} is not a JSON number")
20
+
21
+
22
+ def main():
23
+ parser = argparse.ArgumentParser(description="Call cletter functions with JSON arguments.")
24
+ parser.add_argument("function", choices=api.__all__)
25
+ parser.add_argument("arguments", nargs="?", default="[]", help="JSON array of positional arguments or object of keyword arguments; '-' reads UTF-8 stdin")
26
+ args = parser.parse_args()
27
+ try:
28
+ values = json.loads(sys.stdin.buffer.read().decode("utf-8") if args.arguments == "-" else args.arguments, parse_constant=_reject_constant)
29
+ if not isinstance(values, (list, dict)):
30
+ raise ValueError("arguments must be a JSON array or object")
31
+ # Image operations accept the JSON object returned by normalize.
32
+ if args.function in ("exceeds_limits", "scale_to_fit", "signature_size"):
33
+ raw = values[0] if isinstance(values, list) else values["image"]
34
+ if isinstance(raw, dict):
35
+ raw = dict(raw)
36
+ raw["bytes"] = base64.b64decode(raw["bytes"], validate=True)
37
+ image = api.DecodedImage(**raw)
38
+ if isinstance(values, list):
39
+ values[0] = image
40
+ else:
41
+ values["image"] = image
42
+ fn = getattr(api, args.function)
43
+ result = fn(*values) if isinstance(values, list) else fn(**values)
44
+ print(json.dumps(result, default=_json_default, ensure_ascii=True, allow_nan=False))
45
+ except (ValueError, TypeError, KeyError, IndexError, AttributeError, OverflowError) as error:
46
+ parser.error(str(error))
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
@@ -0,0 +1,359 @@
1
+ # Generated by scripts/sync-python.py; edit tables/*.json instead.
2
+ TABLES = {'countries': {'keywords': {'switzerland': 'CH',
3
+ 'schweiz': 'CH',
4
+ 'suisse': 'CH',
5
+ 'svizzera': 'CH',
6
+ 'germany': 'DE',
7
+ 'deutschland': 'DE',
8
+ 'austria': 'AT',
9
+ 'österreich': 'AT',
10
+ 'oesterreich': 'AT',
11
+ 'united kingdom': 'GB',
12
+ 'uk': 'GB',
13
+ 'britain': 'GB',
14
+ 'england': 'GB',
15
+ 'united states': 'US',
16
+ 'usa': 'US',
17
+ 'france': 'FR',
18
+ 'frankreich': 'FR',
19
+ 'italy': 'IT',
20
+ 'italien': 'IT',
21
+ 'italia': 'IT',
22
+ 'brazil': 'BR',
23
+ 'brasil': 'BR',
24
+ 'brasilien': 'BR',
25
+ 'mexico': 'MX',
26
+ 'mexiko': 'MX',
27
+ 'méxico': 'MX',
28
+ 'netherlands': 'NL',
29
+ 'niederlande': 'NL',
30
+ 'belgium': 'BE',
31
+ 'belgien': 'BE',
32
+ 'belgique': 'BE',
33
+ 'australia': 'AU',
34
+ 'australien': 'AU',
35
+ 'portugal': 'PT',
36
+ 'spain': 'ES',
37
+ 'spanien': 'ES',
38
+ 'españa': 'ES',
39
+ 'liechtenstein': 'LI'},
40
+ 'cantons': ['zürich',
41
+ 'zurich',
42
+ 'zh',
43
+ 'bern',
44
+ 'be',
45
+ 'luzern',
46
+ 'lucerne',
47
+ 'lu',
48
+ 'uri',
49
+ 'ur',
50
+ 'schwyz',
51
+ 'sz',
52
+ 'obwalden',
53
+ 'ow',
54
+ 'nidwalden',
55
+ 'nw',
56
+ 'glarus',
57
+ 'gl',
58
+ 'zug',
59
+ 'zg',
60
+ 'freiburg',
61
+ 'fribourg',
62
+ 'fr',
63
+ 'solothurn',
64
+ 'so',
65
+ 'basel-stadt',
66
+ 'bs',
67
+ 'basel-landschaft',
68
+ 'bl',
69
+ 'schaffhausen',
70
+ 'sh',
71
+ 'appenzell ausserrhoden',
72
+ 'ar',
73
+ 'appenzell innerrhoden',
74
+ 'ai',
75
+ 'st. gallen',
76
+ 'sg',
77
+ 'graubünden',
78
+ 'graubuenden',
79
+ 'gr',
80
+ 'aargau',
81
+ 'ag',
82
+ 'thurgau',
83
+ 'tg',
84
+ 'ticino',
85
+ 'ti',
86
+ 'vaud',
87
+ 'vd',
88
+ 'valais',
89
+ 'wallis',
90
+ 'vs',
91
+ 'neuchâtel',
92
+ 'neuchatel',
93
+ 'ne',
94
+ 'genève',
95
+ 'geneve',
96
+ 'geneva',
97
+ 'ge',
98
+ 'jura',
99
+ 'ju']},
100
+ 'locales': {'locales': {'de': {'formal': 'Sehr geehrte Damen und Herren,',
101
+ 'named': 'Sehr geehrte/r {name},',
102
+ 'subject_prefix': 'Bewerbung als',
103
+ 'subject_unsolicited': 'Initiativbewerbung',
104
+ 'use_ss': False,
105
+ 'region': 'de'},
106
+ 'de-ch': {'formal': 'Sehr geehrte Damen und Herren',
107
+ 'named': 'Sehr geehrte/r {name}',
108
+ 'subject_prefix': 'Bewerbung als',
109
+ 'subject_unsolicited': 'Initiativbewerbung',
110
+ 'use_ss': True,
111
+ 'region': 'ch'},
112
+ 'de-li': {'formal': 'Sehr geehrte Damen und Herren',
113
+ 'named': 'Sehr geehrte/r {name}',
114
+ 'subject_prefix': 'Bewerbung als',
115
+ 'subject_unsolicited': 'Initiativbewerbung',
116
+ 'use_ss': True,
117
+ 'region': 'li'},
118
+ 'de-at': {'formal': 'Sehr geehrte Damen und Herren,',
119
+ 'named': 'Sehr geehrte/r {name},',
120
+ 'subject_prefix': 'Bewerbung als',
121
+ 'subject_unsolicited': 'Initiativbewerbung',
122
+ 'use_ss': False,
123
+ 'region': 'at'},
124
+ 'en': {'formal': 'Dear Sir or Madam,',
125
+ 'named': 'Dear {name},',
126
+ 'subject_prefix': 'Application for',
127
+ 'subject_unsolicited': 'Speculative Application',
128
+ 'use_ss': False},
129
+ 'en-gb': {'formal': 'Dear Sir or Madam,',
130
+ 'named': 'Dear {name},',
131
+ 'subject_prefix': 'Application for',
132
+ 'subject_unsolicited': 'Speculative Application',
133
+ 'use_ss': False},
134
+ 'en-us': {'formal': 'Dear Hiring Manager,',
135
+ 'named': 'Dear {name},',
136
+ 'subject_prefix': 'Application for',
137
+ 'subject_unsolicited': 'Speculative Application',
138
+ 'use_ss': False},
139
+ 'fr': {'formal': 'Madame, Monsieur,',
140
+ 'named': 'Cher/Chère {name},',
141
+ 'subject_prefix': 'Candidature au poste de',
142
+ 'subject_unsolicited': 'Candidature spontanée',
143
+ 'use_ss': False},
144
+ 'fr-ch': {'formal': 'Madame, Monsieur,',
145
+ 'named': 'Cher/Chère {name},',
146
+ 'subject_prefix': 'Candidature au poste de',
147
+ 'subject_unsolicited': 'Candidature spontanée',
148
+ 'use_ss': False},
149
+ 'it': {'formal': 'Gentile Signora, Egregio Signore,',
150
+ 'named': 'Gentile {name},',
151
+ 'subject_prefix': 'Candidatura per',
152
+ 'subject_unsolicited': 'Candidatura spontanea',
153
+ 'use_ss': False},
154
+ 'it-ch': {'formal': 'Gentile Signora, Egregio Signore,',
155
+ 'named': 'Gentile {name},',
156
+ 'subject_prefix': 'Candidatura per',
157
+ 'subject_unsolicited': 'Candidatura spontanea',
158
+ 'use_ss': False},
159
+ 'es': {'formal': 'Estimado/a Señor/a,',
160
+ 'named': 'Estimado/a {name},',
161
+ 'subject_prefix': 'Solicitud para el puesto de',
162
+ 'subject_unsolicited': 'Candidatura espontánea',
163
+ 'use_ss': False},
164
+ 'es-mx': {'formal': 'Estimado/a Señor/a,',
165
+ 'named': 'Estimado/a {name},',
166
+ 'subject_prefix': 'Solicitud para el puesto de',
167
+ 'subject_unsolicited': 'Candidatura espontánea',
168
+ 'use_ss': False},
169
+ 'pt': {'formal': 'Prezado(a) Senhor(a),',
170
+ 'named': 'Prezado(a) {name},',
171
+ 'subject_prefix': 'Candidatura para',
172
+ 'subject_unsolicited': 'Candidatura espontânea',
173
+ 'use_ss': False},
174
+ 'pt-br': {'formal': 'Prezado(a) Senhor(a),',
175
+ 'named': 'Prezado(a) {name},',
176
+ 'subject_prefix': 'Candidatura para',
177
+ 'subject_unsolicited': 'Candidatura espontânea',
178
+ 'use_ss': False},
179
+ 'nl': {'formal': 'Geachte heer, mevrouw,',
180
+ 'named': 'Geachte {name},',
181
+ 'subject_prefix': 'Sollicitatie voor',
182
+ 'subject_unsolicited': 'Open sollicitatie',
183
+ 'use_ss': False},
184
+ 'nl-be': {'formal': 'Geachte heer, mevrouw,',
185
+ 'named': 'Geachte {name},',
186
+ 'subject_prefix': 'Sollicitatie voor',
187
+ 'subject_unsolicited': 'Open sollicitatie',
188
+ 'use_ss': False},
189
+ 'ar': {'formal': 'السيدة/السيد المحترم/ة،',
190
+ 'named': '{name} المحترم/ة،',
191
+ 'subject_prefix': 'طلب توظيف لمنصب',
192
+ 'subject_unsolicited': 'طلب توظيف عام',
193
+ 'use_ss': False},
194
+ 'bg': {'formal': 'Уважаеми Дами и Господа,',
195
+ 'named': 'Уважаеми {name},',
196
+ 'subject_prefix': 'Кандидатура за',
197
+ 'subject_unsolicited': 'Инициативна кандидатура',
198
+ 'use_ss': False},
199
+ 'cs': {'formal': 'Vážená paní, Vážený pane,',
200
+ 'named': 'Vážený/á {name},',
201
+ 'subject_prefix': 'Žádost o pozici',
202
+ 'subject_unsolicited': 'Žádost z vlastní iniciativy',
203
+ 'use_ss': False},
204
+ 'da': {'formal': 'Kære ansættelsesudvalg,',
205
+ 'named': 'Kære {name},',
206
+ 'subject_prefix': 'Ansøgning til',
207
+ 'subject_unsolicited': 'Uopfordret ansøgning',
208
+ 'use_ss': False},
209
+ 'el': {'formal': 'Αξιότιμε Κύριε/Κυρία,',
210
+ 'named': 'Αξιότιμε/η {name},',
211
+ 'subject_prefix': 'Αίτηση για τη θέση',
212
+ 'subject_unsolicited': 'Αυθόρμητη αίτηση',
213
+ 'use_ss': False},
214
+ 'et': {'formal': 'Lugupeetud daamid ja härrad,',
215
+ 'named': 'Lugupeetud {name},',
216
+ 'subject_prefix': 'Kandideerimine positsioonile',
217
+ 'subject_unsolicited': 'Avaldus omal algatusel',
218
+ 'use_ss': False},
219
+ 'fi': {'formal': 'Hyvä vastaanottaja,',
220
+ 'named': 'Hyvä {name},',
221
+ 'subject_prefix': 'Hakemus tehtävään',
222
+ 'subject_unsolicited': 'Avoin hakemus',
223
+ 'use_ss': False},
224
+ 'hu': {'formal': 'Tisztelt Hölgyem/Uram!',
225
+ 'named': 'Tisztelt {name}!',
226
+ 'subject_prefix': 'Jelentkezés',
227
+ 'subject_unsolicited': 'Nyílt jelentkezés',
228
+ 'use_ss': False},
229
+ 'id': {'formal': 'Dengan hormat,',
230
+ 'named': 'Yth. {name},',
231
+ 'subject_prefix': 'Lamaran untuk posisi',
232
+ 'subject_unsolicited': 'Lamaran terbuka',
233
+ 'use_ss': False},
234
+ 'ja': {'formal': '拝啓',
235
+ 'named': '{name}様',
236
+ 'subject_prefix': '応募:',
237
+ 'subject_unsolicited': '自主応募',
238
+ 'use_ss': False},
239
+ 'ko': {'formal': '담당자님께,',
240
+ 'named': '{name}님께,',
241
+ 'subject_prefix': '지원:',
242
+ 'subject_unsolicited': '자발적 지원',
243
+ 'use_ss': False},
244
+ 'lt': {'formal': 'Gerbiamas (-a),',
245
+ 'named': 'Gerbiamas (-a) {name},',
246
+ 'subject_prefix': 'Paraiška pozicijai',
247
+ 'subject_unsolicited': 'Iniciatyvinė paraiška',
248
+ 'use_ss': False},
249
+ 'lv': {'formal': 'Cienījamais kungs/kundze,',
250
+ 'named': 'Cienījamais/ā {name},',
251
+ 'subject_prefix': 'Pieteikums uz vakanci',
252
+ 'subject_unsolicited': 'Iniciatīvas pieteikums',
253
+ 'use_ss': False},
254
+ 'nb': {'formal': 'Kjære mottaker,',
255
+ 'named': 'Kjære {name},',
256
+ 'subject_prefix': 'Søknad til stillingen som',
257
+ 'subject_unsolicited': 'Åpen søknad',
258
+ 'use_ss': False},
259
+ 'pl': {'formal': 'Szanowni Państwo,',
260
+ 'named': 'Szanowny/a {name},',
261
+ 'subject_prefix': 'Aplikacja na stanowisko',
262
+ 'subject_unsolicited': 'Aplikacja z własnej inicjatywy',
263
+ 'use_ss': False},
264
+ 'ro': {'formal': 'Stimată Doamnă/Stimate Domn,',
265
+ 'named': 'Stimate/ă {name},',
266
+ 'subject_prefix': 'Candidatură pentru',
267
+ 'subject_unsolicited': 'Candidatură spontană',
268
+ 'use_ss': False},
269
+ 'ru': {'formal': 'Уважаемые дамы и господа,',
270
+ 'named': 'Уважаемый/ая {name},',
271
+ 'subject_prefix': 'Заявка на должность',
272
+ 'subject_unsolicited': 'Инициативное заявление',
273
+ 'use_ss': False},
274
+ 'sk': {'formal': 'Vážená pani, Vážený pán,',
275
+ 'named': 'Vážený/á {name},',
276
+ 'subject_prefix': 'Žiadosť o pozíciu',
277
+ 'subject_unsolicited': 'Iniciatívna žiadosť',
278
+ 'use_ss': False},
279
+ 'sl': {'formal': 'Spoštovani,',
280
+ 'named': 'Spoštovani/a {name},',
281
+ 'subject_prefix': 'Prijava za delovno mesto',
282
+ 'subject_unsolicited': 'Odprta prijava',
283
+ 'use_ss': False},
284
+ 'sv': {'formal': 'Till den det berör,',
285
+ 'named': 'Bästa {name},',
286
+ 'subject_prefix': 'Ansökan till tjänsten som',
287
+ 'subject_unsolicited': 'Spontanansökan',
288
+ 'use_ss': False},
289
+ 'tr': {'formal': 'Sayın Yetkili,',
290
+ 'named': 'Sayın {name},',
291
+ 'subject_prefix': 'Başvuru:',
292
+ 'subject_unsolicited': 'Açık başvuru',
293
+ 'use_ss': False},
294
+ 'uk': {'formal': 'Шановні пані та панове,',
295
+ 'named': 'Шановний/а {name},',
296
+ 'subject_prefix': 'Заявка на посаду',
297
+ 'subject_unsolicited': 'Ініціативна заявка',
298
+ 'use_ss': False},
299
+ 'zh': {'formal': '尊敬的先生/女士:',
300
+ 'named': '尊敬的{name}:',
301
+ 'subject_prefix': '求职申请:',
302
+ 'subject_unsolicited': '自荐信',
303
+ 'use_ss': False}},
304
+ 'supported': ['ar',
305
+ 'bg',
306
+ 'cs',
307
+ 'da',
308
+ 'de',
309
+ 'de-at',
310
+ 'de-ch',
311
+ 'de-de',
312
+ 'de-li',
313
+ 'el',
314
+ 'en',
315
+ 'en-au',
316
+ 'en-gb',
317
+ 'en-us',
318
+ 'es',
319
+ 'es-es',
320
+ 'es-mx',
321
+ 'et',
322
+ 'fi',
323
+ 'fr',
324
+ 'fr-ch',
325
+ 'fr-fr',
326
+ 'hu',
327
+ 'id',
328
+ 'it',
329
+ 'it-ch',
330
+ 'it-it',
331
+ 'ja',
332
+ 'ko',
333
+ 'lt',
334
+ 'lv',
335
+ 'nb',
336
+ 'nl',
337
+ 'nl-be',
338
+ 'nl-nl',
339
+ 'pl',
340
+ 'pt',
341
+ 'pt-br',
342
+ 'pt-pt',
343
+ 'ro',
344
+ 'ru',
345
+ 'sk',
346
+ 'sl',
347
+ 'sv',
348
+ 'tr',
349
+ 'uk',
350
+ 'zh'],
351
+ 'fallback': 'en',
352
+ 'variants': {'de': {'CH': 'de-ch', 'DE': 'de-de', 'AT': 'de-at', 'LI': 'de-li'},
353
+ 'fr': {'CH': 'fr-ch', 'FR': 'fr-fr'},
354
+ 'it': {'CH': 'it-ch', 'IT': 'it-it'},
355
+ 'en': {'GB': 'en-gb', 'US': 'en-us', 'AU': 'en-au'},
356
+ 'pt': {'BR': 'pt-br', 'PT': 'pt-pt'},
357
+ 'es': {'MX': 'es-mx', 'ES': 'es-es'},
358
+ 'nl': {'BE': 'nl-be', 'NL': 'nl-nl'}},
359
+ 'orthography_replacements': [['ß', 'ss'], ['ẞ', 'SS']]}}
File without changes
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "cletter"
7
+ version = "0.2.1"
8
+ description = "Locale-correct business correspondence: composes cgreet, cfarewell, cink and cdate"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSES/*"]
12
+ requires-python = ">=3.10"
13
+ keywords = ["i18n", "correspondence", "locale"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent"]
15
+
16
+ dependencies = ["cgreet>=0.2.1,<0.3", "cfarewell>=0.2.1,<0.3", "cink>=0.1.4,<0.2", "cdate>=0.2.1,<0.3"]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/corbet-labs/cletter#readme"
20
+ Repository = "https://github.com/corbet-labs/cletter"
21
+ Issues = "https://github.com/corbet-labs/cletter/issues"
22
+
23
+ [project.scripts]
24
+ cletter = "cletter.__main__:main"
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["cletter"]
@@ -0,0 +1,58 @@
1
+ """Run canonical vectors against either the source port or an installed wheel."""
2
+ import base64
3
+ import importlib
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ ROOT = Path(__file__).resolve().parents[2]
9
+ if "--installed" not in sys.argv:
10
+ sys.path.insert(0, str(ROOT / "py"))
11
+ api = importlib.import_module("cletter")
12
+
13
+ ARGUMENTS = {
14
+ "region_parse": ["input"], "region_uses_comma": ["input"],
15
+ "salutation_last_name": ["input"], "salutation_honorific": ["input"],
16
+ "salutation_titles": ["input"], "salutation_surname": ["input"],
17
+ "de_salutation": ["input", "region"],
18
+ "recipient_salutation_warning": ["location", "input"],
19
+ "de_honorific_warning": ["location", "input"],
20
+ "closing": ["locale", "override"], "available_locales": [],
21
+ "long_date": ["locale", "year", "month", "day"],
22
+ "medium_date": ["locale", "year", "month", "day"],
23
+ "short_date": ["locale", "year", "month", "day"],
24
+ "month_year": ["locale", "year", "month"], "is_supported": ["locale"],
25
+ "supported_formats": [], "normalize": ["input"],
26
+ "exceeds_limits": ["image", "max_pixels"], "scale_to_fit": ["image", "max_pixels"],
27
+ "signature_size": ["image", "height_pt", "max_width_pt"],
28
+ "image_snippet": ["path", "height_pt", "width_pt"],
29
+ "resolve_locale": ["language", "location"],
30
+ "normalize_language": ["input"], "country_from_location": ["input"],
31
+ "orthography_replacements": ["locale"], "orthography_issues": ["locale", "text"],
32
+ "opening": ["locale", "person", "override"],
33
+ "subject": ["locale", "title", "prefix_override"],
34
+ "salutation": ["locale", "person"], "apply_ortho": ["locale", "text"],
35
+ "warnings": ["location", "locale", "person"],
36
+ }
37
+
38
+ files = sorted((ROOT / "tests/vectors").glob("*.json"))
39
+ assert files, "No conformance vectors"
40
+ count = 0
41
+ for file in files:
42
+ for vector in json.loads(file.read_text(encoding="utf-8")):
43
+ name = vector["fn"]
44
+ values = dict(vector)
45
+ if "fixture" in vector:
46
+ values["input"] = base64.b64encode((ROOT / "tests/fixtures" / vector["fixture"]).read_bytes()).decode("ascii")
47
+ if name != "normalize":
48
+ values["image"] = api.normalize(values["input"])
49
+ fn = getattr(api, "parse_region" if name == "region_parse" else name)
50
+ actual = fn(*(values.get(key) for key in ARGUMENTS[name]))
51
+ if name == "normalize" and actual is not None:
52
+ actual = {key: getattr(actual, key) for key in ("mime", "width", "height")}
53
+ if isinstance(actual, tuple):
54
+ actual = list(actual)
55
+ if actual != vector["expected"]:
56
+ raise AssertionError(f"{file.name} :: {vector['name']}: {actual!r} != {vector['expected']!r}")
57
+ count += 1
58
+ print(f"Python cletter: {count} vectors passed across {len(files)} files")
@@ -0,0 +1,106 @@
1
+ """Verify wheel/sdist contents and installed Python/console entrypoints.
2
+
3
+ Run with the interpreter in a fresh environment containing the wheel and its
4
+ declared dependencies. This script never adds the source package to sys.path.
5
+ """
6
+ import argparse
7
+ import base64
8
+ from email.parser import BytesParser
9
+ import importlib
10
+ import importlib.metadata
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import subprocess
15
+ import sys
16
+ import tarfile
17
+ import tempfile
18
+ import zipfile
19
+
20
+ ROOT = Path(__file__).resolve().parents[2]
21
+ PACKAGES = [path.name for path in (ROOT / "py").iterdir() if (path / "__init__.py").is_file()]
22
+ if len(PACKAGES) != 1:
23
+ raise RuntimeError("Expected exactly one source package")
24
+ NAME = PACKAGES[0]
25
+ CASES = {
26
+ "cgreet": ("de_salutation", ["Frau Dr. Müller", "ch"],
27
+ {"name": "Frau Dr. Müller", "region": "ch"}, "Sehr geehrte Frau Dr. Müller"),
28
+ "cfarewell": ("closing", ["DE-LI"], {"locale": "DE-LI"}, "Freundliche Grüsse"),
29
+ "cdate": ("long_date", ["EN-GB", 2026, 9, 7],
30
+ {"locale": "EN-GB", "year": 2026, "month": 9, "day": 7}, "7 September 2026"),
31
+ "cink": ("image_snippet", ["signature.png", 20],
32
+ {"path": "signature.png", "height_pt": 20}, '#image("signature.png", height: 20pt)'),
33
+ "cletter": ("salutation", ["DE-LI", "Frau Dr. Müller"],
34
+ {"locale": "DE-LI", "name": "Frau Dr. Müller"}, "Sehr geehrte Frau Dr. Müller"),
35
+ }
36
+
37
+
38
+ def check(condition, message):
39
+ if not condition:
40
+ raise AssertionError(message)
41
+
42
+
43
+ parser = argparse.ArgumentParser(description=__doc__)
44
+ parser.add_argument("--wheel", type=Path, required=True)
45
+ parser.add_argument("--sdist", type=Path, required=True)
46
+ args = parser.parse_args()
47
+ licenses = {path.name: path.read_bytes() for path in (ROOT / "LICENSES").iterdir() if path.is_file()}
48
+ check(bool(licenses), "Source licenses are missing")
49
+ with zipfile.ZipFile(args.wheel) as wheel:
50
+ files = wheel.namelist()
51
+ check(f"{NAME}/py.typed" in files, "Wheel is missing py.typed")
52
+ metadata_paths = [path for path in files if path.endswith(".dist-info/METADATA")]
53
+ check(len(metadata_paths) == 1, "Expected one wheel distribution")
54
+ metadata = BytesParser().parsebytes(wheel.read(metadata_paths[0]))
55
+ check(metadata["Name"] == NAME, "Wheel package name differs from repository")
56
+ check(metadata["License-Expression"] == "Apache-2.0", "Wheel must declare Apache-2.0")
57
+ check(not any("FSL" in path for path in files), "Wheel retains an obsolete license")
58
+ for name, expected in licenses.items():
59
+ check(any(path.endswith("/LICENSES/" + name) and wheel.read(path) == expected for path in files),
60
+ f"Wheel is missing the original {name}")
61
+ with tarfile.open(args.sdist, "r:gz") as sdist:
62
+ files = {member.name: member for member in sdist.getmembers() if member.isfile()}
63
+ for name, expected in licenses.items():
64
+ check(any(path.endswith("/LICENSES/" + name) and sdist.extractfile(member).read() == expected
65
+ for path, member in files.items()), f"Source distribution is missing {name}")
66
+
67
+ distribution = importlib.metadata.distribution(NAME)
68
+ check(distribution.version == metadata["Version"], "Installed version differs from wheel")
69
+ check(any(entry.group == "console_scripts" and entry.name == NAME and entry.value == f"{NAME}.__main__:main"
70
+ for entry in distribution.entry_points), "Missing console entrypoint metadata")
71
+ api = importlib.import_module(NAME)
72
+ check(not Path(api.__file__).resolve().is_relative_to(ROOT / "py"), "Imported source tree instead of installed wheel")
73
+ entrypoint = Path(sys.executable).parent / (NAME + (".exe" if os.name == "nt" else ""))
74
+ check(entrypoint.is_file(), "Installer did not create the console entrypoint")
75
+ function, positional, keywords, expected = CASES[NAME]
76
+
77
+ with tempfile.TemporaryDirectory(prefix=f"{NAME}-python-consumer-") as cwd:
78
+ def call(command, function, values, *, stdin=False, valid=True):
79
+ payload = values if isinstance(values, str) else json.dumps(values, ensure_ascii=False)
80
+ result = subprocess.run(command + [function, "-" if stdin else payload],
81
+ input=payload if stdin else None, cwd=cwd, text=True,
82
+ encoding="utf-8", capture_output=True, timeout=30)
83
+ if valid:
84
+ check(result.returncode == 0, result.stderr)
85
+ return json.loads(result.stdout)
86
+ check(result.returncode == 2 and not result.stdout and "Traceback" not in result.stderr,
87
+ f"Invalid arguments did not produce a clean CLI error: {result}")
88
+
89
+ for command in ([sys.executable, "-m", NAME], [str(entrypoint)]):
90
+ check(call(command, function, positional) == expected, "Positional JSON invocation failed")
91
+ check(call(command, function, keywords, stdin=True) == expected, "Keyword/stdin invocation failed")
92
+ call(command, function, "null", valid=False)
93
+ call(command, function, "[NaN]", valid=False)
94
+ call(command, function, [], valid=False)
95
+ if NAME in ("cink", "cletter"):
96
+ encoded = base64.b64encode(b'<svg xmlns="http://www.w3.org/2000/svg"/>').decode("ascii")
97
+ decoded = call([str(entrypoint)], "normalize", [encoded])
98
+ check(decoded["bytes"] == encoded and decoded["mime"] == "svg", "Image JSON output lost encoded bytes")
99
+ check(call([str(entrypoint)], "signature_size", {"image": decoded, "height_pt": 20}) is None,
100
+ "Image JSON output cannot be used as a subsequent input")
101
+ raster = {"mime": "png", "width": 1, "height": 1, "bytes": ""}
102
+ check(call([str(entrypoint)], "signature_size", {"image": raster, "height_pt": 10**400}) is None,
103
+ "An unrepresentable height escaped the JSON bridge")
104
+ check(call([str(entrypoint)], "signature_size", {"image": raster, "height_pt": 20, "max_width_pt": 10**400}) is None,
105
+ "An unrepresentable maximum width escaped the JSON bridge")
106
+ print(f"Python {NAME}: installed module, console JSON calls, wheel/sdist licenses and metadata passed")