1
+use serde::Serialize;
2
+use serde_json::{json, Map, Value};
3
+
4
+use crate::error::{Error, Result};
5
+
6
+/// Maximum `title` length, in characters.
7
+pub const TITLE_MAX_LEN: usize = 256;
8
+/// Maximum `description` length, in characters.
9
+pub const DESCRIPTION_MAX_LEN: usize = 10_000;
10
+/// Maximum `shortDescription` length, in characters.
11
+pub const SHORT_DESCRIPTION_MAX_LEN: usize = 1_000;
12
+/// Maximum `releaseNotes` length, in characters.
13
+pub const RELEASE_NOTES_MAX_LEN: usize = 1_500;
14
+/// Maximum number of `features`.
15
+pub const FEATURES_MAX_COUNT: usize = 20;
16
+/// Maximum length of one feature, in characters.
17
+pub const FEATURE_MAX_LEN: usize = 200;
18
+/// Maximum number of `keywords` (search terms).
19
+pub const KEYWORDS_MAX_COUNT: usize = 7;
20
+/// Maximum length of one search term, in characters.
21
+pub const KEYWORD_MAX_LEN: usize = 30;
22
+/// Maximum number of words across all search terms.
23
+pub const KEYWORDS_MAX_WORDS: usize = 21;
24
+
25
+/// The listing keys this crate edits. Unset fields are left alone.
26
+#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
27
+#[serde(rename_all = "camelCase")]
28
+pub struct ListingFields {
29
+ #[serde(skip_serializing_if = "Option::is_none")]
30
+ pub title: Option<String>,
31
+ #[serde(skip_serializing_if = "Option::is_none")]
32
+ pub short_description: Option<String>,
33
+ #[serde(skip_serializing_if = "Option::is_none")]
34
+ pub description: Option<String>,
35
+ #[serde(skip_serializing_if = "Option::is_none")]
36
+ pub release_notes: Option<String>,
37
+ #[serde(skip_serializing_if = "Option::is_none")]
38
+ pub features: Option<Vec<String>>,
39
+ #[serde(skip_serializing_if = "Option::is_none")]
40
+ pub keywords: Option<Vec<String>>,
41
+}
42
+
43
+fn chars(s: &str) -> usize {
44
+ s.chars().count()
45
+}
46
+
47
+impl ListingFields {
48
+ pub fn is_empty(&self) -> bool {
49
+ *self == Self::default()
50
+ }
51
+
52
+ /// Check the fields against the Store's limits. `Err` names the first
53
+ /// violation; `Ok` carries warnings (non-ASCII punctuation) to show.
54
+ pub fn validate(&self) -> std::result::Result<Vec<String>, String> {
55
+ let texts = [
56
+ ("title", &self.title, TITLE_MAX_LEN),
57
+ (
58
+ "shortDescription",
59
+ &self.short_description,
60
+ SHORT_DESCRIPTION_MAX_LEN,
61
+ ),
62
+ ("description", &self.description, DESCRIPTION_MAX_LEN),
63
+ ("releaseNotes", &self.release_notes, RELEASE_NOTES_MAX_LEN),
64
+ ];
65
+ for (name, value, max) in texts {
66
+ let len = value.as_deref().map_or(0, chars);
67
+ if len > max {
68
+ return Err(format!(
69
+ "{name} is {len} characters; the Microsoft Store accepts at most {max}"
70
+ ));
71
+ }
72
+ }
73
+ if let Some(features) = &self.features {
74
+ if features.len() > FEATURES_MAX_COUNT {
75
+ return Err(format!(
76
+ "features has {} entries; the Microsoft Store accepts at most {FEATURES_MAX_COUNT}",
77
+ features.len()
78
+ ));
79
+ }
80
+ if let Some((i, f)) = features
81
+ .iter()
82
+ .enumerate()
83
+ .find(|(_, f)| chars(f) > FEATURE_MAX_LEN)
84
+ {
85
+ return Err(format!(
86
+ "features[{i}] is {} characters; at most {FEATURE_MAX_LEN}",
87
+ chars(f)
88
+ ));
89
+ }
90
+ }
91
+ if let Some(keywords) = &self.keywords {
92
+ if keywords.len() > KEYWORDS_MAX_COUNT {
93
+ return Err(format!(
94
+ "keywords has {} entries; the Microsoft Store accepts at most {KEYWORDS_MAX_COUNT}",
95
+ keywords.len()
96
+ ));
97
+ }
98
+ if let Some((i, k)) = keywords
99
+ .iter()
100
+ .enumerate()
101
+ .find(|(_, k)| chars(k) > KEYWORD_MAX_LEN)
102
+ {
103
+ return Err(format!(
104
+ "keywords[{i}] is {} characters; at most {KEYWORD_MAX_LEN}",
105
+ chars(k)
106
+ ));
107
+ }
108
+ let words: usize = keywords.iter().map(|k| k.split_whitespace().count()).sum();
109
+ if words > KEYWORDS_MAX_WORDS {
110
+ return Err(format!(
111
+ "keywords hold {words} words in total; at most {KEYWORDS_MAX_WORDS}"
112
+ ));
113
+ }
114
+ }
115
+ Ok(self.ascii_warnings())
116
+ }
117
+
118
+ /// Em dashes, en dashes and curly quotes, which the repo's listing note
119
+ /// asks to keep out of store copy.
120
+ fn ascii_warnings(&self) -> Vec<String> {
121
+ let bad = |c: char| {
122
+ matches!(
123
+ c,
124
+ '\u{2014}' | '\u{2013}' | '\u{2018}' | '\u{2019}' | '\u{201C}' | '\u{201D}'
125
+ )
126
+ };
127
+ let mut out = Vec::new();
128
+ let mut check = |name: String, text: &str| {
129
+ if let Some(c) = text.chars().find(|c| bad(*c)) {
130
+ out.push(format!(
131
+ "{name} contains {c:?}; use plain ASCII punctuation"
132
+ ));
133
+ }
134
+ };
135
+ for (name, value) in [
136
+ ("title", &self.title),
137
+ ("shortDescription", &self.short_description),
138
+ ("description", &self.description),
139
+ ("releaseNotes", &self.release_notes),
140
+ ] {
141
+ if let Some(v) = value {
142
+ check(name.to_string(), v);
143
+ }
144
+ }
145
+ for (name, list) in [("features", &self.features), ("keywords", &self.keywords)] {
146
+ for (i, v) in list.iter().flatten().enumerate() {
147
+ check(format!("{name}[{i}]"), v);
148
+ }
149
+ }
150
+ out
151
+ }
152
+
153
+ /// Read these fields from a submission's `baseListing` for `locale`.
154
+ /// Fields the listing lacks come back `None`.
155
+ pub fn read(submission: &Value, locale: &str) -> Self {
156
+ let Some(base) = find_locale_key(submission, locale)
157
+ .and_then(|key| submission.pointer(&format!("/listings/{}/baseListing", escape(&key))))
158
+ else {
159
+ return Self::default();
160
+ };
161
+ let text = |k: &str| base.get(k).and_then(Value::as_str).map(str::to_string);
162
+ let list = |k: &str| {
163
+ base.get(k).and_then(Value::as_array).map(|a| {
164
+ a.iter()
165
+ .filter_map(|v| v.as_str().map(str::to_string))
166
+ .collect()
167
+ })
168
+ };
169
+ Self {
170
+ title: text("title"),
171
+ short_description: text("shortDescription"),
172
+ description: text("description"),
173
+ release_notes: text("releaseNotes"),
174
+ features: list("features"),
175
+ keywords: list("keywords"),
176
+ }
177
+ }
178
+
179
+ /// Replace only the set keys of `baseListing` for `locale`, creating the
180
+ /// locale when the submission lacks it. Every other key is untouched.
181
+ pub fn apply(&self, submission: &mut Value, locale: &str) -> Result<()> {
182
+ let listings = submission
183
+ .as_object_mut()
184
+ .ok_or_else(|| Error::Shape("submission is not an object".into()))?
185
+ .entry("listings")
186
+ .or_insert_with(|| json!({}))
187
+ .as_object_mut()
188
+ .ok_or_else(|| Error::Shape("listings is not an object".into()))?;
189
+ let key = listings
190
+ .keys()
191
+ .find(|k| k.eq_ignore_ascii_case(locale))
192
+ .cloned()
193
+ .unwrap_or_else(|| locale.to_ascii_lowercase());
194
+ let entry = listings
195
+ .entry(key)
196
+ .or_insert_with(|| json!({}))
197
+ .as_object_mut()
198
+ .ok_or_else(|| Error::Shape("listing is not an object".into()))?;
199
+ let base = entry
200
+ .entry("baseListing")
201
+ .or_insert_with(|| Value::Object(Map::new()))
202
+ .as_object_mut()
203
+ .ok_or_else(|| Error::Shape("baseListing is not an object".into()))?;
204
+ let mut set = |k: &str, v: Value| {
205
+ base.insert(k.to_string(), v);
206
+ };
207
+ if let Some(v) = &self.title {
208
+ set("title", json!(v));
209
+ }
210
+ if let Some(v) = &self.short_description {
211
+ set("shortDescription", json!(v));
212
+ }
213
+ if let Some(v) = &self.description {
214
+ set("description", json!(v));
215
+ }
216
+ if let Some(v) = &self.release_notes {
217
+ set("releaseNotes", json!(v));
218
+ }
219
+ if let Some(v) = &self.features {
220
+ set("features", json!(v));
221
+ }
222
+ if let Some(v) = &self.keywords {
223
+ set("keywords", json!(v));
224
+ }
225
+ Ok(())
226
+ }
227
+
228
+ /// Names of the fields set here whose stored value is not an exact match.
229
+ pub fn diff(&self, stored: &Self) -> Vec<&'static str> {
230
+ fn differs<T: PartialEq>(sent: &Option<T>, stored: &Option<T>) -> bool {
231
+ sent.as_ref().is_some_and(|s| stored.as_ref() != Some(s))
232
+ }
233
+ [
234
+ ("title", differs(&self.title, &stored.title)),
235
+ (
236
+ "shortDescription",
237
+ differs(&self.short_description, &stored.short_description),
238
+ ),
239
+ (
240
+ "description",
241
+ differs(&self.description, &stored.description),
242
+ ),
243
+ (
244
+ "releaseNotes",
245
+ differs(&self.release_notes, &stored.release_notes),
246
+ ),
247
+ ("features", differs(&self.features, &stored.features)),
248
+ ("keywords", differs(&self.keywords, &stored.keywords)),
249
+ ]
250
+ .into_iter()
251
+ .filter(|(_, d)| *d)
252
+ .map(|(n, _)| n)
253
+ .collect()
254
+ }
255
+}
256
+
257
+/// The key in `listings` matching `locale`, ignoring case (`en-us`/`en-US`).
258
+pub fn find_locale_key(submission: &Value, locale: &str) -> Option<String> {
259
+ submission
260
+ .get("listings")?
261
+ .as_object()?
262
+ .keys()
263
+ .find(|k| k.eq_ignore_ascii_case(locale))
264
+ .cloned()
265
+}
266
+
267
+/// Escape a JSON-pointer segment.
268
+fn escape(segment: &str) -> String {
269
+ segment.replace('~', "~0").replace('/', "~1")
270
+}
271
+
272
+#[cfg(test)]
273
+mod tests {
274
+ use super::*;
275
+
276
+ fn text(len: usize) -> Option<String> {
277
+ Some("x".repeat(len))
278
+ }
279
+
280
+ #[test]
281
+ fn each_text_field_over_its_limit_is_rejected_by_name() {
282
+ let cases = [
283
+ (
284
+ ListingFields {
285
+ title: text(257),
286
+ ..Default::default()
287
+ },
288
+ "title",
289
+ ),
290
+ (
291
+ ListingFields {
292
+ short_description: text(1001),
293
+ ..Default::default()
294
+ },
295
+ "shortDescription",
296
+ ),
297
+ (
298
+ ListingFields {
299
+ description: text(10_001),
300
+ ..Default::default()
301
+ },
302
+ "description",
303
+ ),
304
+ (
305
+ ListingFields {
306
+ release_notes: text(1501),
307
+ ..Default::default()
308
+ },
309
+ "releaseNotes",
310
+ ),
311
+ ];
312
+ for (fields, name) in cases {
313
+ let message = fields.validate().unwrap_err();
314
+ assert!(message.starts_with(name), "{message}");
315
+ }
316
+ }
317
+
318
+ #[test]
319
+ fn fields_at_their_limits_pass_and_lengths_count_characters() {
320
+ let fields = ListingFields {
321
+ title: Some("é".repeat(256)),
322
+ short_description: text(1000),
323
+ description: text(10_000),
324
+ release_notes: text(1500),
325
+ features: Some(vec!["x".repeat(200); 20]),
326
+ keywords: Some(vec!["a b c".into(); 7]),
327
+ };
328
+ assert!(fields.validate().unwrap().is_empty());
329
+ }
330
+
331
+ #[test]
332
+ fn list_limits_are_enforced() {
333
+ let too_many = ListingFields {
334
+ features: Some(vec!["f".into(); 21]),
335
+ ..Default::default()
336
+ };
337
+ assert!(too_many
338
+ .validate()
339
+ .unwrap_err()
340
+ .starts_with("features has 21"));
341
+ let long = ListingFields {
342
+ features: Some(vec!["x".repeat(201)]),
343
+ ..Default::default()
344
+ };
345
+ assert!(long.validate().unwrap_err().starts_with("features[0]"));
346
+ let terms = ListingFields {
347
+ keywords: Some(vec!["k".into(); 8]),
348
+ ..Default::default()
349
+ };
350
+ assert!(terms.validate().unwrap_err().starts_with("keywords has 8"));
351
+ let wide = ListingFields {
352
+ keywords: Some(vec!["x".repeat(31)]),
353
+ ..Default::default()
354
+ };
355
+ assert!(wide.validate().unwrap_err().starts_with("keywords[0]"));
356
+ let words = ListingFields {
357
+ keywords: Some(vec!["a b c d".into(); 6]),
358
+ ..Default::default()
359
+ };
360
+ assert!(words.validate().unwrap_err().contains("24 words"));
361
+ }
362
+
363
+ #[test]
364
+ fn dashes_and_curly_quotes_warn_without_failing() {
365
+ let fields = ListingFields {
366
+ title: Some("A \u{2014} B".into()),
367
+ features: Some(vec!["it\u{2019}s".into()]),
368
+ ..Default::default()
369
+ };
370
+ let warnings = fields.validate().unwrap();
371
+ assert_eq!(warnings.len(), 2);
372
+ assert!(warnings[0].starts_with("title"));
373
+ assert!(warnings[1].starts_with("features[0]"));
374
+ }
375
+
376
+ fn submission() -> Value {
377
+ json!({
378
+ "id": "1",
379
+ "applicationPackages": [{"fileName": "a.msix", "version": "1.3.1.0"}],
380
+ "pricing": {"trialPeriod": "NoFreeTrial"},
381
+ "listings": {
382
+ "en-us": {
383
+ "baseListing": {
384
+ "title": "Old",
385
+ "description": "old desc",
386
+ "images": [{"fileName": "s.png"}],
387
+ "copyrightAndTrademarkInfo": "c"
388
+ },
389
+ "platformOverrides": {}
390
+ },
391
+ "id": {"baseListing": {"title": "Judul"}}
392
+ }
393
+ })
394
+ }
395
+
396
+ #[test]
397
+ fn apply_replaces_only_the_set_keys_and_keeps_everything_else() {
398
+ let mut sub = submission();
399
+ let before = sub.clone();
400
+ ListingFields {
401
+ title: Some("New".into()),
402
+ features: Some(vec!["a".into()]),
403
+ ..Default::default()
404
+ }
405
+ .apply(&mut sub, "en-US")
406
+ .unwrap();
407
+ assert_eq!(sub["listings"]["en-us"]["baseListing"]["title"], "New");
408
+ assert_eq!(
409
+ sub["listings"]["en-us"]["baseListing"]["features"],
410
+ json!(["a"])
411
+ );
412
+ // Everything not named is byte-identical.
413
+ sub["listings"]["en-us"]["baseListing"]["title"] = json!("Old");
414
+ sub["listings"]["en-us"]["baseListing"]
415
+ .as_object_mut()
416
+ .unwrap()
417
+ .remove("features");
418
+ assert_eq!(sub, before);
419
+ }
420
+
421
+ #[test]
422
+ fn apply_creates_a_missing_locale_in_lowercase() {
423
+ let mut sub = submission();
424
+ ListingFields {
425
+ title: Some("Hi".into()),
426
+ ..Default::default()
427
+ }
428
+ .apply(&mut sub, "de-DE")
429
+ .unwrap();
430
+ assert_eq!(sub["listings"]["de-de"]["baseListing"]["title"], "Hi");
431
+ }
432
+
433
+ #[test]
434
+ fn read_and_diff_round_trip() {
435
+ let mut sub = submission();
436
+ let sent = ListingFields {
437
+ title: Some("New".into()),
438
+ keywords: Some(vec!["git".into()]),
439
+ ..Default::default()
440
+ };
441
+ sent.apply(&mut sub, "en-us").unwrap();
442
+ let stored = ListingFields::read(&sub, "EN-US");
443
+ assert!(sent.diff(&stored).is_empty());
444
+ assert_eq!(stored.description.as_deref(), Some("old desc"));
445
+ let other = ListingFields {
446
+ title: Some("New ".into()),
447
+ ..Default::default()
448
+ };
449
+ assert_eq!(other.diff(&stored), vec!["title"]);
450
+ }
451
+}