@atlantjs/arch 15.6.7 → 15.7.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 (106) hide show
  1. package/index.js +60 -0
  2. package/package.json +4 -3
  3. package/{tsconfig.tsbuildinfo → tsconfig.build.tsbuildinfo} +1 -1
  4. package/src/@tool-box/tests/builder.abstract.util.js +0 -39
  5. package/src/@tool-box/tests/builders/datetime/datetime.edge.builder.js +0 -15
  6. package/src/@tool-box/tests/builders/failures/dummies/failure.dummy.js +0 -13
  7. package/src/@tool-box/tests/builders/failures/failure.builder.js +0 -17
  8. package/src/@tool-box/tests/builders/metadata/metadata-uv.builder.js +0 -18
  9. package/src/@tool-box/tests/builders/metadata/metadata.edge.builder.js +0 -15
  10. package/src/@tool-box/tests/builders/user/email.edge.builder.js +0 -15
  11. package/src/@tool-box/tests/builders/user/username.edge.builder.js +0 -15
  12. package/src/@tool-box/tests/faker/faker.js +0 -208
  13. package/src/@tool-box/utils/convert-units/convert-units.js +0 -154
  14. package/src/@tool-box/utils/datatypes/boolean-utils.js +0 -155
  15. package/src/@tool-box/utils/datatypes/generic-types.js +0 -3
  16. package/src/@tool-box/utils/datatypes/plainify.js +0 -2
  17. package/src/@tool-box/utils/datatypes/string-utils.js +0 -292
  18. package/src/@tool-box/utils/datetime/mappers/month.mapper.js +0 -58
  19. package/src/@tool-box/utils/datetime/mappers/points/month-abbreviation.enum.js +0 -18
  20. package/src/@tool-box/utils/datetime/mappers/points/month-number.enum.js +0 -18
  21. package/src/@tool-box/utils/ducts/common.js +0 -47
  22. package/src/@tool-box/utils/ducts/optional-type.js +0 -128
  23. package/src/@tool-box/utils/ducts/return-type.js +0 -67
  24. package/src/@tool-box/utils/http-provider/http-provider-failure-response.js +0 -19
  25. package/src/@tool-box/utils/http-provider/http-provider-success-response.js +0 -20
  26. package/src/@tool-box/utils/http-provider/http-provider.js +0 -85
  27. package/src/@tool-box/utils/logger/index.js +0 -31
  28. package/src/@tool-box/utils/map/map.abstract.js +0 -84
  29. package/src/@tool-box/utils/random/random.js +0 -260
  30. package/src/@tool-box/utils/type-guard/guardian-exception.js +0 -6
  31. package/src/@tool-box/utils/type-guard/guardian.js +0 -625
  32. package/src/@tool-box/utils/type-guard/guardian.type.js +0 -2
  33. package/src/@tool-box/utils/validators/is-cron-expression.js +0 -39
  34. package/src/@tool-box/utils/validators/is-date-string.js +0 -42
  35. package/src/@tool-box/utils/validators/is-password-match.js +0 -27
  36. package/src/@tool-box/utils/validators/is-password-policy.validator.js +0 -30
  37. package/src/@tool-box/utils/validators/is-schedule.js +0 -43
  38. package/src/@tool-box/utils/validators/is-time-string.js +0 -39
  39. package/src/@tool-box/utils/validators/is-ulid.js +0 -39
  40. package/src/index.js +0 -179
  41. package/src/objects/@common/edges/email.edge.js +0 -94
  42. package/src/objects/@common/edges/ulid.sketch.edge.js +0 -91
  43. package/src/objects/@common/edges/url.edge.js +0 -269
  44. package/src/objects/@common/edges/username.edge.js +0 -41
  45. package/src/objects/@common/edges/uuid.sketch.edge.js +0 -145
  46. package/src/objects/@common/points/environment.point.js +0 -10
  47. package/src/objects/@common/points/header-token-name.point.js +0 -10
  48. package/src/objects/@common/points/http-status-codes.point.js +0 -244
  49. package/src/objects/amount/amount-value.edge.js +0 -76
  50. package/src/objects/amount/amount.edge.js +0 -626
  51. package/src/objects/amount/amount.polygon.js +0 -2
  52. package/src/objects/amount/amount.uv.js +0 -29
  53. package/src/objects/amount/points/duration-unit.point.js +0 -15
  54. package/src/objects/amount/points/energy-unit.point.js +0 -10
  55. package/src/objects/amount/points/length-unit.point.js +0 -10
  56. package/src/objects/amount/points/mass-unit.point.js +0 -11
  57. package/src/objects/amount/points/month-name.point.js +0 -18
  58. package/src/objects/amount/points/object-unit.point.js +0 -7
  59. package/src/objects/amount/points/units.point.js +0 -2
  60. package/src/objects/amount/points/volume-unit.point.js +0 -8
  61. package/src/objects/amount/points/week-day.point.js +0 -13
  62. package/src/objects/datetime/edges/datetime.edge.js +0 -672
  63. package/src/objects/datetime/edges/locale/day/day-name-to-english.mapper.js +0 -19
  64. package/src/objects/datetime/edges/locale/day/day-name-to-portuguese.mapper.js +0 -19
  65. package/src/objects/datetime/edges/locale/day/today-to-language.mapper.js +0 -15
  66. package/src/objects/datetime/edges/locale/holidays-country.type.js +0 -2
  67. package/src/objects/datetime/edges/locale/month/month-to-english.mapper.js +0 -24
  68. package/src/objects/datetime/edges/locale/month/month-to-portuguese.mapper.js +0 -24
  69. package/src/objects/datetime/points/month-name.enum.js +0 -18
  70. package/src/objects/datetime/points/week-day.enum.js +0 -13
  71. package/src/objects/failure/edges/failure.abstract.js +0 -24
  72. package/src/objects/failure/edges/failure.abstract.polygon.js +0 -2
  73. package/src/objects/language/points/language.point.js +0 -135
  74. package/src/objects/metadata/metadata.edge.js +0 -25
  75. package/src/objects/metadata/metadata.polygon.js +0 -2
  76. package/src/objects/metadata/metadata.uv.js +0 -29
  77. package/src/objects/password/password.edge.js +0 -175
  78. package/src/objects/password/password.polygon.js +0 -2
  79. package/src/objects/password/steps/not-allowing-consecutive-chars-step.js +0 -34
  80. package/src/objects/password/steps/not-allowing-date-step.js +0 -61
  81. package/src/objects/password/steps/not-allowing-phone-step.js +0 -27
  82. package/src/objects/password/steps/not-allowing-repeated-chars-step.js +0 -34
  83. package/src/objects/password/steps/not-allowing-string-step.js +0 -19
  84. package/src/objects/password/steps/not-allowing-these-chars-step.js +0 -17
  85. package/src/objects/password/steps/numeric-step.js +0 -13
  86. package/src/objects/password/steps/with-at-least-one-letter-step.js +0 -14
  87. package/src/objects/password/steps/with-at-least-one-number-digit-step.js +0 -14
  88. package/src/objects/password/steps/with-at-least-one-special-char-step.js +0 -14
  89. package/src/objects/password/steps/with-length-step.js +0 -18
  90. package/src/objects/password/validation-step.js +0 -9
  91. package/src/objects/password/validation-step.type.js +0 -2
  92. package/src/objects/primitives/boolean.edge.sketch.js +0 -147
  93. package/src/objects/primitives/datetime.edge.sketch.js +0 -7
  94. package/src/objects/primitives/number.edge.sketch.js +0 -346
  95. package/src/objects/primitives/string.edge.sketch.js +0 -218
  96. package/src/objects/scheduling/scheduling.edge.failure.js +0 -14
  97. package/src/objects/scheduling/scheduling.edge.js +0 -280
  98. package/src/objects/time/time.edge.js +0 -447
  99. package/src/objects-interface/edges/edge.abstract.js +0 -6
  100. package/src/objects-interface/face.abstract.js +0 -6
  101. package/src/objects-interface/solid.abstract.js +0 -11
  102. package/src/objects-interface/uv.abstract.js +0 -6
  103. package/src/objects-interface/vertices/vertex.abstract.js +0 -11
  104. package/src/shared/payload.abstract.js +0 -6
  105. package/src/shared/request.abstract.js +0 -3
  106. package/src/shared/response.abstract.js +0 -6
