hanzio 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +786 -239
  2. package/dist/api-wrapper/builders.d.ts +4 -3
  3. package/dist/api-wrapper/create-client.d.ts +1 -1
  4. package/dist/api-wrapper/describe.d.ts +16 -0
  5. package/dist/api-wrapper/endpoint.d.ts +18 -0
  6. package/dist/api-wrapper/errors.d.ts +39 -2
  7. package/dist/api-wrapper/index.d.ts +5 -0
  8. package/dist/api-wrapper/otel.d.ts +44 -0
  9. package/dist/api-wrapper/paginate.d.ts +12 -0
  10. package/dist/api-wrapper/redaction.d.ts +2 -0
  11. package/dist/api-wrapper/shared.d.ts +16 -2
  12. package/dist/api-wrapper/testing.d.ts +23 -0
  13. package/dist/api-wrapper/transport.d.ts +4 -5
  14. package/dist/api-wrapper/types.d.ts +103 -18
  15. package/dist/array/index.d.ts +50 -4
  16. package/dist/cache/createCache.d.ts +31 -0
  17. package/dist/cache/index.d.ts +19 -2
  18. package/dist/color/contrast.d.ts +40 -0
  19. package/dist/color/index.d.ts +2 -0
  20. package/dist/{math → color}/metricsSeriesColors.d.ts +14 -7
  21. package/dist/cool-console-log/index.d.ts +34 -5
  22. package/dist/crypto/encoding.d.ts +18 -0
  23. package/dist/crypto/hash.d.ts +33 -0
  24. package/dist/crypto/index.d.ts +4 -0
  25. package/dist/crypto/sealer.d.ts +25 -0
  26. package/dist/crypto/webhook.d.ts +20 -0
  27. package/dist/date/index.d.ts +46 -2
  28. package/dist/emitter/index.d.ts +21 -0
  29. package/dist/error/index.d.ts +12 -0
  30. package/dist/format/index.d.ts +102 -0
  31. package/dist/function/index.d.ts +60 -0
  32. package/dist/guard/index.d.ts +20 -0
  33. package/dist/i18n/index.d.ts +37 -0
  34. package/dist/index-0zvtcbzy.js +224 -0
  35. package/dist/index-8r2vdzjg.js +87 -0
  36. package/dist/index-hy7kbb99.js +157 -0
  37. package/dist/index-hyt6c56h.js +290 -0
  38. package/dist/{src/secrets/infisical.js → index-j1ybktbr.js} +500 -538
  39. package/dist/index-k9yx6bne.js +89 -0
  40. package/dist/index-kj1phgrx.js +169 -0
  41. package/dist/index-ktynw3vs.js +37 -0
  42. package/dist/index-mnkcfyx8.js +78 -0
  43. package/dist/{p-queue/index.js → index-pwt0dz63.js} +7 -11
  44. package/dist/index-rp5pqghz.js +157 -0
  45. package/dist/index-w882zry3.js +29 -0
  46. package/dist/index.d.ts +7 -7
  47. package/dist/jwt/index.d.ts +50 -2
  48. package/dist/math/index.d.ts +2 -2
  49. package/dist/math/linearRegressionTrend.d.ts +14 -1
  50. package/dist/math/scale.d.ts +8 -0
  51. package/dist/object/index.d.ts +19 -0
  52. package/dist/p-queue/index.d.ts +1 -1
  53. package/dist/promise/index.d.ts +97 -2
  54. package/dist/secrets/core.d.ts +7 -0
  55. package/dist/secrets/index.d.ts +3 -1
  56. package/dist/secrets/public-config.d.ts +7 -0
  57. package/dist/secrets/vite.d.ts +1 -0
  58. package/dist/secrets/worker.d.ts +1 -0
  59. package/dist/sitemap/index.d.ts +48 -6
  60. package/dist/src/api-wrapper/index.js +60 -1130
  61. package/dist/src/api-wrapper/testing.js +20 -0
  62. package/dist/{cool-console-log → src/cool-console-log}/index.js +80 -33
  63. package/dist/src/crypto/index.js +195 -0
  64. package/dist/src/format/index.js +211 -0
  65. package/dist/src/i18n/index.js +36 -0
  66. package/dist/src/index.js +739 -3145
  67. package/dist/src/jwt/index.js +138 -92
  68. package/dist/src/p-queue/index.js +9 -437
  69. package/dist/src/secrets/index.js +50 -1428
  70. package/dist/src/secrets/vite.js +10 -39
  71. package/dist/src/secrets/worker.js +14 -273
  72. package/dist/src/sitemap/index.js +183 -511
  73. package/dist/src/storage/index.js +119 -0
  74. package/dist/src/zod/index.js +340 -167
  75. package/dist/state/index.d.ts +21 -0
  76. package/dist/storage/index.d.ts +58 -0
  77. package/dist/string/index.d.ts +75 -2
  78. package/dist/typedswitch/index.d.ts +31 -24
  79. package/dist/types/index.d.ts +11 -0
  80. package/dist/url/index.d.ts +50 -1
  81. package/dist/zod/index.d.ts +32 -3
  82. package/dist/zod/introspect.d.ts +19 -0
  83. package/dist/zod/jsonToZodSchemaMapper.d.ts +3 -1
  84. package/dist/zod/zodMinMaxFilter.d.ts +22 -3
  85. package/dist/zod/zodToTypeString.d.ts +8 -3
  86. package/package.json +78 -7
  87. package/src/api-wrapper/actions-impl.ts +11 -72
  88. package/src/api-wrapper/builders.ts +32 -25
  89. package/src/api-wrapper/create-client.ts +171 -41
  90. package/src/api-wrapper/describe.ts +157 -0
  91. package/src/api-wrapper/endpoint.ts +26 -0
  92. package/src/api-wrapper/error-reporting.ts +7 -1
  93. package/src/api-wrapper/errors.ts +107 -2
  94. package/src/api-wrapper/headers.ts +11 -6
  95. package/src/api-wrapper/index.ts +5 -0
  96. package/src/api-wrapper/otel.ts +139 -0
  97. package/src/api-wrapper/paginate.ts +28 -0
  98. package/src/api-wrapper/redaction.ts +42 -0
  99. package/src/api-wrapper/shared.ts +21 -2
  100. package/src/api-wrapper/testing.ts +48 -0
  101. package/src/api-wrapper/transport.ts +41 -43
  102. package/src/api-wrapper/types.ts +185 -18
  103. package/src/array/index.ts +195 -42
  104. package/src/cache/createCache.ts +157 -0
  105. package/src/cache/index.ts +132 -147
  106. package/src/color/contrast.ts +163 -0
  107. package/src/color/index.ts +22 -0
  108. package/src/{math → color}/metricsSeriesColors.ts +47 -49
  109. package/src/cool-console-log/index.ts +128 -41
  110. package/src/crypto/encoding.ts +83 -0
  111. package/src/crypto/hash.ts +170 -0
  112. package/src/crypto/index.ts +26 -0
  113. package/src/crypto/sealer.ts +168 -0
  114. package/src/crypto/webhook.ts +86 -0
  115. package/src/date/index.ts +109 -34
  116. package/src/emitter/index.ts +82 -0
  117. package/src/error/index.ts +63 -0
  118. package/src/format/index.ts +389 -0
  119. package/src/function/index.ts +201 -0
  120. package/src/guard/index.ts +80 -0
  121. package/src/i18n/index.ts +125 -0
  122. package/src/index.ts +11 -7
  123. package/src/jwt/index.ts +199 -125
  124. package/src/math/index.ts +5 -10
  125. package/src/math/linearRegressionTrend.ts +33 -8
  126. package/src/math/scale.ts +17 -0
  127. package/src/object/index.ts +99 -0
  128. package/src/p-queue/index.ts +2 -0
  129. package/src/promise/index.ts +304 -9
  130. package/src/secrets/core.ts +72 -16
  131. package/src/secrets/index.ts +16 -4
  132. package/src/secrets/public-config.ts +47 -0
  133. package/src/secrets/vite.ts +2 -0
  134. package/src/secrets/worker.ts +2 -0
  135. package/src/sitemap/index.ts +293 -130
  136. package/src/state/index.ts +133 -81
  137. package/src/storage/index.ts +187 -0
  138. package/src/string/index.ts +261 -23
  139. package/src/typedswitch/index.ts +58 -38
  140. package/src/types/index.ts +14 -0
  141. package/src/url/index.ts +146 -1
  142. package/src/zod/index.ts +105 -9
  143. package/src/zod/introspect.ts +103 -0
  144. package/src/zod/jsonToZodSchemaMapper.ts +44 -21
  145. package/src/zod/zodMinMaxFilter.ts +37 -13
  146. package/src/zod/zodToTypeString.ts +184 -181
  147. package/dist/api-wrapper/index.js +0 -250
  148. package/dist/gzip/index.d.ts +0 -2
  149. package/dist/gzip/index.js +0 -16
  150. package/dist/index.js +0 -1823
  151. package/dist/jwt/index.js +0 -19
  152. package/dist/sitemap/index.js +0 -552
  153. package/dist/src/gzip/index.js +0 -16
  154. package/dist/src/secrets/loaders.js +0 -1529
  155. package/dist/zod/index.js +0 -210
