@atproto/syntax 0.4.2 → 0.5.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE.txt +1 -1
  3. package/dist/at-identifier.d.ts +1 -0
  4. package/dist/at-identifier.d.ts.map +1 -1
  5. package/dist/at-identifier.js +9 -0
  6. package/dist/at-identifier.js.map +1 -1
  7. package/dist/aturi.d.ts +8 -0
  8. package/dist/aturi.d.ts.map +1 -1
  9. package/dist/aturi.js +31 -40
  10. package/dist/aturi.js.map +1 -1
  11. package/dist/aturi_validation.d.ts +3 -2
  12. package/dist/aturi_validation.d.ts.map +1 -1
  13. package/dist/aturi_validation.js +13 -3
  14. package/dist/aturi_validation.js.map +1 -1
  15. package/dist/datetime.d.ts +128 -11
  16. package/dist/datetime.d.ts.map +1 -1
  17. package/dist/datetime.js +205 -79
  18. package/dist/datetime.js.map +1 -1
  19. package/dist/did.d.ts +3 -2
  20. package/dist/did.d.ts.map +1 -1
  21. package/dist/did.js +18 -13
  22. package/dist/did.js.map +1 -1
  23. package/dist/handle.d.ts +4 -3
  24. package/dist/handle.d.ts.map +1 -1
  25. package/dist/handle.js +9 -9
  26. package/dist/handle.js.map +1 -1
  27. package/dist/index.d.ts +7 -5
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +11 -22
  30. package/dist/index.js.map +1 -1
  31. package/dist/language.d.ts +18 -0
  32. package/dist/language.d.ts.map +1 -0
  33. package/dist/language.js +30 -0
  34. package/dist/language.js.map +1 -0
  35. package/dist/nsid.d.ts +4 -4
  36. package/dist/nsid.d.ts.map +1 -1
  37. package/dist/nsid.js +9 -11
  38. package/dist/nsid.js.map +1 -1
  39. package/dist/recordkey.d.ts +2 -2
  40. package/dist/recordkey.d.ts.map +1 -1
  41. package/dist/recordkey.js +10 -10
  42. package/dist/recordkey.js.map +1 -1
  43. package/dist/tid.d.ts +2 -2
  44. package/dist/tid.d.ts.map +1 -1
  45. package/dist/tid.js +5 -5
  46. package/dist/tid.js.map +1 -1
  47. package/dist/uri.d.ts +3 -0
  48. package/dist/uri.d.ts.map +1 -0
  49. package/dist/uri.js +7 -0
  50. package/dist/uri.js.map +1 -0
  51. package/package.json +7 -4
  52. package/src/at-identifier.ts +12 -1
  53. package/src/aturi.ts +30 -1
  54. package/src/aturi_validation.ts +20 -4
  55. package/src/datetime.ts +271 -92
  56. package/src/did.ts +25 -15
  57. package/src/handle.ts +17 -13
  58. package/src/index.ts +7 -5
  59. package/src/language.ts +39 -0
  60. package/src/nsid.ts +13 -7
  61. package/src/recordkey.ts +14 -12
  62. package/src/tid.ts +7 -5
  63. package/src/uri.ts +5 -0
  64. package/tests/aturi.test.ts +50 -2
  65. package/tests/datetime.test.ts +148 -61
  66. package/tests/did.test.ts +1 -0
  67. package/tests/handle.test.ts +1 -0
  68. package/tests/language.test.ts +88 -0
  69. package/tests/nsid.test.ts +1 -0
  70. package/tests/recordkey.test.ts +1 -0
  71. package/tests/tid.test.ts +1 -0
  72. package/tsconfig.build.json +5 -2
  73. package/tsconfig.build.tsbuildinfo +1 -1
  74. package/tsconfig.tests.json +6 -4
  75. package/vitest.config.ts +5 -0
  76. package/jest.config.js +0 -7
  77. package/tsconfig.tests.tsbuildinfo +0 -1
package/dist/datetime.js CHANGED
@@ -1,108 +1,234 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InvalidDatetimeError = exports.normalizeDatetimeAlways = void 0;
4
- exports.ensureValidDatetime = ensureValidDatetime;
5
- exports.isValidDatetime = isValidDatetime;
3
+ exports.InvalidDatetimeError = void 0;
4
+ exports.assertAtprotoDate = assertAtprotoDate;
5
+ exports.asAtprotoDate = asAtprotoDate;
6
+ exports.isAtprotoDate = isAtprotoDate;
7
+ exports.ifAtprotoDate = ifAtprotoDate;
8
+ exports.assertDatetimeString = assertDatetimeString;
9
+ exports.ensureValidDatetime = assertDatetimeString;
10
+ exports.asDatetimeString = asDatetimeString;
11
+ exports.isDatetimeString = isDatetimeString;
12
+ exports.isValidDatetime = isDatetimeString;
13
+ exports.ifDatetimeString = ifDatetimeString;
14
+ exports.currentDatetimeString = currentDatetimeString;
15
+ exports.toDatetimeString = toDatetimeString;
6
16
  exports.normalizeDatetime = normalizeDatetime;
7
- /* Validates datetime string against atproto Lexicon 'datetime' format.
8
- * Syntax is described at: https://atproto.com/specs/lexicon#datetime
17
+ exports.normalizeDatetimeAlways = normalizeDatetimeAlways;
18
+ /**
19
+ * Indicates a date or string is not a valid representation of a datetime
20
+ * according to the atproto
21
+ * {@link https://atproto.com/specs/lexicon#datetime specification}.
9
22
  */