@@ -1,218 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StringEdgeSketch = void 0;
4
- class StringEdgeSketch {
5
- constructor(value) {
6
- this.value = value;
7
- this.sanitize();
8
- this.validate();
9
- }
10
- // ==================== Getters ====================
11
- /**
12
- * Retorna o valor da string.
13
- * @returns String interna do edge
14
- * @example
15
- * new MyStringEdge("hello").toString() // "hello"
16
- */
17
- toString() {
18
- return this.value;
19
- }
20
- /**
21
- * Retorna o comprimento da string.
22
- * @returns Número de caracteres da string
23
- * @example
24
- * new MyStringEdge("hello").length() // 5
25
- */
26
- length() {
27
- return this.value.length;
28
- }
29
- // ==================== Verificações ====================
30
- /**
31
- * Verifica se a string contém uma substring específica.
32
- * @param value - Substring a ser procurada
33
- * @returns true se a substring foi encontrada, false caso contrário
34
- * @example
35
- * new MyStringEdge("hello world").has("world") // true
36
- * new MyStringEdge("hello world").has("foo") // false
37
- */
38
- has(value) {
39
- return this.value.includes(value); // 🐛 fix: !indexOf() falha quando index é 0
40
- }
41
- /**
42
- * Verifica se a string começa com uma substring específica.
43
- * @param value - Substring a ser verificada no início
44
- * @returns true se a string começa com a substring, false caso contrário
45
- * @example
46
- * new MyStringEdge("hello world").startsWith("hello") // true
47
- * new MyStringEdge("hello world").startsWith("world") // false
48
- */
49
- startsWith(value) {
50
- return this.value.startsWith(value);
51
- }
52
- /**
53
- * Verifica se a string termina com uma substring específica.
54
- * @param value - Substring a ser verificada no final
55
- * @returns true se a string termina com a substring, false caso contrário
56
- * @example
57
- * new MyStringEdge("hello world").endsWith("world") // true
58
- * new MyStringEdge("hello world").endsWith("hello") // false
59
- */
60
- endsWith(value) {
61
- return this.value.endsWith(value);
62
- }
63
- /**
64
- * Verifica se a string é igual a outra (case-sensitive).
65
- * @param value - String para comparação
66
- * @returns true se as strings são iguais, false caso contrário
67
- * @example
68
- * new MyStringEdge("hello").isEqual("hello") // true
69
- * new MyStringEdge("hello").isEqual("Hello") // false
70
- */
71
- isEqual(value) {
72
- return this.value === value;
73
- }
74
- /**
75
- * Verifica se a string é igual a outra ignorando maiúsculas/minúsculas.
76
- * @param value - String para comparação
77
- * @returns true se as strings são iguais (case-insensitive), false caso contrário
78
- * @example
79
- * new MyStringEdge("hello").isEqualIgnoreCase("HELLO") // true
80
- * new MyStringEdge("hello").isEqualIgnoreCase("world") // false
81
- */
82
- isEqualIgnoreCase(value) {
83
- return this.value.toLowerCase() === value.toLowerCase();
84
- }
85
- // ==================== Extração ====================
86
- /**
87
- * Extrai uma substring entre dois delimitadores (exclusivo).
88
- * @param start - Delimitador de início (não incluído no resultado)
89
- * @param end - Delimitador de fim (não incluído no resultado)
90
- * @returns Substring entre os delimitadores
91
- * @example
92
- * new MyStringEdge("[hello]").extract("[", "]") // "hello"
93
- * new MyStringEdge("(foo bar)").extract("(", ")") // "foo bar"
94
- */
95
- extract(start, end) {
96
- const indexStart = this.value.indexOf(start) + start.length; // 🐛 fix: incluir tamanho do delimitador
97
- const indexEnd = this.value.lastIndexOf(end); // 🐛 fix: remover + 1 que incluía o char final
98
- return this.value.substring(indexStart, indexEnd);
99
- }
100
- /**
101
- * Retorna uma fatia da string entre dois índices.
102
- * @param start - Índice inicial (inclusivo)
103
- * @param end - Índice final (exclusivo, opcional)
104
- * @returns Substring entre os índices fornecidos
105
- * @example
106
- * new MyStringEdge("hello world").slice(0, 5) // "hello"
107
- * new MyStringEdge("hello world").slice(6) // "world"
108
- */
109
- slice(start, end) {
110
- return this.value.slice(start, end);
111
- }
112
- // ==================== Transformação ====================
113
- /**
114
- * Remove todas as ocorrências das substrings fornecidas.
115
- * @param substrings - Array de substrings a serem removidas
116
- * @returns Nova string sem as substrings fornecidas
117
- * @example
118
- * new MyStringEdge("hello world").remove(["hello", " "]) // "world"
119
- * new MyStringEdge("foo-bar_baz").remove(["-", "_"]) // "foobarbaz"
120
- */
121
- remove(substrings) {
122
- return substrings.reduce(
123
- // 🐛 fix: regex com [...] quebra para substrings com mais de 1 char
124
- (acc, substring) => acc.split(substring).join(""), this.value);
125
- }
126
- /**
127
- * Substitui a primeira ocorrência de uma substring por outra.
128
- * @param search - Substring a ser substituída
129
- * @param replacement - Substring substituta
130
- * @returns Nova string com a primeira ocorrência substituída
131
- * @example
132
- * new MyStringEdge("foo bar foo").replace("foo", "baz") // "baz bar foo"
133
- */
134
- replace(search, replacement) {
135
- return this.value.replace(search, replacement);
136
- }
137
- /**
138
- * Substitui todas as ocorrências de uma substring por outra.
139
- * @param search - Substring a ser substituída
140
- * @param replacement - Substring substituta
141
- * @returns Nova string com todas as ocorrências substituídas
142
- * @example
143
- * new MyStringEdge("foo bar foo").replaceAll("foo", "baz") // "baz bar baz"
144
- */
145
- replaceAll(search, replacement) {
146
- return this.value.split(search).join(replacement);
147
- }
148
- /**
149
- * Converte a string para letras maiúsculas.
150
- * @returns String em maiúsculas
151
- * @example
152
- * new MyStringEdge("hello").toUpperCase() // "HELLO"
153
- */
154
- toUpperCase() {
155
- return this.value.toUpperCase();
156
- }
157
- /**
158
- * Converte a string para letras minúsculas.
159
- * @returns String em minúsculas
160
- * @example
161
- * new MyStringEdge("HELLO").toLowerCase() // "hello"
162
- */
163
- toLowerCase() {
164
- return this.value.toLowerCase();
165
- }
166
- /**
167
- * Reverte os caracteres da string.
168
- * @returns String com os caracteres em ordem inversa
169
- * @example
170
- * new MyStringEdge("hello").reverse() // "olleh"
171
- */
172
- reverse() {
173
- return this.value.split("").reverse().join("");
174
- }
175
- /**
176
- * Trunca a string para um comprimento máximo, adicionando "..." ao final.
177
- * Se a string já for menor ou igual ao comprimento, retorna sem alteração.
178
- * @param length - Comprimento máximo da string resultante (incluindo "...")
179
- * @returns String truncada com "..." se necessário
180
- * @example
181
- * new MyStringEdge("Hello World").truncate(8) // "Hello..."
182
- * new MyStringEdge("Hi").truncate(8) // "Hi"
183
- */
184
- truncate(length) {
185
- if (this.value.length <= length)
186
- return this.value;
187
- return `${this.value.substring(0, length - 3)}...`;
188
- }
189
- /**
190
- * Conta o número de ocorrências de uma substring na string.
191
- * @param substring - Substring a ser contada
192
- * @returns Número de ocorrências encontradas
193
- * @example
194
- * new MyStringEdge("hello world hello").countOccurrences("hello") // 2
195
- */
196
- countOccurrences(substring) {
197
- if (substring.length === 0)
198
- return 0;
199
- return this.value.split(substring).length - 1;
200
- }
201
- // ==================== Privados ====================
202
- /**
203
- * Remove espaços extras no início e no fim da string.
204
- */
205
- sanitize() {
206
- this.value = this.value.trim();
207
- }
208
- /**
209
- * Valida se a string não está vazia após o sanitize.
210
- * @throws {TypeError} Se a string estiver vazia
211
- */
212
- validate() {
213
- if (this.value.length <= 0) {
214
- throw new TypeError(`${this.constructor.name} should not be empty.`);
215
- }
216
- }
217
- }
218
- exports.StringEdgeSketch = StringEdgeSketch;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RecurringSchedulingEdgeFailure = void 0;
4
- const failure_abstract_1 = require("#/objects/failure/edges/failure.abstract");
5
- class RecurringSchedulingEdgeFailure extends failure_abstract_1.FailureAbstract {
6
- constructor(schedule, error) {
7
- super({
8
- failureClass: RecurringSchedulingEdgeFailure,
9
- message: `${schedule} is not a recurring schedule`,
10
- stackTrace: error,
11
- });
12
- }
13
- }
14
- exports.RecurringSchedulingEdgeFailure = RecurringSchedulingEdgeFailure;
@@ -1,280 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SchedulingEdge = void 0;
4
- const cron_parser_1 = require("cron-parser");
5
- const optional_type_1 = require("#/@tool-box/utils/ducts/optional-type");
6
- const return_type_1 = require("#/@tool-box/utils/ducts/return-type");
7
- const datetime_edge_1 = require("#/objects/datetime/edges/datetime.edge");
8
- const string_edge_sketch_1 = require("#/objects/primitives/string.edge.sketch");
9
- const time_edge_1 = require("#/objects/time/time.edge");
10
- class SchedulingEdge extends string_edge_sketch_1.StringEdgeSketch {
11
- constructor(_cronExpression) {
12
- // normaliza espaços múltiplos para evitar inconsistência de validação
13
- super(_cronExpression.replace(/\s+/g, " "));
14
- this._cronExpression = _cronExpression;
15
- this.expiresInPacked = optional_type_1.Nothing;
16
- this.validateCronExpression();
17
- }
18
- validateCronExpression() {
19
- try {
20
- cron_parser_1.CronExpressionParser.parse(this.toString());
21
- }
22
- catch {
23
- throw new Error(`${this.toString()} should be a valid Cron Expression.`);
24
- }
25
- }
26
- // ==================== Verificações ====================
27
- /**
28
- * Verifica se o agendamento é recorrente (baseado em expressão cron).
29
- * @returns true se o agendamento é recorrente, false se é um datetime fixo
30
- * @example
31
- * new ScheduleEdge(new CronExpressionEdge("0 8 * * *")).isRecurrent() // true
32
- * new ScheduleEdge(new DatetimeEdge(new Date())).isRecurrent() // false
33
- */
34
- isRecurrent() {
35
- return this.expiresInPacked.hasSomething();
36
- }
37
- /**
38
- * Verifica se o agendamento é um evento único (baseado no momento de expiracao).
39
- * @returns true se o agendamento é um evento único, false se é recorrente
40
- */
41
- isOneTime() {
42
- return this.expiresInPacked.hasNothing();
43
- }
44
- // ==================== Ocorrências ====================
45
- /**
46
- * Retorna a próxima ocorrência de um agendamento recorrente.
47
- * @returns Success com a próxima ocorrência ou Failure se o agendamento não for recorrente
48
- * @example
49
- * const schedule = new ScheduleEdge(new CronExpressionEdge("0 8 * * *"));
50
- * schedule.nextOccurrence() // Success(DatetimeEdge com a próxima ocorrência às 8h)
51
- */
52
- nextOccurrence() {
53
- const cronDate = cron_parser_1.CronExpressionParser.parse(this._cronExpression.toString()).next();
54
- return (0, return_type_1.Success)(new datetime_edge_1.DatetimeEdge(cronDate.toDate()));
55
- }
56
- /**
57
- * Retorna as próximas N ocorrências de um agendamento recorrente.
58
- * @param quantity - Número de ocorrências a retornar
59
- * @returns Success com array das próximas ocorrências ou Failure se não for recorrente
60
- * @example
61
- * const schedule = new ScheduleEdge(new CronExpressionEdge("0 8 * * *"));
62
- * schedule.nextOccurrences(3) // Success([DatetimeEdge, DatetimeEdge, DatetimeEdge])
63
- */
64
- nextOccurrences(quantity) {
65
- const cronDates = cron_parser_1.CronExpressionParser.parse(this._cronExpression.toString()).take(quantity);
66
- return (0, return_type_1.Success)(cronDates.map((cronDate) => new datetime_edge_1.DatetimeEdge(cronDate.toDate())));
67
- }
68
- /**
69
- * Retorna a ocorrência anterior de um agendamento recorrente.
70
- * @returns Success com a ocorrência anterior ou Failure se o agendamento não for recorrente
71
- * @example
72
- * const schedule = new ScheduleEdge(new CronExpressionEdge("0 8 * * *"));
73
- * schedule.previousOccurrence() // Success(DatetimeEdge com a última ocorrência às 8h)
74
- */
75
- previousOccurrence() {
76
- const cronDate = cron_parser_1.CronExpressionParser.parse(this._cronExpression.toString()).prev();
77
- return (0, return_type_1.Success)(new datetime_edge_1.DatetimeEdge(cronDate.toDate()));
78
- }
79
- /**
80
- * Retorna as N ocorrências anteriores de um agendamento recorrente.
81
- * @param quantity - Número de ocorrências a retornar
82
- * @returns Success com array das ocorrências anteriores ou Failure se não for recorrente
83
- * @example
84
- * const schedule = new ScheduleEdge(new CronExpressionEdge("0 8 * * *"));
85
- * schedule.previousOccurrences(3) // Success([DatetimeEdge, DatetimeEdge, DatetimeEdge])
86
- */
87
- previousOccurrences(quantity) {
88
- const cronDates = cron_parser_1.CronExpressionParser.parse(this._cronExpression.toString()).take(-quantity);
89
- return (0, return_type_1.Success)(cronDates.map((cronDate) => new datetime_edge_1.DatetimeEdge(cronDate.toDate())));
90
- }
91
- /**
92
- * Retorna todas as ocorrências dentro de um intervalo de datas.
93
- * @param start - Data de início do intervalo
94
- * @param end - Data de fim do intervalo
95
- * @returns Success com array das ocorrências no intervalo ou Failure se não for recorrente
96
- * @example
97
- * const schedule = new ScheduleEdge(new CronExpressionEdge("0 8 * * *"));
98
- * schedule.occurrencesBetween(startDate, endDate)
99
- * // Success([DatetimeEdge, DatetimeEdge, ...])
100
- */
101
- occurrencesBetween(start, end) {
102
- const interval = cron_parser_1.CronExpressionParser.parse(this._cronExpression.toString(), {
103
- currentDate: start.toDate(),
104
- endDate: end.toDate(),
105
- });
106
- const occurrences = [];
107
- while (true) {
108
- try {
109
- const next = interval.next();
110
- occurrences.push(new datetime_edge_1.DatetimeEdge(next.toDate()));
111
- }
112
- catch {
113
- break;
114
- }
115
- }
116
- return (0, return_type_1.Success)(occurrences);
117
- }
118
- /**
119
- * Conta quantas ocorrências existem dentro de um intervalo de datas.
120
- * @param start - Data de início do intervalo
121
- * @param end - Data de fim do intervalo
122
- * @returns Success com o número de ocorrências ou Failure se não for recorrente
123
- * @example
124
- * const schedule = new ScheduleEdge(new CronExpressionEdge("0 8 * * 1-5"));
125
- * schedule.countOccurrencesBetween(startDate, endDate) // Success(5) em uma semana
126
- */
127
- countOccurrencesBetween(start, end) {
128
- const resultWrapped = this.occurrencesBetween(start, end);
129
- if (!resultWrapped.hasSuccess)
130
- return resultWrapped;
131
- return (0, return_type_1.Success)(resultWrapped.unwrap().values.length);
132
- }
133
- // ==================== Getters ====================
134
- /**
135
- * Retorna o horário do agendamento como um TimeEdge.
136
- * @returns TimeEdge com hora e minuto do agendamento
137
- * @example
138
- * new ScheduleEdge(new CronExpressionEdge("0 8 * * *")).getTime()
139
- * // TimeEdge("08:00")
140
- */
141
- getTime() {
142
- const interval = cron_parser_1.CronExpressionParser.parse(this._cronExpression.toString()).fields;
143
- const hour = String(interval.hour.values.toString()).padStart(2, "0");
144
- const minute = String(interval.minute.values.toString()).padStart(2, "0");
145
- return new time_edge_1.TimeEdge(`${hour}:${minute}`);
146
- }
147
- /**
148
- * Retorna os campos da expressão cron.
149
- */
150
- getFields() {
151
- return this.toString().split(/\s+/);
152
- }
153
- // ==================== Cálculo de Execução ====================
154
- /**
155
- * Retorna a próxima execução a partir de uma data base.
156
- */
157
- nextDate(fromDate = new Date()) {
158
- const interval = cron_parser_1.CronExpressionParser.parse(this.toString(), {
159
- currentDate: fromDate,
160
- });
161
- return interval.next().toDate();
162
- }
163
- /**
164
- * Retorna a execução anterior a partir de uma data base.
165
- */
166
- previousDate(fromDate = new Date()) {
167
- const interval = cron_parser_1.CronExpressionParser.parse(this.toString(), {
168
- currentDate: fromDate,
169
- });
170
- return interval.prev().toDate();
171
- }
172
- /**
173
- * Retorna as próximas N execuções.
174
- */
175
- nextDates(count, fromDate = new Date()) {
176
- if (count <= 0)
177
- return [];
178
- const interval = cron_parser_1.CronExpressionParser.parse(this.toString(), {
179
- currentDate: fromDate,
180
- });
181
- const dates = [];
182
- for (let i = 0; i < count; i++) {
183
- dates.push(interval.next().toDate());
184
- }
185
- return dates;
186
- }
187
- // ==================== Métodos Estáticos ====================
188
- /**
189
- * Valida expressão cron sem lançar exceção.
190
- */
191
- static isValid(expression) {
192
- try {
193
- cron_parser_1.CronExpressionParser.parse(expression.trim().replace(/\s+/g, " "));
194
- return true;
195
- }
196
- catch {
197
- return false;
198
- }
199
- }
200
- /**
201
- * Retorna a CronExpressionEdge do agendamento se for recorrente.
202
- * @returns Success com a CronExpressionEdge ou Failure se for evento único
203
- * @example
204
- * const cron = new CronExpressionEdge("0 8 * * *");
205
- * new ScheduleEdge(cron).getCronExpression() // CronExpressionEdge("0 8 * * *")
206
- */
207
- getCronExpression() {
208
- return this._cronExpression;
209
- }
210
- // ==================== Clonagem e Imutabilidade ====================
211
- /**
212
- * Cria uma cópia independente desta instância de ScheduleEdge.
213
- * @returns Nova instância com o mesmo momento interno
214
- * @example
215
- * const schedule = new ScheduleEdge(new CronExpressionEdge("0 8 * * *"));
216
- * const clone = schedule.clone(); // instância independente
217
- */
218
- clone() {
219
- return new SchedulingEdge(this._cronExpression);
220
- }
221
- // ==================== Métodos Estáticos ====================
222
- /**
223
- * Cria um ScheduleEdge de evento único a partir de um objeto Datetime.
224
- * @param datetime - Data e hora do evento único
225
- * @returns Nova instância de ScheduleEdge para evento único
226
- * @example
227
- * ScheduleEdge.fromDatetime(new Datetime("2026-12-25T08:00:00"))
228
- * // agendamento para o Natal de 2026 às 8h
229
- */
230
- static fromDatetime(datetime) {
231
- const date = datetime.toDate();
232
- const minute = date.getMinutes();
233
- const hour = date.getHours();
234
- const day = date.getDate();
235
- const month = date.getMonth() + 1;
236
- const dayOfWeek = date.getDay();
237
- const cron = `${minute} ${hour} ${day} ${month} ${dayOfWeek}`;
238
- const scheduledFor = new SchedulingEdge(cron);
239
- scheduledFor.expiresInPacked = (0, optional_type_1.Optional)(datetime);
240
- return scheduledFor;
241
- }
242
- /**
243
- * Cria um ScheduleEdge para agendamentos diários em um horário específico.
244
- * @param time - Horário do agendamento no formato TimeEdge
245
- * @returns Nova instância de ScheduleEdge com recorrência diária
246
- * @example
247
- * ScheduleEdge.daily(new TimeEdge("08:00")) // todos os dias às 8h -> "0 8 * * *"
248
- */
249
- static daily(time) {
250
- const expression = `${time.getMinutes()} ${time.getHours()} * * *`;
251
- return new SchedulingEdge(expression);
252
- }
253
- /**
254
- * Cria um ScheduleEdge para agendamentos semanais em um dia e horário específico.
255
- * @param dayOfWeek - Dia da semana (0=domingo, 1=segunda, ..., 6=sábado)
256
- * @param time - Horário do agendamento no formato TimeEdge
257
- * @returns Nova instância de ScheduleEdge com recorrência semanal
258
- * @example
259
- * ScheduleEdge.weekly(1, new TimeEdge("08:00"))
260
- * // toda segunda-feira às 8h -> "0 8 * * 1"
261
- */
262
- static weekly(dayOfWeek, time) {
263
- const expression = `${time.getMinutes()} ${time.getHours()} * * ${dayOfWeek}`;
264
- return new SchedulingEdge(expression);
265
- }
266
- /**
267
- * Cria um ScheduleEdge para agendamentos mensais em um dia e horário específico.
268
- * @param dayOfMonth - Dia do mês (1-31)
269
- * @param time - Horário do agendamento no formato TimeEdge
270
- * @returns Nova instância de ScheduleEdge com recorrência mensal
271
- * @example
272
- * ScheduleEdge.monthly(15, new TimeEdge("08:00"))
273
- * // todo dia 15 de cada mês às 8h -> "0 8 15 * *"
274
- */
275
- static monthly(dayOfMonth, time) {
276
- const expression = `${time.getMinutes()} ${time.getHours()} ${dayOfMonth} * *`;
277
- return new SchedulingEdge(expression);
278
- }
279
- }
280
- exports.SchedulingEdge = SchedulingEdge;