@@ -0,0 +1,119 @@
1
+ // src/storage/index.ts
2
+ function createMemoryStorage() {
3
+ const map = new Map;
4
+ return {
5
+ getItem: (key) => map.get(key) ?? null,
6
+ setItem: (key, value) => {
7
+ map.set(key, String(value));
8
+ },
9
+ removeItem: (key) => {
10
+ map.delete(key);
11
+ }
12
+ };
13
+ }
14
+ var sharedMemoryStorage;
15
+ function defaultStorage() {
16
+ try {
17
+ const storage = globalThis.localStorage;
18
+ if (storage)
19
+ return storage;
20
+ } catch {}
21
+ sharedMemoryStorage ??= createMemoryStorage();
22
+ return sharedMemoryStorage;
23
+ }
24
+ function createCodec(options) {
25
+ const {
26
+ fallback,
27
+ parse = (raw) => raw,
28
+ serialize = JSON.stringify,
29
+ deserialize = JSON.parse
30
+ } = options;
31
+ return {
32
+ serialize,
33
+ decode(raw) {
34
+ if (raw === null)
35
+ return fallback;
36
+ try {
37
+ return parse(deserialize(raw));
38
+ } catch {
39
+ return fallback;
40
+ }
41
+ }
42
+ };
43
+ }
44
+ function createStorageItem(options) {
45
+ const { key, fallback, storage = defaultStorage() } = options;
46
+ const { serialize, decode } = createCodec(options);
47
+ let mirror;
48
+ const write = (value, action) => {
49
+ try {
50
+ action();
51
+ mirror = undefined;
52
+ } catch {
53
+ mirror = { value };
54
+ }
55
+ };
56
+ const get = () => {
57
+ if (mirror)
58
+ return mirror.value;
59
+ try {
60
+ return decode(storage.getItem(key));
61
+ } catch {
62
+ return fallback;
63
+ }
64
+ };
65
+ return {
66
+ key,
67
+ get,
68
+ set: (value) => write(value, () => storage.setItem(key, serialize(value))),
69
+ remove: () => write(fallback, () => storage.removeItem(key)),
70
+ subscribe(listener) {
71
+ const target = globalThis;
72
+ if (!target.addEventListener || !target.removeEventListener) {
73
+ return () => {};
74
+ }
75
+ const onStorage = (event) => {
76
+ if (event.storageArea !== storage)
77
+ return;
78
+ if (event.key !== key && event.key !== null)
79
+ return;
80
+ mirror = undefined;
81
+ listener(get());
82
+ };
83
+ target.addEventListener("storage", onStorage);
84
+ return () => target.removeEventListener?.("storage", onStorage);
85
+ }
86
+ };
87
+ }
88
+ function createAsyncStorageItem(options) {
89
+ const { key, fallback, storage } = options;
90
+ const { serialize, decode } = createCodec(options);
91
+ let mirror;
92
+ const write = async (value, action) => {
93
+ try {
94
+ await action();
95
+ mirror = undefined;
96
+ } catch {
97
+ mirror = { value };
98
+ }
99
+ };
100
+ return {
101
+ key,
102
+ async get() {
103
+ if (mirror)
104
+ return mirror.value;
105
+ try {
106
+ return decode(await storage.getItem(key));
107
+ } catch {
108
+ return fallback;
109
+ }
110
+ },
111
+ set: (value) => write(value, () => storage.setItem(key, serialize(value))),
112
+ remove: () => write(fallback, () => storage.removeItem(key))
113
+ };
114
+ }
115
+ export {
116
+ createAsyncStorageItem,
117
+ createMemoryStorage,
118
+ createStorageItem
119
+ };
@@ -1,32 +1,299 @@
1
+ import {
2
+ toArray2
3
+ } from "../../index-hy7kbb99.js";
4
+ import {
5
+ ok2,
6
+ err2
7
+ } from "../../index-0zvtcbzy.js";
8
+ import {
9
+ isRecord2
10
+ } from "../../index-8r2vdzjg.js";
11
+
1
12
  // src/zod/index.ts