10
- function ensureValidDatetime(dtStr) {
11
- const date = new Date(dtStr);
12
- // must parse as ISO 8601; this also verifies semantics like month is not 13 or 00
13
- if (isNaN(date.getTime())) {
14
- throw new InvalidDatetimeError('datetime did not parse as ISO 8601');
15
- }
16
- if (date.toISOString().startsWith('-')) {
17
- throw new InvalidDatetimeError('datetime normalized to a negative time');
18
- }
19
- // regex and other checks for RFC-3339
20
- if (!/^[0-9]{4}-[01][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](.[0-9]{1,20})?(Z|([+-][0-2][0-9]:[0-5][0-9]))$/.test(dtStr)) {
21
- throw new InvalidDatetimeError("datetime didn't validate via regex");
22
- }
23
- if (dtStr.length > 64) {
24
- throw new InvalidDatetimeError('datetime is too long (64 chars max)');
25
- }
26
- if (dtStr.endsWith('-00:00')) {
27
- throw new InvalidDatetimeError('datetime can not use "-00:00" for UTC timezone');
28
- }
29
- if (dtStr.startsWith('000')) {
30
- throw new InvalidDatetimeError('datetime so close to year zero not allowed');
31
- }
23
+ class InvalidDatetimeError extends Error {
32
24
  }
33
- /* Same logic as ensureValidDatetime(), but returns a boolean instead of throwing an exception.
25
+ exports.InvalidDatetimeError = InvalidDatetimeError;
26
+ /**
27
+ * @see {@link AtprotoDate}
34
28
  */
35
- function isValidDatetime(dtStr) {
36
- try {
37
- ensureValidDatetime(dtStr);
29
+ function assertAtprotoDate(date) {
30
+ const res = parseDate(date);
31
+ if (!res.success) {
32
+ throw new InvalidDatetimeError(res.message);
38
33
  }
39
- catch (err) {
40
- if (err instanceof InvalidDatetimeError) {
41
- return false;
42
- }
43
- throw err;
34
+ }
35
+ /**
36
+ * @see {@link AtprotoDate}
37
+ */
38
+ function asAtprotoDate(date) {
39
+ assertAtprotoDate(date);
40
+ return date;
41
+ }
42
+ /**
43
+ * @see {@link AtprotoDate}
44
+ */
45
+ function isAtprotoDate(date) {
46
+ return parseDate(date).success;
47
+ }
48
+ /**
49
+ * @see {@link AtprotoDate}
50
+ */
51
+ function ifAtprotoDate(date) {
52
+ return isAtprotoDate(date) ? date : undefined;
53
+ }
54
+ /**
55
+ * Validates that a string is a valid {@link DatetimeString} format string,
56
+ * throwing an error if it is not.
57
+ *
58
+ * @throws InvalidDatetimeError if the input string does not meet the atproto 'datetime' format requirements.
59
+ * @see {@link DatetimeString}
60
+ */
61
+ function assertDatetimeString(input) {
62
+ const result = parseString(input);
63
+ if (!result.success) {
64
+ throw new InvalidDatetimeError(result.message);
44
65
  }
45
- return true;
46
66
  }
47
- /* Takes a flexible datetime string and normalizes representation.
67
+ /**
68
+ * Casts a string to a {@link DatetimeString} if it is a valid datetime format
69
+ * string, throwing an error if it is not.
48
70
  *
49
- * This function will work with any valid atproto datetime (eg, anything which isValidDatetime() is true for). It *additionally* is more flexible about accepting datetimes that don't comply to RFC 3339, or are missing timezone information, and normalizing them to a valid datetime.
71
+ * @throws InvalidDatetimeError if the input string does not meet the atproto 'datetime' format requirements.
72
+ * @see {@link DatetimeString}
73
+ */
74
+ function asDatetimeString(input) {
75
+ assertDatetimeString(input);
76
+ return input;
77
+ }
78
+ /**
79
+ * Checks if a string is a valid {@link DatetimeString} format string.
50
80
  *
51
- * One use-case is a consistent, sortable string. Another is to work with older invalid createdAt datetimes.
81
+ * @see {@link DatetimeString}
82
+ */
83
+ function isDatetimeString(input) {
84
+ return parseString(input).success;
85
+ }
86
+ /**
87
+ * Returns the input if it is a valid {@link DatetimeString} format string, or
88
+ * `undefined` if it is not.
52
89
  *
53
- * Successful output will be a valid atproto datetime with millisecond precision (3 sub-second digits) and UTC timezone with trailing 'Z' syntax. Throws `InvalidDatetimeError` if the input string could not be parsed as a datetime, even with permissive parsing.
90
+ * @see {@link DatetimeString}
91
+ */
92
+ function ifDatetimeString(input) {
93
+ return isDatetimeString(input) ? input : undefined;
94
+ }
95
+ /**
96
+ * Returns the current date and time as a {@link DatetimeString}.
54
97
  *
55
- * Expected output format: YYYY-MM-DDTHH:mm:ss.sssZ
98
+ * @see {@link DatetimeString}
99
+ */
100
+ function currentDatetimeString() {
101
+ return toDatetimeString(new Date());
102
+ }
103
+ /**
104
+ * Converts any {@link Date} into a {@link DatetimeString} if possible, throwing
105
+ * an error if the date is not a valid atproto datetime.
106
+ *
107
+ * This is short-hand for `asAtprotoDate(date).toISOString()`.
108
+ *
109
+ * @throws InvalidDatetimeError if the input date is not a valid atproto datetime (eg, it is too far in the future or past, or it normalizes to a negative year).
110
+ * @see {@link DatetimeString}
111
+ */
112
+ function toDatetimeString(date) {
113
+ return asAtprotoDate(date).toISOString();
114
+ }
115
+ /**
116
+ * Takes a flexible datetime string and normalizes its representation.
117
+ *
118
+ * This function will work with any valid value that can be parsed as a date. It
119
+ * *additionally* is more flexible about accepting datetimes that are missing
120
+ * timezone information, and normalizing them to a valid atproto datetime.
121
+ *
122
+ * One use-case is a consistent, sortable string. Another is to work with older
123
+ * invalid createdAt datetimes.
124
+ *
125
+ * @returns ISODatetimeString - a valid atproto datetime with millisecond precision (3 sub-second digits) and UTC timezone with trailing 'Z' syntax.
126
+ * @throws InvalidDatetimeError - if the input string could not be parsed as a datetime, even with permissive parsing.
56
127
  */
57
128
  function normalizeDatetime(dtStr) {
58
- if (isValidDatetime(dtStr)) {
59
- const outStr = new Date(dtStr).toISOString();
60
- if (isValidDatetime(outStr)) {
61
- return outStr;
62
- }
63
- }
64
- // check if this permissive datetime is missing a timezone
65
- if (!/.*(([+-]\d\d:?\d\d)|[a-zA-Z])$/.test(dtStr)) {
66
- const date = new Date(dtStr + 'Z');
67
- if (!isNaN(date.getTime())) {
68
- const tzStr = date.toISOString();
69
- if (isValidDatetime(tzStr)) {
70
- return tzStr;
71
- }
72
- }
73
- }
74
- // finally try parsing as simple datetime
129
+ // Parse the string as is
75
130
  const date = new Date(dtStr);
76
- if (isNaN(date.getTime())) {
77
- throw new InvalidDatetimeError('datetime did not parse as any timestamp format');
131
+ if (isAtprotoDate(date)) {
132
+ return date.toISOString();
78
133
  }
79
- const isoStr = date.toISOString();
80
- if (isValidDatetime(isoStr)) {
81
- return isoStr;
82
- }
83
- else {
84
- throw new InvalidDatetimeError('datetime normalized to invalid timestamp string');
134
+ // if dtStr is not a valid date, try parsing again with a timezone
135
+ if (isNaN(date.getTime()) && !/.*(([+-]\d\d:?\d\d)|[a-zA-Z])$/.test(dtStr)) {
136
+ const date = new Date(`${dtStr}Z`);
137
+ if (isAtprotoDate(date)) {
138
+ return date.toISOString();
139
+ }
85
140
  }
141
+ throw new InvalidDatetimeError('datetime did not parse as any timestamp format');
86
142
  }
87
- /* Variant of normalizeDatetime() which always returns a valid datetime strings.
143
+ /**
144
+ * Variant of {@link normalizeDatetime} which always returns a valid datetime
145
+ * string.
88
146
  *
89
- * If a InvalidDatetimeError is encountered, returns the UNIX epoch time as a UTC datetime (1970-01-01T00:00:00.000Z).
147
+ * If a {@link InvalidDatetimeError} is encountered, returns the UNIX epoch time
148
+ * as a UTC datetime (`1970-01-01T00:00:00.000Z`).
149
+ *
150
+ * @see {@link normalizeDatetime}
90
151
  */
91
- const normalizeDatetimeAlways = (dtStr) => {
152
+ function normalizeDatetimeAlways(dtStr) {
92
153
  try {
93
154
  return normalizeDatetime(dtStr);
94
155
  }
95
156
  catch (err) {
96
- if (err instanceof InvalidDatetimeError) {
97
- return new Date(0).toISOString();
98
- }
99
- throw err;
157
+ return '1970-01-01T00:00:00.000Z';
100
158
  }
101
- };
102
- exports.normalizeDatetimeAlways = normalizeDatetimeAlways;
103
- /* Indicates a datetime string did not pass full atproto Lexicon datetime string format checks.
159
+ }
160
+ const failure = (m) => ({ success: false, message: m });
161
+ const success = (v) => ({ success: true, value: v });
162
+ /**
163
+ * @see {@link https://www.rfc-editor.org/rfc/rfc3339#section-5.6 Internet Date/Time Format}
164
+ *
165
+ * @example
166
+ * ```abnf
167
+ * date-fullyear = 4DIGIT
168
+ * date-month = 2DIGIT ; 01-12
169
+ * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
170
+ * ; month/year
171
+ * time-hour = 2DIGIT ; 00-23
172
+ * time-minute = 2DIGIT ; 00-59
173
+ * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second
174
+ * ; rules
175
+ * time-secfrac = "." 1*DIGIT
176
+ * time-numoffset = ("+" / "-") time-hour ":" time-minute
177
+ * time-offset = "Z" / time-numoffset
178
+ * partial-time = time-hour ":" time-minute ":" time-second
179
+ * [time-secfrac]
180
+ * full-date = date-fullyear "-" date-month "-" date-mday
181
+ * full-time = partial-time time-offset
182
+ * date-time = full-date "T" full-time
183
+ * ```
104
184
  */
105
- class InvalidDatetimeError extends Error {
185
+ const DATETIME_REGEX = /^(?<full_year>[0-9]{4})-(?<date_month>0[1-9]|1[012])-(?<date_mday>[0-2][0-9]|3[01])T(?<time_hour>[0-1][0-9]|2[0-3]):(?<time_minute>[0-5][0-9]):(?<time_second>[0-5][0-9]|60)(?<time_secfrac>\.[0-9]+)?(?<time_offset>Z|(?<time_numoffset>[+-](?:[0-1][0-9]|2[0-3]):[0-5][0-9]))$/;
186
+ /**
187
+ * Validates that the input is a datetime string according to atproto Lexicon
188
+ * rules, and parses it into a Date object.
189
+ */
190
+ function parseString(input) {
191
+ // @NOTE Performing cheap tests first
192
+ if (typeof input !== 'string') {
193
+ return failure('datetime must be a string');
194
+ }
195
+ if (input.length > 64) {
196
+ return failure('datetime is too long (64 chars max)');
197
+ }
198
+ if (input.endsWith('-00:00')) {
199
+ return failure('datetime can not use "-00:00" for UTC timezone');
200
+ }
201
+ if (!DATETIME_REGEX.test(input)) {
202
+ return failure("datetime is not in a valid format (must match RFC 3339 & ISO 8601 with 'Z' or ±hh:mm timezone)");
203
+ }
204
+ // must parse as ISO 8601; this also verifies semantics like leap seconds and
205
+ // correct number of days in month, which the regex does not check for
206
+ const date = new Date(input);
207
+ return parseDate(date);
208
+ }
209
+ /**
210
+ * Ensures that a Date object represents a valid datetime according to atproto
211
+ * Lexicon rules. This ensures that `date.toISOString()` will produce a valid
212
+ * datetime string that can be used where {@link DatetimeString} is expected.
213
+ */
214
+ function parseDate(date) {
215
+ const fullYear = date.getUTCFullYear();
216
+ // Ensures that the date is valid. We could check isNaN(date.getTime()) here
217
+ // but since we'll check the year anyway, we just use that for the validity
218
+ // check since an invalid date will have NaN year.
219
+ if (Number.isNaN(fullYear)) {
220
+ return failure('datetime did not parse as ISO 8601');
221
+ }
222
+ // Ensure that the ISO string representation does not start with ±YYYYYY
223
+ if (fullYear < 0) {
224
+ return failure('datetime normalized to a negative time');
225
+ }
226
+ if (fullYear > 9999) {
227
+ return failure('datetime year is too far in the future');
228
+ }
229
+ if (fullYear < 10) {
230
+ return failure('datetime so close to year zero not allowed');
231
+ }
232
+ return success(date);
106
233
  }
107
- exports.InvalidDatetimeError = InvalidDatetimeError;
108
234
  //# sourceMappingURL=datetime.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"datetime.js","sourceRoot":"","sources":["../src/datetime.ts"],"names":[],"mappings":";;;AAcA,kDA8BC;AAID,0CAWC;AAYD,8CAkCC;AA9FD;;GAEG;AACH,SAAgB,mBAAmB,CACjC,KAAa;IAEb,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAA;IAC5B,kFAAkF;IAClF,IAAI,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QAC1B,MA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,2BASnC;AAED;GACG;AACH,MAAa,oBAAqB,SAAQ,KAAK;CAAG;AAAlD,oDAAkD","sourcesContent":["/** An ISO 8601 formatted datetime string (YYYY-MM-DDTHH:mm:ss.sssZ) */\nexport type DatetimeString =\n `${string}-${string}-${string}T${string}:${string}:${string}${'Z' | `+${string}` | `-${string}`}`\n\n// Allow date.toISOString() to be used where datetime format is expected\ndeclare global {\n interface Date {\n toISOString(): `${string}-${string}-${string}T${string}:${string}:${string}Z`\n }\n}\n\n/* Validates datetime string against atproto Lexicon 'datetime' format.\n * Syntax is described at: https://atproto.com/specs/lexicon#datetime\n */\nexport function ensureValidDatetime(\n dtStr: string,\n): asserts dtStr is DatetimeString {\n const date = new Date(dtStr)\n // must parse as ISO 8601; this also verifies semantics like month is not 13 or 00\n if (isNaN(date.getTime())) {\n throw new InvalidDatetimeError('datetime did not parse as ISO 8601')\n }\n if (date.toISOString().startsWith('-')) {\n throw new InvalidDatetimeError('datetime normalized to a negative time')\n }\n // regex and other checks for RFC-3339\n if (\n !/^[0-9]{4}-[01][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](.[0-9]{1,20})?(Z|([+-][0-2][0-9]:[0-5][0-9]))$/.test(\n dtStr,\n )\n ) {\n throw new InvalidDatetimeError(\"datetime didn't validate via regex\")\n }\n if (dtStr.length > 64) {\n throw new InvalidDatetimeError('datetime is too long (64 chars max)')\n }\n if (dtStr.endsWith('-00:00')) {\n throw new InvalidDatetimeError(\n 'datetime can not use \"-00:00\" for UTC timezone',\n )\n }\n if (dtStr.startsWith('000')) {\n throw new InvalidDatetimeError('datetime so close to year zero not allowed')\n }\n}\n\n/* Same logic as ensureValidDatetime(), but returns a boolean instead of throwing an exception.\n */\nexport function isValidDatetime(dtStr: string): dtStr is DatetimeString {\n try {\n ensureValidDatetime(dtStr)\n } catch (err) {\n if (err instanceof InvalidDatetimeError) {\n return false\n }\n throw err\n }\n\n return true\n}\n\n/* Takes a flexible datetime string and normalizes representation.\n *\n * This function will work with any valid atproto datetime (eg, anything which isValidDatetime() is true for). It *additionally* is more flexible about accepting datetimes that don't comply to RFC 3339, or are missing timezone information, and normalizing them to a valid datetime.\n *\n * One use-case is a consistent, sortable string. Another is to work with older invalid createdAt datetimes.\n *\n * Successful output will be a valid atproto datetime with millisecond precision (3 sub-second digits) and UTC timezone with trailing 'Z' syntax. Throws `InvalidDatetimeError` if the input string could not be parsed as a datetime, even with permissive parsing.\n *\n * Expected output format: YYYY-MM-DDTHH:mm:ss.sssZ\n */\nexport function normalizeDatetime(dtStr: string): DatetimeString {\n if (isValidDatetime(dtStr)) {\n const outStr = new Date(dtStr).toISOString()\n if (isValidDatetime(outStr)) {\n return outStr\n }\n }\n\n // check if this permissive datetime is missing a timezone\n if (!/.*(([+-]\\d\\d:?\\d\\d)|[a-zA-Z])$/.test(dtStr)) {\n const date = new Date(dtStr + 'Z')\n if (!isNaN(date.getTime())) {\n const tzStr = date.toISOString()\n if (isValidDatetime(tzStr)) {\n return tzStr\n }\n }\n }\n\n // finally try parsing as simple datetime\n const date = new Date(dtStr)\n if (isNaN(date.getTime())) {\n throw new InvalidDatetimeError(\n 'datetime did not parse as any timestamp format',\n )\n }\n const isoStr = date.toISOString()\n if (isValidDatetime(isoStr)) {\n return isoStr\n } else {\n throw new InvalidDatetimeError(\n 'datetime normalized to invalid timestamp string',\n )\n }\n}\n\n/* Variant of normalizeDatetime() which always returns a valid datetime strings.\n *\n * If a InvalidDatetimeError is encountered, returns the UNIX epoch time as a UTC datetime (1970-01-01T00:00:00.000Z).\n */\nexport const normalizeDatetimeAlways = (dtStr: string): DatetimeString => {\n try {\n return normalizeDatetime(dtStr)\n } catch (err) {\n if (err instanceof InvalidDatetimeError) {\n return new Date(0).toISOString()\n }\n throw err\n }\n}\n\n/* Indicates a datetime string did not pass full atproto Lexicon datetime string format checks.\n */\nexport class InvalidDatetimeError extends Error {}\n"]}
1
+ {"version":3,"file":"datetime.js","sourceRoot":"","sources":["../src/datetime.ts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E,2EAA2E;IAC3E,kDAAkD;IAClD,IAAI,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC,oCAAoC,CAAC,CAAA;IACtD,CAAC;IACD,wEAAwE;IACxE,IAAI,QAAQ,GAAG,CAAC,EAAE,CAAC;QACjB,OAAO,OAAO,CAAC,wCAAwC,CAAC,CAAA;IAC1D,CAAC;IACD,IAAI,QAAQ,GAAG,IAAI,EAAE,CAAC;QACpB,OAAO,OAAO,CAAC,wCAAwC,CAAC,CAAA;IAC1D,CAAC;IACD,IAAI,QAAQ,GAAG,EAAE,EAAE,CAAC;QAClB,OAAO,OAAO,CAAC,4CAA4C,CAAC,CAAA;IAC9D,CAAC;IACD,OAAO,OAAO,CAAC,IAAmB,CAAC,CAAA;AACrC,CAAC","sourcesContent":["/**\n * Indicates a date or string is not a valid representation of a datetime\n * according to the atproto\n * {@link https://atproto.com/specs/lexicon#datetime specification}.\n */\nexport class InvalidDatetimeError extends Error {}\n\n/**\n * A subset of {@link DatetimeString} that represent valid datetime strings with\n * the format: `YYYY-MM-DDTHH:mm:ss.sssZ`, as returned by `Date.toISOString()\n * for dates between the years 0000 and 9999.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString}\n */\nexport type ISODatetimeString =\n // @TODO Switch to branded types for more accurate type safety.\n `${string}-${string}-${string}T${string}:${string}:${string}.${string}Z`\n\n/**\n * Represents a {@link Date} that can be safely stringified into a valid atproto\n * {@link DatetimeString} using the {@link Date.toISOString toISOString()}\n * method.\n */\nexport interface AtprotoDate extends Date {\n toISOString(): ISODatetimeString\n}\n\n/**\n * @see {@link AtprotoDate}\n */\nexport function assertAtprotoDate(date: Date): asserts date is AtprotoDate {\n const res = parseDate(date)\n if (!res.success) {\n throw new InvalidDatetimeError(res.message)\n }\n}\n\n/**\n * @see {@link AtprotoDate}\n */\nexport function asAtprotoDate(date: Date): AtprotoDate {\n assertAtprotoDate(date)\n return date\n}\n\n/**\n * @see {@link AtprotoDate}\n */\nexport function isAtprotoDate(date: Date): date is AtprotoDate {\n return parseDate(date).success\n}\n\n/**\n * @see {@link AtprotoDate}\n */\nexport function ifAtprotoDate(date: Date): AtprotoDate | undefined {\n return isAtprotoDate(date) ? date : undefined\n}\n\n/**\n * Datetime strings in atproto data structures and API calls should meet the\n * {@link https://ijmacd.github.io/rfc3339-iso8601/ intersecting} requirements\n * of the RFC 3339, ISO 8601, and WHATWG HTML datetime standards.\n *\n * @note This literal template type is not accurate enough to ensure that a\n * string is a valid atproto datetime. The {@link DatetimeString} validation\n * functions ({@link assertDatetimeString}, {@link isDatetimeString}, etc)\n * should be used to validate that a string meets the atproto datetime\n * requirements, and the {@link toDatetimeString} function should be used to\n * convert a {@link Date} object into a valid {@link DatetimeString} string.\n *\n * @example \"2024-01-15T12:30:00Z\"\n * @example \"2024-01-15T12:30:00.000Z\"\n * @example \"2024-01-15T12:30:00+00:00\"\n * @example \"2024-01-15T11:30:00-01:00\"\n * @see {@link https://atproto.com/specs/lexicon#datetime atproto Lexicon datetime format}\n * @see {@link https://www.rfc-editor.org/rfc/rfc3339 RFC 3339}\n * @see {@link https://www.iso.org/iso-8601-date-and-time-format.html ISO 8601}\n */\nexport type DatetimeString =\n // @TODO Switch to branded types for more accurate type safety?\n | `${string}-${string}-${string}T${string}:${string}:${string}Z`\n | `${string}-${string}-${string}T${string}:${string}:${string}${'+' | '-'}${string}:${string}`\n\n/**\n * Validates that a string is a valid {@link DatetimeString} format string,\n * throwing an error if it is not.\n *\n * @throws InvalidDatetimeError if the input string does not meet the atproto 'datetime' format requirements.\n * @see {@link DatetimeString}\n */\nexport function assertDatetimeString<I>(\n input: I,\n): asserts input is I & DatetimeString {\n const result = parseString(input)\n if (!result.success) {\n throw new InvalidDatetimeError(result.message)\n }\n}\n\n/**\n * Casts a string to a {@link DatetimeString} if it is a valid datetime format\n * string, throwing an error if it is not.\n *\n * @throws InvalidDatetimeError if the input string does not meet the atproto 'datetime' format requirements.\n * @see {@link DatetimeString}\n */\nexport function asDatetimeString<I>(input: I): I & DatetimeString {\n assertDatetimeString(input)\n return input\n}\n\n/**\n * Checks if a string is a valid {@link DatetimeString} format string.\n *\n * @see {@link DatetimeString}\n */\nexport function isDatetimeString<I>(input: I): input is I & DatetimeString {\n return parseString(input).success\n}\n\n/**\n * Returns the input if it is a valid {@link DatetimeString} format string, or\n * `undefined` if it is not.\n *\n * @see {@link DatetimeString}\n */\nexport function ifDatetimeString<I>(\n input: I,\n): undefined | (I & DatetimeString) {\n return isDatetimeString(input) ? input : undefined\n}\n\n/**\n * Returns the current date and time as a {@link DatetimeString}.\n *\n * @see {@link DatetimeString}\n */\nexport function currentDatetimeString(): DatetimeString {\n return toDatetimeString(new Date())\n}\n\n/**\n * Converts any {@link Date} into a {@link DatetimeString} if possible, throwing\n * an error if the date is not a valid atproto datetime.\n *\n * This is short-hand for `asAtprotoDate(date).toISOString()`.\n *\n * @throws InvalidDatetimeError if the input date is not a valid atproto datetime (eg, it is too far in the future or past, or it normalizes to a negative year).\n * @see {@link DatetimeString}\n */\nexport function toDatetimeString(date: Date): DatetimeString {\n return asAtprotoDate(date).toISOString()\n}\n\n/**\n * Takes a flexible datetime string and normalizes its representation.\n *\n * This function will work with any valid value that can be parsed as a date. It\n * *additionally* is more flexible about accepting datetimes that are missing\n * timezone information, and normalizing them to a valid atproto datetime.\n *\n * One use-case is a consistent, sortable string. Another is to work with older\n * invalid createdAt datetimes.\n *\n * @returns ISODatetimeString - a valid atproto datetime with millisecond precision (3 sub-second digits) and UTC timezone with trailing 'Z' syntax.\n * @throws InvalidDatetimeError - if the input string could not be parsed as a datetime, even with permissive parsing.\n */\nexport function normalizeDatetime(dtStr: string): ISODatetimeString {\n // Parse the string as is\n const date = new Date(dtStr)\n if (isAtprotoDate(date)) {\n return date.toISOString()\n }\n\n // if dtStr is not a valid date, try parsing again with a timezone\n if (isNaN(date.getTime()) && !/.*(([+-]\\d\\d:?\\d\\d)|[a-zA-Z])$/.test(dtStr)) {\n const date = new Date(`${dtStr}Z`)\n if (isAtprotoDate(date)) {\n return date.toISOString()\n }\n }\n\n throw new InvalidDatetimeError(\n 'datetime did not parse as any timestamp format',\n )\n}\n\n/**\n * Variant of {@link normalizeDatetime} which always returns a valid datetime\n * string.\n *\n * If a {@link InvalidDatetimeError} is encountered, returns the UNIX epoch time\n * as a UTC datetime (`1970-01-01T00:00:00.000Z`).\n *\n * @see {@link normalizeDatetime}\n */\nexport function normalizeDatetimeAlways(dtStr: string): ISODatetimeString {\n try {\n return normalizeDatetime(dtStr)\n } catch (err) {\n return '1970-01-01T00:00:00.000Z'\n }\n}\n\n// Legacy exports (should we deprecate these ?)\nexport {\n assertDatetimeString as ensureValidDatetime,\n isDatetimeString as isValidDatetime,\n}\n\n// -----------------------------------------------------------------------------\n// ------------------------- Internal validation logic -------------------------\n// -----------------------------------------------------------------------------\n\n// Validation utils that allow avoiding try/catch for control flow (performance\n// optimization). Other syntax formats should also use this pattern to avoid\n// try/catch in their validation logic, at which point these utils can be moved\n// to a common internal utils.\ntype FailureResult = { success: false; message: string }\nconst failure = (m: string): FailureResult => ({ success: false, message: m })\ntype SuccessResult<V> = { success: true; value: V }\nconst success = <V>(v: V): SuccessResult<V> => ({ success: true, value: v })\ntype Result<V> = FailureResult | SuccessResult<V>\n\n/**\n * @see {@link https://www.rfc-editor.org/rfc/rfc3339#section-5.6 Internet Date/Time Format}\n *\n * @example\n * ```abnf\n * date-fullyear = 4DIGIT\n * date-month = 2DIGIT ; 01-12\n * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on\n * ; month/year\n * time-hour = 2DIGIT ; 00-23\n * time-minute = 2DIGIT ; 00-59\n * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second\n * ; rules\n * time-secfrac = \".\" 1*DIGIT\n * time-numoffset = (\"+\" / \"-\") time-hour \":\" time-minute\n * time-offset = \"Z\" / time-numoffset\n * partial-time = time-hour \":\" time-minute \":\" time-second\n * [time-secfrac]\n * full-date = date-fullyear \"-\" date-month \"-\" date-mday\n * full-time = partial-time time-offset\n * date-time = full-date \"T\" full-time\n * ```\n */\nconst DATETIME_REGEX =\n /^(?<full_year>[0-9]{4})-(?<date_month>0[1-9]|1[012])-(?<date_mday>[0-2][0-9]|3[01])T(?<time_hour>[0-1][0-9]|2[0-3]):(?<time_minute>[0-5][0-9]):(?<time_second>[0-5][0-9]|60)(?<time_secfrac>\\.[0-9]+)?(?<time_offset>Z|(?<time_numoffset>[+-](?:[0-1][0-9]|2[0-3]):[0-5][0-9]))$/\n\n/**\n * Validates that the input is a datetime string according to atproto Lexicon\n * rules, and parses it into a Date object.\n */\nfunction parseString(input: unknown): Result<AtprotoDate> {\n // @NOTE Performing cheap tests first\n if (typeof input !== 'string') {\n return failure('datetime must be a string')\n }\n if (input.length > 64) {\n return failure('datetime is too long (64 chars max)')\n }\n if (input.endsWith('-00:00')) {\n return failure('datetime can not use \"-00:00\" for UTC timezone')\n }\n if (!DATETIME_REGEX.test(input)) {\n return failure(\n \"datetime is not in a valid format (must match RFC 3339 & ISO 8601 with 'Z' or ±hh:mm timezone)\",\n )\n }\n\n // must parse as ISO 8601; this also verifies semantics like leap seconds and\n // correct number of days in month, which the regex does not check for\n const date = new Date(input)\n\n return parseDate(date)\n}\n\n/**\n * Ensures that a Date object represents a valid datetime according to atproto\n * Lexicon rules. This ensures that `date.toISOString()` will produce a valid\n * datetime string that can be used where {@link DatetimeString} is expected.\n */\nfunction parseDate(date: Date): Result<AtprotoDate> {\n const fullYear = date.getUTCFullYear()\n // Ensures that the date is valid. We could check isNaN(date.getTime()) here\n // but since we'll check the year anyway, we just use that for the validity\n // check since an invalid date will have NaN year.\n if (Number.isNaN(fullYear)) {\n return failure('datetime did not parse as ISO 8601')\n }\n // Ensure that the ISO string representation does not start with ±YYYYYY\n if (fullYear < 0) {\n return failure('datetime normalized to a negative time')\n }\n if (fullYear > 9999) {\n return failure('datetime year is too far in the future')\n }\n if (fullYear < 10) {\n return failure('datetime so close to year zero not allowed')\n }\n return success(date as AtprotoDate)\n}\n"]}
package/dist/did.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export type DidString<M extends string = string> = `did:${M}:${string}`;
2
- export declare function ensureValidDid(did: string): asserts did is DidString;
3
- export declare function ensureValidDidRegex(did: string): asserts did is DidString;
2
+ export declare function ensureValidDid<I extends string>(input: I): asserts input is I & DidString;
3
+ export declare function ensureValidDidRegex<I extends string>(input: I): asserts input is I & DidString;
4
+ export declare function isValidDid<I extends string>(input: I): input is I & DidString;
4
5
  export declare class InvalidDidError extends Error {
5
6
  }
6
7
  //# sourceMappingURL=did.d.ts.map
package/dist/did.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"did.d.ts","sourceRoot":"","sources":["../src/did.ts"],"names":[],"mappings":"AAcA,MAAM,MAAM,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,IAAI,MAAM,EAAE,CAAA;AAEvE,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,IAAI,SAAS,CA8BpE;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,IAAI,SAAS,CAUzE;AAED,qBAAa,eAAgB,SAAQ,KAAK;CAAG"}
1
+ {"version":3,"file":"did.d.ts","sourceRoot":"","sources":["../src/did.ts"],"names":[],"mappings":"AAcA,MAAM,MAAM,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,IAAI,MAAM,EAAE,CAAA;AAEvE,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,EAC7C,KAAK,EAAE,CAAC,GACP,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,CA8BhC;AAID,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,MAAM,EAClD,KAAK,EAAE,CAAC,GACP,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,CAUhC;AAED,wBAAgB,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,KAAK,IAAI,CAAC,GAAG,SAAS,CAE7E;AAED,qBAAa,eAAgB,SAAQ,KAAK;CAAG"}
package/dist/did.js CHANGED
@@ -16,38 +16,43 @@ Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.InvalidDidError = void 0;
17
17
  exports.ensureValidDid = ensureValidDid;
18
18
  exports.ensureValidDidRegex = ensureValidDidRegex;
19
- function ensureValidDid(did) {
20
- if (!did.startsWith('did:')) {
19
+ exports.isValidDid = isValidDid;
20
+ function ensureValidDid(input) {
21
+ if (!input.startsWith('did:')) {
21
22
  throw new InvalidDidError('DID requires "did:" prefix');
22
23
  }
24
+ if (input.length > 2048) {
25
+ throw new InvalidDidError('DID is too long (2048 chars max)');
26
+ }
27
+ if (input.endsWith(':') || input.endsWith('%')) {
28
+ throw new InvalidDidError('DID can not end with ":" or "%"');
29
+ }
23
30
  // check that all chars are boring ASCII
24
- if (!/^[a-zA-Z0-9._:%-]*$/.test(did)) {
31
+ if (!/^[a-zA-Z0-9._:%-]*$/.test(input)) {
25
32
  throw new InvalidDidError('Disallowed characters in DID (ASCII letters, digits, and a couple other characters only)');
26
33
  }
27
- const { length, 1: method } = did.split(':');
34
+ const { length, 1: method } = input.split(':');
28
35
  if (length < 3) {
29
36
  throw new InvalidDidError('DID requires prefix, method, and method-specific content');
30
37
  }
31
38
  if (!/^[a-z]+$/.test(method)) {
32
39
  throw new InvalidDidError('DID method must be lower-case letters');
33
40
  }
34
- if (did.endsWith(':') || did.endsWith('%')) {
35
- throw new InvalidDidError('DID can not end with ":" or "%"');
36
- }
37
- if (did.length > 2 * 1024) {
38
- throw new InvalidDidError('DID is too long (2048 chars max)');
39
- }
40
41
  }
41
- function ensureValidDidRegex(did) {
42
+ const DID_REGEX = /^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/;
43
+ function ensureValidDidRegex(input) {
42
44
  // simple regex to enforce most constraints via just regex and length.
43
45
  // hand wrote this regex based on above constraints
44
- if (!/^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/.test(did)) {
46
+ if (!DID_REGEX.test(input)) {
45
47
  throw new InvalidDidError("DID didn't validate via regex");
46
48
  }
47
- if (did.length > 2 * 1024) {
49
+ if (input.length > 2048) {
48
50
  throw new InvalidDidError('DID is too long (2048 chars max)');
49
51
  }
50
52
  }
53
+ function isValidDid(input) {
54
+ return input.length <= 2048 && DID_REGEX.test(input);
55
+ }
51
56
  class InvalidDidError extends Error {
52
57
  }
53
58
  exports.InvalidDidError = InvalidDidError;
package/dist/did.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"did.js","sourceRoot":"","sources":["../src/did.ts"],"names":[],"mappings":";AAAA,8BAA8B;AAC9B,iEAAiE;AACjE,+CAA+C;AAC/C,2CAA2C;AAC3C,wEAAwE;AACxE,sFAAsF;AACtF,qFAAqF;AACrF,wHAAwH;AACxH,8GAA8G;AAC9G,6FAA6F;AAC7F,qGAAqG;AACrG,mCAAmC;AACnC,oDAAoD;;;AAIpD,wCA8BC;AAED,kDAUC;AA1CD,SAAgB,cAAc,CAAC,GAAW;IACxC,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,eAAe,CAAC,4BAA4B,CAAC,CAAA;IACzD,CAAC;IAED,wCAAwC;IACxC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACrC,MAAM,IAAI,eAAe,CACvB,0FAA0F,CAC3F,CAAA;IACH,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC5C,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;QACf,MAAM,IAAI,eAAe,CACvB,0DAA0D,CAC3D,CAAA;IACH,CAAC;IAED,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7B,MAAM,IAAI,eAAe,CAAC,uCAAuC,CAAC,CAAA;IACpE,CAAC;IAED,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,eAAe,CAAC,iCAAiC,CAAC,CAAA;IAC9D,CAAC;IAED,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC;QAC1B,MAAM,IAAI,eAAe,CAAC,kCAAkC,CAAC,CAAA;IAC/D,CAAC;AACH,CAAC;AAED,SAAgB,mBAAmB,CAAC,GAAW;IAC7C,sEAAsE;IACtE,mDAAmD;IACnD,IAAI,CAAC,8CAA8C,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QAC9D,MAAM,IAAI,eAAe,CAAC,+BAA+B,CAAC,CAAA;IAC5D,CAAC;IAED,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC;QAC1B,MAAM,IAAI,eAAe,CAAC,kCAAkC,CAAC,CAAA;IAC/D,CAAC;AACH,CAAC;AAED,MAAa,eAAgB,SAAQ,KAAK;CAAG;AAA7C,0CAA6C","sourcesContent":["// Human-readable constraints:\n// - valid W3C DID (https://www.w3.org/TR/did-core/#did-syntax)\n// - entire URI is ASCII: [a-zA-Z0-9._:%-]\n// - always starts \"did:\" (lower-case)\n// - method name is one or more lower-case letters, followed by \":\"\n// - remaining identifier can have any of the above chars, but can not end in \":\"\n// - it seems that a bunch of \":\" can be included, and don't need spaces between\n// - \"%\" is used only for \"percent encoding\" and must be followed by two hex characters (and thus can't end in \"%\")\n// - query (\"?\") and fragment (\"#\") stuff is defined for \"DID URIs\", but not as part of identifier itself\n// - \"The current specification does not take a position on the maximum length of a DID\"\n// - in current atproto, only allowing did:plc and did:web. But not *forcing* this at lexicon layer\n// - hard length limit of 8KBytes\n// - not going to validate \"percent encoding\" here\n\nexport type DidString<M extends string = string> = `did:${M}:${string}`\n\nexport function ensureValidDid(did: string): asserts did is DidString {\n if (!did.startsWith('did:')) {\n throw new InvalidDidError('DID requires \"did:\" prefix')\n }\n\n // check that all chars are boring ASCII\n if (!/^[a-zA-Z0-9._:%-]*$/.test(did)) {\n throw new InvalidDidError(\n 'Disallowed characters in DID (ASCII letters, digits, and a couple other characters only)',\n )\n }\n\n const { length, 1: method } = did.split(':')\n if (length < 3) {\n throw new InvalidDidError(\n 'DID requires prefix, method, and method-specific content',\n )\n }\n\n if (!/^[a-z]+$/.test(method)) {\n throw new InvalidDidError('DID method must be lower-case letters')\n }\n\n if (did.endsWith(':') || did.endsWith('%')) {\n throw new InvalidDidError('DID can not end with \":\" or \"%\"')\n }\n\n if (did.length > 2 * 1024) {\n throw new InvalidDidError('DID is too long (2048 chars max)')\n }\n}\n\nexport function ensureValidDidRegex(did: string): asserts did is DidString {\n // simple regex to enforce most constraints via just regex and length.\n // hand wrote this regex based on above constraints\n if (!/^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/.test(did)) {\n throw new InvalidDidError(\"DID didn't validate via regex\")\n }\n\n if (did.length > 2 * 1024) {\n throw new InvalidDidError('DID is too long (2048 chars max)')\n }\n}\n\nexport class InvalidDidError extends Error {}\n"]}
1
+ {"version":3,"file":"did.js","sourceRoot":"","sources":["../src/did.ts"],"names":[],"mappings":";AAAA,8BAA8B;AAC9B,iEAAiE;AACjE,+CAA+C;AAC/C,2CAA2C;AAC3C,wEAAwE;AACxE,sFAAsF;AACtF,qFAAqF;AACrF,wHAAwH;AACxH,8GAA8G;AAC9G,6FAA6F;AAC7F,qGAAqG;AACrG,mCAAmC;AACnC,oDAAoD;;;AAIpD,wCAgCC;AAID,kDAYC;AAED,gCAEC;AApDD,SAAgB,cAAc,CAC5B,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C,CAAC,CAAA;IAC/D,CAAC;AACH,CAAC;AAED,SAAgB,UAAU,CAAmB,KAAQ;IACnD,OAAO,KAAK,CAAC,MAAM,IAAI,IAAI,IAAI,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;AACtD,CAAC;AAED,MAAa,eAAgB,SAAQ,KAAK;CAAG;AAA7C,0CAA6C","sourcesContent":["// Human-readable constraints:\n// - valid W3C DID (https://www.w3.org/TR/did-core/#did-syntax)\n// - entire URI is ASCII: [a-zA-Z0-9._:%-]\n// - always starts \"did:\" (lower-case)\n// - method name is one or more lower-case letters, followed by \":\"\n// - remaining identifier can have any of the above chars, but can not end in \":\"\n// - it seems that a bunch of \":\" can be included, and don't need spaces between\n// - \"%\" is used only for \"percent encoding\" and must be followed by two hex characters (and thus can't end in \"%\")\n// - query (\"?\") and fragment (\"#\") stuff is defined for \"DID URIs\", but not as part of identifier itself\n// - \"The current specification does not take a position on the maximum length of a DID\"\n// - in current atproto, only allowing did:plc and did:web. But not *forcing* this at lexicon layer\n// - hard length limit of 8KBytes\n// - not going to validate \"percent encoding\" here\n\nexport type DidString<M extends string = string> = `did:${M}:${string}`\n\nexport function ensureValidDid<I extends string>(\n input: I,\n): asserts input is I & DidString {\n if (!input.startsWith('did:')) {\n throw new InvalidDidError('DID requires \"did:\" prefix')\n }\n\n if (input.length > 2048) {\n throw new InvalidDidError('DID is too long (2048 chars max)')\n }\n\n if (input.endsWith(':') || input.endsWith('%')) {\n throw new InvalidDidError('DID can not end with \":\" or \"%\"')\n }\n\n // check that all chars are boring ASCII\n if (!/^[a-zA-Z0-9._:%-]*$/.test(input)) {\n throw new InvalidDidError(\n 'Disallowed characters in DID (ASCII letters, digits, and a couple other characters only)',\n )\n }\n\n const { length, 1: method } = input.split(':')\n if (length < 3) {\n throw new InvalidDidError(\n 'DID requires prefix, method, and method-specific content',\n )\n }\n\n if (!/^[a-z]+$/.test(method)) {\n throw new InvalidDidError('DID method must be lower-case letters')\n }\n}\n\nconst DID_REGEX = /^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/\n\nexport function ensureValidDidRegex<I extends string>(\n input: I,\n): asserts input is I & DidString {\n // simple regex to enforce most constraints via just regex and length.\n // hand wrote this regex based on above constraints\n if (!DID_REGEX.test(input)) {\n throw new InvalidDidError(\"DID didn't validate via regex\")\n }\n\n if (input.length > 2048) {\n throw new InvalidDidError('DID is too long (2048 chars max)')\n }\n}\n\nexport function isValidDid<I extends string>(input: I): input is I & DidString {\n return input.length <= 2048 && DID_REGEX.test(input)\n}\n\nexport class InvalidDidError extends Error {}\n"]}
package/dist/handle.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  export declare const INVALID_HANDLE = "handle.invalid";
2
2
  export type HandleString = `${string}.${string}`;
3
3
  export declare const DISALLOWED_TLDS: string[];
4
- export declare function ensureValidHandle(handle: string): asserts handle is HandleString;
5
- export declare function ensureValidHandleRegex(handle: string): asserts handle is HandleString;
4
+ export declare function ensureValidHandle<I extends string>(input: I): asserts input is I & HandleString;
5
+ export declare function ensureValidHandleRegex<I extends string>(input: I): asserts input is I & HandleString;
6
+ export declare function normalizeHandle(handle: HandleString): HandleString;
6
7
  export declare function normalizeHandle(handle: string): string;
7
8
  export declare function normalizeAndEnsureValidHandle(handle: string): HandleString;
8
- export declare function isValidHandle(handle: string): handle is HandleString;
9
+ export declare function isValidHandle<I extends string>(input: I): input is I & HandleString;
9
10
  export declare function isValidTld(handle: string): boolean;
10
11
  export declare class InvalidHandleError extends Error {
11
12
  }
@@ -1 +1 @@
1
- {"version":3,"file":"handle.d.ts","sourceRoot":"","sources":["../src/handle.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,cAAc,mBAAmB,CAAA;AAE9C,MAAM,MAAM,YAAY,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAA;AAMhD,eAAO,MAAM,eAAe,UAY3B,CAAA;AAqBD,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,GACb,OAAO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M,GAAG,YAAY,CAI1E;AAED,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,EAC5C,KAAK,EAAE,CAAC,GACP,KAAK,IAAI,CAAC,GAAG,YAAY,CAE3B;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAOlD;AAED,qBAAa,kBAAmB,SAAQ,KAAK;CAAG;AAChD,6BAA6B;AAC7B,qBAAa,mBAAoB,SAAQ,KAAK;CAAG;AACjD,6BAA6B;AAC7B,qBAAa,sBAAuB,SAAQ,KAAK;CAAG;AACpD,6BAA6B;AAC7B,qBAAa,qBAAsB,SAAQ,KAAK;CAAG"}
package/dist/handle.js CHANGED
@@ -44,15 +44,15 @@ exports.DISALLOWED_TLDS = [
44
44
  // - does not validate whether domain or TLD exists, or is a reserved or
45
45
  // special TLD (eg, .onion or .local)
46
46
  // - does not validate punycode
47
- function ensureValidHandle(handle) {
47
+ function ensureValidHandle(input) {
48
48
  // check that all chars are boring ASCII
49
- if (!/^[a-zA-Z0-9.-]*$/.test(handle)) {
49
+ if (!/^[a-zA-Z0-9.-]*$/.test(input)) {
50
50
  throw new InvalidHandleError('Disallowed characters in handle (ASCII letters, digits, dashes, periods only)');
51
51
  }
52
- if (handle.length > 253) {
52
+ if (input.length > 253) {
53
53
  throw new InvalidHandleError('Handle is too long (253 chars max)');
54
54
  }
55
- const labels = handle.split('.');
55
+ const labels = input.split('.');
56
56
  if (labels.length < 2) {
57
57
  throw new InvalidHandleError('Handle domain needs at least two parts');
58
58
  }
@@ -74,11 +74,11 @@ function ensureValidHandle(handle) {
74
74
  }
75
75
  // simple regex translation of above constraints
76
76
  const HANDLE_REGEX = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
77
- function ensureValidHandleRegex(handle) {
78
- if (handle.length > 253) {
77
+ function ensureValidHandleRegex(input) {
78
+ if (input.length > 253) {
79
79
  throw new InvalidHandleError('Handle is too long (253 chars max)');
80
80
  }
81
- if (!HANDLE_REGEX.test(handle)) {
81
+ if (!HANDLE_REGEX.test(input)) {
82
82
  throw new InvalidHandleError("Handle didn't validate via regex");
83
83
  }
84
84
  }
@@ -90,8 +90,8 @@ function normalizeAndEnsureValidHandle(handle) {
90
90
  ensureValidHandle(normalized);
91
91
  return normalized;
92
92
  }
93
- function isValidHandle(handle) {
94
- return handle.length <= 253 && HANDLE_REGEX.test(handle);
93
+ function isValidHandle(input) {
94
+ return input.length <= 253 && HANDLE_REGEX.test(input);
95
95
  }
96
96
  function isValidTld(handle) {
97
97
  for (const tld of exports.DISALLOWED_TLDS) {
@@ -1 +1 @@
1
- {"version":3,"file":"handle.js","sourceRoot":"","sources":["../src/handle.ts"],"names":[],"mappings":";;;AAyCA,8CAoCC;AAMD,wDASC;AAED,0CAEC;AAED,sEAIC;AAED,sCAEC;AAED,gCAOC;AAnHY,QAAA,cAAc,GAAG,gBAAgB,CAAA;AAI9C,yEAAyE;AACzE,+EAA+E;AAC/E,wBAAwB;AACxB,4EAA4E;AAC/D,QAAA,eAAe,GAAG;IAC7B,QAAQ;IACR,OAAO;IACP,UAAU;IACV,YAAY;IACZ,WAAW;IACX,UAAU;IACV,MAAM;IACN,uDAAuD;IACvD,QAAQ;IACR,sEAAsE;IACtE,qEAAqE;CACtE,CAAA;AAED,kCAAkC;AAClC,oCAAoC;AACpC,4EAA4E;AAC5E,6EAA6E;AAC7E,kBAAkB;AAClB,uEAAuE;AACvE,0CAA0C;AAC1C,0DAA0D;AAC1D,oDAAoD;AACpD,oFAAoF;AACpF,wDAAwD;AACxD,uEAAuE;AACvE,wBAAwB;AACxB,mEAAmE;AACnE,iDAAiD;AACjD,mDAAmD;AACnD,yEAAyE;AACzE,wCAAwC;AACxC,gCAAgC;AAChC,SAAgB,iBAAiB,CAC/B,MAAc;IAEd,wCAAwC;IACxC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,MAAM,C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IAEd,IAAI,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACxB,MAAM,IAAI,kBAAkB,CAAC,oCAAoC,CAAC,CAAA;IACpE,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,kBAAkB,CAAC,kCAAkC,CAAC,CAAA;IAClE,CAAC;AACH,CAAC;AAED,SAAgB,eAAe,CAAC,MAAc;IAC5C,OAAO,MAAM,CAAC,WAAW,EAAE,CAAA;AAC7B,CAAC;AAED,SAAgB,6BAA6B,CAAC,MAAc;IAC1D,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAA;IAC1C,iBAAiB,CAAC,UAAU,CAAC,CAAA;IAC7B,OAAO,UAAU,CAAA;AACnB,CAAC;AAED,SAAgB,aAAa,CAAC,MAAc;IAC1C,OAAO,MAAM,CAAC,MAAM,IAAI,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;AAC1D,CAAC;AAED,SAAgB,UAAU,CAAC,MAAc;IACvC,KAAK,MAAM,GAAG,IAAI,uBAAe,EAAE,CAAC;QAClC,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YACzB,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAED,MAAa,kBAAmB,SAAQ,KAAK;CAAG;AAAhD,gDAAgD;AAChD,6BAA6B;AAC7B,MAAa,mBAAoB,SAAQ,KAAK;CAAG;AAAjD,kDAAiD;AACjD,6BAA6B;AAC7B,MAAa,sBAAuB,SAAQ,KAAK;CAAG;AAApD,wDAAoD;AACpD,6BAA6B;AAC7B,MAAa,qBAAsB,SAAQ,KAAK;CAAG;AAAnD,sDAAmD","sourcesContent":["export const INVALID_HANDLE = 'handle.invalid'\n\nexport type HandleString = `${string}.${string}`\n\n// Currently these are registration-time restrictions, not protocol-level\n// restrictions. We have a couple accounts in the wild that we need to clean up\n// before hard-disallow.\n// See also: https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains\nexport const DISALLOWED_TLDS = [\n '.local',\n '.arpa',\n '.invalid',\n '.localhost',\n '.internal',\n '.example',\n '.alt',\n // policy could concievably change on \".onion\" some day\n '.onion',\n // NOTE: .test is allowed in testing and devopment. In practical terms\n // \"should\" \"never\" actually resolve and get registered in production\n]\n\n// Handle constraints, in English:\n// - must be a possible domain name\n// - RFC-1035 is commonly referenced, but has been updated. eg, RFC-3696,\n// section 2. and RFC-3986, section 3. can now have leading numbers (eg,\n// 4chan.org)\n// - \"labels\" (sub-names) are made of ASCII letters, digits, hyphens\n// - can not start or end with a hyphen\n// - TLD (last component) should not start with a digit\n// - can't end with a hyphen (can end with digit)\n// - each segment must be between 1 and 63 characters (not including any periods)\n// - overall length can't be more than 253 characters\n// - separated by (ASCII) periods; does not start or end with period\n// - case insensitive\n// - domains (handles) are equal if they are the same lower-case\n// - punycode allowed for internationalization\n// - no whitespace, null bytes, joining chars, etc\n// - does not validate whether domain or TLD exists, or is a reserved or\n// special TLD (eg, .onion or .local)\n// - does not validate punycode\nexport function ensureValidHandle(\n handle: string,\n): asserts handle is HandleString {\n // check that all chars are boring ASCII\n if (!/^[a-zA-Z0-9.-]*$/.test(handle)) {\n throw new InvalidHandleError(\n 'Disallowed characters in handle (ASCII letters, digits, dashes, periods only)',\n )\n }\n\n if (handle.length > 253) {\n throw new InvalidHandleError('Handle is too long (253 chars max)')\n }\n const labels = handle.split('.')\n if (labels.length < 2) {\n throw new InvalidHandleError('Handle domain needs at least two parts')\n }\n for (let i = 0; i < labels.length; i++) {\n const l = labels[i]\n if (l.length < 1) {\n throw new InvalidHandleError('Handle parts can not be empty')\n }\n if (l.length > 63) {\n throw new InvalidHandleError('Handle part too long (max 63 chars)')\n }\n if (l.endsWith('-') || l.startsWith('-')) {\n throw new InvalidHandleError(\n 'Handle parts can not start or end with hyphens',\n )\n }\n if (i + 1 === labels.length && !/^[a-zA-Z]/.test(l)) {\n throw new InvalidHandleError(\n 'Handle final component (TLD) must start with ASCII letter',\n )\n }\n }\n}\n\n// simple regex translation of above constraints\nconst HANDLE_REGEX =\n /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/\n\nexport function ensureValidHandleRegex(\n handle: string,\n): asserts handle is HandleString {\n if (handle.length > 253) {\n throw new InvalidHandleError('Handle is too long (253 chars max)')\n }\n if (!HANDLE_REGEX.test(handle)) {\n throw new InvalidHandleError(\"Handle didn't validate via regex\")\n }\n}\n\nexport function normalizeHandle(handle: string): string {\n return handle.toLowerCase()\n}\n\nexport function normalizeAndEnsureValidHandle(handle: string): HandleString {\n const normalized = normalizeHandle(handle)\n ensureValidHandle(normalized)\n return normalized\n}\n\nexport function isValidHandle(handle: string): handle is HandleString {\n return handle.length <= 253 && HANDLE_REGEX.test(handle)\n}\n\nexport function isValidTld(handle: string): boolean {\n for (const tld of DISALLOWED_TLDS) {\n if (handle.endsWith(tld)) {\n return false\n }\n }\n return true\n}\n\nexport class InvalidHandleError extends Error {}\n/** @deprecated Never used */\nexport class ReservedHandleError extends Error {}\n/** @deprecated Never used */\nexport class UnsupportedDomainError extends Error {}\n/** @deprecated Never used */\nexport class DisallowedDomainError extends Error {}\n"]}
1
+ {"version":3,"file":"handle.js","sourceRoot":"","sources":["../src/handle.ts"],"names":[],"mappings":";;;AAyCA,8CAoCC;AAMD,wDASC;AAID,0CAEC;AAED,sEAIC;AAED,sCAIC;AAED,gCAOC;AAvHY,QAAA,cAAc,GAAG,gBAAgB,CAAA;AAI9C,yEAAyE;AACzE,+EAA+E;AAC/E,wBAAwB;AACxB,4EAA4E;AAC/D,QAAA,eAAe,GAAG;IAC7B,QAAQ;IACR,OAAO;IACP,UAAU;IACV,YAAY;IACZ,WAAW;IACX,UAAU;IACV,MAAM;IACN,uDAAuD;IACvD,Q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AAA;QACd,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAED,MAAa,kBAAmB,SAAQ,KAAK;CAAG;AAAhD,gDAAgD;AAChD,6BAA6B;AAC7B,MAAa,mBAAoB,SAAQ,KAAK;CAAG;AAAjD,kDAAiD;AACjD,6BAA6B;AAC7B,MAAa,sBAAuB,SAAQ,KAAK;CAAG;AAApD,wDAAoD;AACpD,6BAA6B;AAC7B,MAAa,qBAAsB,SAAQ,KAAK;CAAG;AAAnD,sDAAmD","sourcesContent":["export const INVALID_HANDLE = 'handle.invalid'\n\nexport type HandleString = `${string}.${string}`\n\n// Currently these are registration-time restrictions, not protocol-level\n// restrictions. We have a couple accounts in the wild that we need to clean up\n// before hard-disallow.\n// See also: https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains\nexport const DISALLOWED_TLDS = [\n '.local',\n '.arpa',\n '.invalid',\n '.localhost',\n '.internal',\n '.example',\n '.alt',\n // policy could concievably change on \".onion\" some day\n '.onion',\n // NOTE: .test is allowed in testing and devopment. In practical terms\n // \"should\" \"never\" actually resolve and get registered in production\n]\n\n// Handle constraints, in English:\n// - must be a possible domain name\n// - RFC-1035 is commonly referenced, but has been updated. eg, RFC-3696,\n// section 2. and RFC-3986, section 3. can now have leading numbers (eg,\n// 4chan.org)\n// - \"labels\" (sub-names) are made of ASCII letters, digits, hyphens\n// - can not start or end with a hyphen\n// - TLD (last component) should not start with a digit\n// - can't end with a hyphen (can end with digit)\n// - each segment must be between 1 and 63 characters (not including any periods)\n// - overall length can't be more than 253 characters\n// - separated by (ASCII) periods; does not start or end with period\n// - case insensitive\n// - domains (handles) are equal if they are the same lower-case\n// - punycode allowed for internationalization\n// - no whitespace, null bytes, joining chars, etc\n// - does not validate whether domain or TLD exists, or is a reserved or\n// special TLD (eg, .onion or .local)\n// - does not validate punycode\nexport function ensureValidHandle<I extends string>(\n input: I,\n): asserts input is I & HandleString {\n // check that all chars are boring ASCII\n if (!/^[a-zA-Z0-9.-]*$/.test(input)) {\n throw new InvalidHandleError(\n 'Disallowed characters in handle (ASCII letters, digits, dashes, periods only)',\n )\n }\n\n if (input.length > 253) {\n throw new InvalidHandleError('Handle is too long (253 chars max)')\n }\n const labels = input.split('.')\n if (labels.length < 2) {\n throw new InvalidHandleError('Handle domain needs at least two parts')\n }\n for (let i = 0; i < labels.length; i++) {\n const l = labels[i]\n if (l.length < 1) {\n throw new InvalidHandleError('Handle parts can not be empty')\n }\n if (l.length > 63) {\n throw new InvalidHandleError('Handle part too long (max 63 chars)')\n }\n if (l.endsWith('-') || l.startsWith('-')) {\n throw new InvalidHandleError(\n 'Handle parts can not start or end with hyphens',\n )\n }\n if (i + 1 === labels.length && !/^[a-zA-Z]/.test(l)) {\n throw new InvalidHandleError(\n 'Handle final component (TLD) must start with ASCII letter',\n )\n }\n }\n}\n\n// simple regex translation of above constraints\nconst HANDLE_REGEX =\n /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/\n\nexport function ensureValidHandleRegex<I extends string>(\n input: I,\n): asserts input is I & HandleString {\n if (input.length > 253) {\n throw new InvalidHandleError('Handle is too long (253 chars max)')\n }\n if (!HANDLE_REGEX.test(input)) {\n throw new InvalidHandleError(\"Handle didn't validate via regex\")\n }\n}\n\nexport function normalizeHandle(handle: HandleString): HandleString\nexport function normalizeHandle(handle: string): string\nexport function normalizeHandle(handle: string): string {\n return handle.toLowerCase()\n}\n\nexport function normalizeAndEnsureValidHandle(handle: string): HandleString {\n const normalized = normalizeHandle(handle)\n ensureValidHandle(normalized)\n return normalized\n}\n\nexport function isValidHandle<I extends string>(\n input: I,\n): input is I & HandleString {\n return input.length <= 253 && HANDLE_REGEX.test(input)\n}\n\nexport function isValidTld(handle: string): boolean {\n for (const tld of DISALLOWED_TLDS) {\n if (handle.endsWith(tld)) {\n return false\n }\n }\n return true\n}\n\nexport class InvalidHandleError extends Error {}\n/** @deprecated Never used */\nexport class ReservedHandleError extends Error {}\n/** @deprecated Never used */\nexport class UnsupportedDomainError extends Error {}\n/** @deprecated Never used */\nexport class DisallowedDomainError extends Error {}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
- export * from './handle.js';
1
+ export * from './at-identifier.js';
2
+ export * from './aturi.js';
3
+ export * from './datetime.js';
2
4
  export * from './did.js';
5
+ export * from './handle.js';
3
6
  export * from './nsid.js';
4
- export * from './aturi.js';
5
- export * from './at-identifier.js';
6
- export * from './tid.js';
7
+ export * from './language.js';
7
8
  export * from './recordkey.js';
8
- export * from './datetime.js';
9
+ export * from './tid.js';
10
+ export * from './uri.js';
9
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA;AAC1B,cAAc,oBAAoB,CAAA;AAClC,cAAc,UAAU,CAAA;AACxB,cAAc,gBAAgB,CAAA;AAC9B,cAAc,eAAe,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,UAAU,CAAA;AACxB,cAAc,aAAa,CAAA;AAC3B,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA"}