2
13
  import { z as z3 } from "zod";
3
14
 
15
+ // src/zod/zodToTypeString.ts
16
+ var visiting = new Set;
17
+ function walk(schema, onCycle, fn) {
18
+ if (visiting.has(schema))
19
+ return onCycle;
20
+ visiting.add(schema);
21
+ try {
22
+ return fn(defOf(schema));
23
+ } finally {
24
+ visiting.delete(schema);
25
+ }
26
+ }
27
+ function defOf(schema) {
28
+ return schema._zod.def;
29
+ }
30
+ function pipeTarget(def) {
31
+ return defOf(def.out).type === "transform" ? def.in : def.out;
32
+ }
33
+ function literal(value) {
34
+ if (typeof value === "string")
35
+ return JSON.stringify(value);
36
+ return typeof value === "bigint" ? `${value}n` : String(value);
37
+ }
38
+ function wrap(type) {
39
+ return /[|&]/.test(type) ? `(${type})` : type;
40
+ }
41
+ function zodToTypeString(schema, indent = 0) {
42
+ return walk(schema, "unknown", (def) => {
43
+ const pad = " ".repeat(indent);
44
+ const innerPad = " ".repeat(indent + 1);
45
+ const render = (inner) => zodToTypeString(inner, indent);
46
+ switch (def.type) {
47
+ case "object": {
48
+ const entries = Object.entries(def.shape);
49
+ if (entries.length === 0)
50
+ return "{}";
51
+ const fields = entries.map(([key, value]) => {
52
+ const valueDef = defOf(value);
53
+ const isOptional = valueDef.type === "optional";
54
+ const typeStr = zodToTypeString(isOptional ? valueDef.innerType : value, indent + 1);
55
+ return `${innerPad}${key}${isOptional ? "?" : ""}: ${typeStr}`;
56
+ });
57
+ return `{
58
+ ${fields.join(`
59
+ `)}
60
+ ${pad}}`;
61
+ }
62
+ case "array":
63
+ return `${wrap(render(def.element))}[]`;
64
+ case "tuple": {
65
+ const items = def.items.map(render);
66
+ if (def.rest)
67
+ items.push(`...${wrap(render(def.rest))}[]`);
68
+ return `[${items.join(", ")}]`;
69
+ }
70
+ case "string":
71
+ case "number":
72
+ case "bigint":
73
+ case "boolean":
74
+ case "symbol":
75
+ case "null":
76
+ case "undefined":
77
+ case "void":
78
+ case "never":
79
+ case "any":
80
+ case "unknown":
81
+ return def.type;
82
+ case "date":
83
+ return "Date";
84
+ case "record":
85
+ return `Record<${render(def.keyType)}, ${render(def.valueType)}>`;
86
+ case "map":
87
+ return `Map<${render(def.keyType)}, ${render(def.valueType)}>`;
88
+ case "set":
89
+ return `Set<${render(def.valueType)}>`;
90
+ case "promise":
91
+ return `Promise<${render(def.innerType)}>`;
92
+ case "enum":
93
+ return Object.values(def.entries).map(literal).join(" | ");
94
+ case "literal":
95
+ return def.values.map(literal).join(" | ");
96
+ case "union":
97
+ return def.options.map(render).join(" | ");
98
+ case "intersection":
99
+ return `${wrap(render(def.left))} & ${wrap(render(def.right))}`;
100
+ case "optional":
101
+ return `${render(def.innerType)} | undefined`;
102
+ case "nullable":
103
+ return `${render(def.innerType)} | null`;
104
+ case "nonoptional": {
105
+ const innerDef = defOf(def.innerType);
106
+ return render(innerDef.type === "optional" ? innerDef.innerType : def.innerType);
107
+ }
108
+ case "default":
109
+ case "prefault":
110
+ case "catch":
111
+ case "readonly":
112
+ return render(def.innerType);
113
+ case "lazy":
114
+ return render(def.getter());
115
+ case "pipe":
116
+ return render(pipeTarget(def));
117
+ default:
118
+ return "unknown";
119
+ }
120
+ });
121
+ }
122
+ function zodToExample(schema) {
123
+ return walk(schema, null, (def) => {
124
+ switch (def.type) {
125
+ case "object": {
126
+ const result = {};
127
+ for (const [key, value] of Object.entries(def.shape)) {
128
+ if (defOf(value).type !== "optional") {
129
+ result[key] = zodToExample(value);
130
+ }
131
+ }
132
+ return result;
133
+ }
134
+ case "array":
135
+ return [zodToExample(def.element)];
136
+ case "set":
137
+ return [zodToExample(def.valueType)];
138
+ case "tuple":
139
+ return def.items.map(zodToExample);
140
+ case "string":
141
+ return "";
142
+ case "number":
143
+ case "bigint":
144
+ return 0;
145
+ case "boolean":
146
+ return false;
147
+ case "date":
148
+ return new Date(0).toISOString();
149
+ case "enum":
150
+ return Object.values(def.entries)[0];
151
+ case "literal":
152
+ return def.values[0];
153
+ case "union":
154
+ return zodToExample(def.options[0]);
155
+ case "intersection": {
156
+ const left = zodToExample(def.left);
157
+ const right = zodToExample(def.right);
158
+ return isRecord2(left) && isRecord2(right) ? { ...left, ...right } : left;
159
+ }
160
+ case "optional":
161
+ case "nullable":
162
+ case "nonoptional":
163
+ case "default":
164
+ case "prefault":
165
+ case "catch":
166
+ case "readonly":
167
+ case "promise":
168
+ return zodToExample(def.innerType);
169
+ case "lazy":
170
+ return zodToExample(def.getter());
171
+ case "pipe":
172
+ return zodToExample(pipeTarget(def));
173
+ case "record":
174
+ case "map":
175
+ return {};
176
+ default:
177
+ return null;
178
+ }
179
+ });
180
+ }
181
+
182
+ // src/zod/introspect.ts
183
+ function pipeInput(def) {
184
+ return defOf(def.in).type === "transform" ? def.out : def.in;
185
+ }
186
+ function unwrapOnce(def) {
187
+ switch (def.type) {
188
+ case "optional":
189
+ case "nullable":
190
+ case "default":
191
+ case "prefault":
192
+ case "nonoptional":
193
+ case "catch":
194
+ case "readonly":
195
+ return def.innerType;
196
+ case "lazy":
197
+ return def.getter();
198
+ case "pipe":
199
+ return pipeInput(def);
200
+ default:
201
+ return;
202
+ }
203
+ }
204
+ function unwrapSchema(schema) {
205
+ const inner = unwrapOnce(defOf(schema));
206
+ return inner ? unwrapSchema(inner) : schema;
207
+ }
208
+ function getEnumValues(schema) {
209
+ const def = defOf(unwrapSchema(schema));
210
+ return def.type === "enum" ? Object.values(def.entries).map(String) : undefined;
211
+ }
212
+ function getObjectShape(schema) {
213
+ const def = defOf(unwrapSchema(schema));
214
+ return def.type === "object" ? def.shape : undefined;
215
+ }
216
+ function zodDefaults(schema) {
217
+ return defaultFor(schema);
218
+ }
219
+ function defaultFor(schema) {
220
+ return walk(schema, undefined, (def) => {
221
+ switch (def.type) {
222
+ case "default":
223
+ case "prefault":
224
+ return def.defaultValue;
225
+ case "optional":
226
+ return;
227
+ case "nullable":
228
+ return null;
229
+ case "object": {
230
+ const result = {};
231
+ for (const [key, child] of Object.entries(def.shape)) {
232
+ result[key] = defaultFor(child);
233
+ }
234
+ return result;
235
+ }
236
+ case "array":
237
+ return [];
238
+ case "string":
239
+ return "";
240
+ case "number":
241
+ return 0;
242
+ case "bigint":
243
+ return 0n;
244
+ case "boolean":
245
+ return false;
246
+ case "enum":
247
+ return Object.values(def.entries)[0];
248
+ case "literal":
249
+ return def.values[0];
250
+ case "union":
251
+ return def.options[0] && defaultFor(def.options[0]);
252
+ default: {
253
+ const inner = unwrapOnce(def);
254
+ return inner && defaultFor(inner);
255
+ }
256
+ }
257
+ });
258
+ }
4
259
  // src/zod/jsonToZodSchemaMapper.ts
5
260
  import { z } from "zod";
6
261
  function jsonToZodSchemaMapper(jsonObject, zodSchema, config) {
262
+ return zodSchema.parse(mapObject(jsonObject, zodSchema, config));
263
+ }
264
+ function mapObject(jsonObject, schema, config) {
265
+ const shape = schema instanceof z.ZodObject ? schema.shape : {};
7
266
  const result = {};
8
- const shape = zodSchema instanceof z.ZodObject ? zodSchema.shape : {};
9
- for (const key of Object.keys(shape)) {
267
+ for (const [key, fieldSchema] of Object.entries(shape)) {
10
268
  const fieldConfig = config[key];
11
- let value = jsonObject[key];
12
- if (fieldConfig) {
13
- value = fieldConfig(jsonObject);
269
+ if (typeof fieldConfig === "function") {
270
+ result[key] = fieldConfig(jsonObject);
271
+ continue;
14
272
  }
15
- if (shape[key] instanceof z.ZodObject && value && typeof value === "object") {
16
- result[key] = jsonToZodSchemaMapper(value, shape[key], config[key] || {});
273
+ const nested = fieldConfig ?? {};
274
+ const value = jsonObject[key];
275
+ const inner = unwrap(fieldSchema);
276
+ const element = inner instanceof z.ZodArray && unwrap(inner.element);
277
+ if (inner instanceof z.ZodObject && isRecord2(value)) {
278
+ result[key] = mapObject(value, inner, nested);
279
+ } else if (element instanceof z.ZodObject && Array.isArray(value)) {
280
+ result[key] = value.map((item) => isRecord2(item) ? mapObject(item, element, nested) : item);
17
281
  } else {
18
282
  result[key] = value;
19
283
  }
20
284
  }
21
- return zodSchema.parse(result);
285
+ return result;
286
+ }
287
+ function unwrap(schema) {
288
+ return schema instanceof z.ZodOptional || schema instanceof z.ZodNullable ? unwrap(schema.unwrap()) : schema;
22
289
  }
23
290
  // src/zod/zodMinMaxFilter.ts
24
291
  import { z as z2 } from "zod";
25
- var zodMinMaxFilter = z2.object({
26
- min: z2.number().optional(),
27
- max: z2.number().optional()
28
- });
29
- function toGteLteFilter(filter) {
292
+ function createMinMaxFilter(schema) {
293
+ return z2.object({ min: schema.optional(), max: schema.optional() });
294
+ }
295
+ var zodMinMaxFilter = createMinMaxFilter(z2.number());
296
+ function toRange(filter, lower, upper) {
30
297
  if (!filter)
31
298
  return;
32
299
  const hasMin = filter.min !== undefined;
@@ -34,176 +301,82 @@ function toGteLteFilter(filter) {
34
301
  if (!hasMin && !hasMax)
35
302
  return;
36
303
  return {
37
- ...hasMin && { gte: filter.min },
38
- ...hasMax && { lte: filter.max }
304
+ ...hasMin && { [lower]: filter.min },
305
+ ...hasMax && { [upper]: filter.max }
39
306
  };
40
307
  }
41
- // src/zod/zodToTypeString.ts
42
- function getDefProp(def, prop) {
43
- return def?.[prop];
308
+ function toGteLteFilter(filter) {
309
+ return toRange(filter, "gte", "lte");
44
310
  }
45
- function zodToTypeString(schema, indent = 0) {
46
- const pad = " ".repeat(indent);
47
- const innerPad = " ".repeat(indent + 1);
48
- const def = schema._zod?.def ?? schema._def;
49
- if (!def)
50
- return "unknown";
51
- const schemaType = getDefProp(def, "type") ?? getDefProp(def, "typeName");
52
- switch (schemaType) {
53
- case "object": {
54
- const shape = getDefProp(def, "shape");
55
- if (!shape || Object.keys(shape).length === 0)
56
- return "{}";
57
- const fields = Object.entries(shape).map(([key, value]) => {
58
- const valueType = getDefProp(value._zod?.def ?? value._def, "type");
59
- const isOptional = valueType === "optional";
60
- const innerSchema = isOptional ? getDefProp(value._zod?.def ?? value._def, "innerType") ?? value : value;
61
- const typeStr = zodToTypeString(innerSchema, indent + 1);
62
- return `${innerPad}${key}${isOptional ? "?" : ""}: ${typeStr}`;
63
- });
64
- return `{
65
- ${fields.join(`
66
- `)}
67
- ${pad}}`;
68
- }
69
- case "array": {
70
- const itemType = getDefProp(def, "element") ?? getDefProp(def, "type");
71
- return itemType ? `${zodToTypeString(itemType, indent)}[]` : "unknown[]";
72
- }
73
- case "string":
74
- return "string";
75
- case "number":
76
- return "number";
77
- case "boolean":
78
- return "boolean";
79
- case "date":
80
- return "Date";
81
- case "null":
82
- return "null";
83
- case "undefined":
84
- return "undefined";
85
- case "any":
86
- return "any";
87
- case "unknown":
88
- return "unknown";
89
- case "record": {
90
- const valueType = getDefProp(def, "valueType");
91
- return valueType ? `Record<string, ${zodToTypeString(valueType, indent)}>` : "Record<string, unknown>";
92
- }
93
- case "enum": {
94
- const values = getDefProp(def, "values");
95
- return values ? values.map((v) => `"${v}"`).join(" | ") : "string";
96
- }
97
- case "literal": {
98
- const value = getDefProp(def, "value");
99
- return typeof value === "string" ? `"${value}"` : String(value);
100
- }
101
- case "union": {
102
- const options = getDefProp(def, "options");
103
- return options ? options.map((o) => zodToTypeString(o, indent)).join(" | ") : "unknown";
104
- }
105
- case "optional": {
106
- const inner = getDefProp(def, "innerType");
107
- return inner ? `${zodToTypeString(inner, indent)} | undefined` : "unknown";
108
- }
109
- case "nullable": {
110
- const inner = getDefProp(def, "innerType");
111
- return inner ? `${zodToTypeString(inner, indent)} | null` : "unknown";
112
- }
113
- case "default": {
114
- const inner = getDefProp(def, "innerType");
115
- return inner ? zodToTypeString(inner, indent) : "unknown";
116
- }
117
- case "ZodObject":
118
- case "ZodArray":
119
- case "ZodString":
120
- case "ZodNumber":
121
- case "ZodBoolean":
122
- case "ZodDate":
123
- case "ZodNull":
124
- case "ZodUndefined":
125
- case "ZodAny":
126
- case "ZodUnknown":
127
- case "ZodRecord":
128
- case "ZodEnum":
129
- case "ZodLiteral":
130
- case "ZodUnion":
131
- case "ZodOptional":
132
- case "ZodNullable":
133
- case "ZodDefault":
134
- return zodToTypeString(schema, indent);
135
- default:
136
- return "unknown";
137
- }
138
- }
139
- function zodToExample(schema) {
140
- const def = schema._zod?.def ?? schema._def;
141
- if (!def)
142
- return null;
143
- const schemaType = getDefProp(def, "type") ?? getDefProp(def, "typeName");
144
- switch (schemaType) {
145
- case "object": {
146
- const shape = getDefProp(def, "shape");
147
- if (!shape)
148
- return {};
149
- const result = {};
150
- for (const [key, value] of Object.entries(shape)) {
151
- const valueType = getDefProp(value._zod?.def ?? value._def, "type");
152
- const isOptional = valueType === "optional";
153
- if (!isOptional) {
154
- result[key] = zodToExample(value);
155
- }
156
- }
157
- return result;
158
- }
159
- case "array": {
160
- const itemType = getDefProp(def, "element") ?? getDefProp(def, "type");
161
- return itemType ? [zodToExample(itemType)] : [];
162
- }
163
- case "string":
164
- return "";
165
- case "number":
166
- return 0;
167
- case "boolean":
168
- return false;
169
- case "enum": {
170
- const values = getDefProp(def, "values");
171
- return values?.[0] ?? "";
172
- }
173
- case "literal":
174
- return getDefProp(def, "value");
175
- case "optional":
176
- case "default": {
177
- const inner = getDefProp(def, "innerType");
178
- return inner ? zodToExample(inner) : null;
179
- }
180
- case "record":
181
- return {};
182
- default:
183
- return null;
184
- }
311
+ function toGtLtFilter(filter) {
312
+ return toRange(filter, "gt", "lt");
185
313
  }
186
314
 
187
315
  // src/zod/index.ts
188
- function createZId(typeName) {
189
- return z3.string().min(1, `${typeName} ID is required`).brand();
316
+ function createZId(typeName, { prefix = "" } = {}) {
317
+ return z3.string().min(1, `${typeName} ID is required`).startsWith(prefix, `${typeName} ID must start with "${prefix}"`).brand();
318
+ }
319
+ function asId(value) {
320
+ return value;
321
+ }
322
+ function parseId(typeName, value) {
323
+ return createZId(typeName).parse(value);
324
+ }
325
+ function safeParseId(typeName, value) {
326
+ return toResult(createZId(typeName).safeParse(value));
327
+ }
328
+ function createIdHelpers() {
329
+ return {
330
+ zId: (typeName) => createZId(typeName),
331
+ asId,
332
+ parseId,
333
+ safeParseId
334
+ };
335
+ }
336
+ var zJsonValue = z3.lazy(() => z3.union([
337
+ z3.string(),
338
+ z3.number(),
339
+ z3.boolean(),
340
+ z3.null(),
341
+ z3.array(zJsonValue),
342
+ zJsonObject
343
+ ]));
344
+ var zJsonObject = z3.record(z3.string(), zJsonValue);
345
+ function parseJson(text, schema) {
346
+ let value;
347
+ try {
348
+ value = JSON.parse(text);
349
+ } catch (error) {
350
+ return { ok: false, data: null, error };
351
+ }
352
+ return toResult(schema.safeParse(value));
353
+ }
354
+ function toResult(result) {
355
+ return result.success ? ok2(result.data) : err2(result.error);
190
356
  }
191
357
  function zSingleOrArray(schema) {
192
358
  return z3.union([z3.array(schema), schema]);
193
359
  }
194
- function normalizeSingleOrArray(value) {
195
- if (value == null)
196
- return [];
197
- if (Array.isArray(value))
198
- return [...value];
199
- return [value];
200
- }
360
+ var normalizeSingleOrArray = toArray2;
201
361
  export {
362
+ asId,
363
+ createIdHelpers,
364
+ createMinMaxFilter,
202
365
  createZId,
366
+ getEnumValues,
367
+ getObjectShape,
203
368
  jsonToZodSchemaMapper,
204
369
  normalizeSingleOrArray,
370
+ parseId,
371
+ parseJson,
372
+ safeParseId,
373
+ toGtLtFilter,
205
374
  toGteLteFilter,
375
+ unwrapSchema,
376
+ zJsonObject,
377
+ zJsonValue,
206
378
  zSingleOrArray,
379
+ zodDefaults,
207
380
  zodMinMaxFilter,
208
381
  zodToExample,
209
382
  zodToTypeString
@@ -46,6 +46,10 @@ export interface StateMachineConfig<TState extends string, TAction extends strin
46
46
  stateTransitions: Record<TState, readonly TState[]>;
47
47
  validators?: Partial<Record<TState, ValidatorFn<TState, TContext, TAction>>>;
48
48
  globalValidator?: ValidatorFn<TState, TContext, TAction>;
49
+ actionValidators?: Partial<Record<TAction, ValidatorFn<TState, TContext, TAction>>>;
50
+ initialState?: TState;
51
+ onTransition?: (context: TContext, from: TState, to: TState, action: TAction) => void | Promise<void>;
52
+ applyTransition?: boolean;
49
53
  actions?: {
50
54
  [K in TAction]?: ActionHandlerFn<TContext, TActionDataMap[K], TActionResultMap[K]>;
51
55
  };
@@ -74,6 +78,12 @@ export declare class SimpleStateMachine<TState extends string, TAction extends s
74
78
  * @returns Map of target states to validation results (true if any action to that state validates)
75
79
  */
76
80
  getPossibleTransitions(): Promise<Partial<Record<TState, ValidationResult>>>;
81
+ /**
82
+ * Checks whether an action can be executed from the current state
83
+ *
84
+ * @returns true, or the reason the action is not allowed
85
+ */
86
+ canExecute(action: TAction): Promise<ValidationResult>;
77
87
  /**
78
88
  * Executes an action with additional data
79
89
  *
@@ -99,3 +109,14 @@ export declare class SimpleStateMachine<TState extends string, TAction extends s
99
109
  */
100
110
  getInitialState(): TState | undefined;
101
111
  }
112
+ /**
113
+ * Defines a state machine config once and binds it to items on demand
114
+ *
115
+ * @example
116
+ * const orderMachine = createStateMachine<Status, Action, Order>(config)
117
+ * const machine = orderMachine.for(order, 'status')
118
+ */
119
+ export declare function createStateMachine<TState extends string, TAction extends string, TContext, TActionDataMap extends ActionDataMap<TAction> = ActionDataMap<TAction>, TActionResultMap extends ActionResultMap<TAction> = ActionResultMap<TAction>>(config: StateMachineConfig<TState, TAction, TContext, TActionDataMap, TActionResultMap>): {
120
+ config: StateMachineConfig<TState, TAction, TContext, TActionDataMap, TActionResultMap>;
121
+ for: (item: TContext, stateKey: StateKey<TContext, TState>) => SimpleStateMachine<TState, TAction, TContext, TActionDataMap, TActionResultMap>;
122
+ };