@wildo-ai/zod-decorators 1.0.1 → 1.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.
- package/LICENSE +34 -0
- package/dist/esm/.builder.pid +9 -0
- package/dist/esm/__mocks__/mime.d.ts.map +1 -1
- package/dist/esm/__mocks__/mime.js +1 -1
- package/dist/esm/__mocks__/mime.js.map +1 -1
- package/dist/esm/commons.d.ts.map +1 -1
- package/dist/esm/commons.js +1 -1
- package/dist/esm/commons.js.map +1 -1
- package/dist/esm/companion-exports.d.ts +8 -0
- package/dist/esm/companion-exports.d.ts.map +1 -0
- package/dist/esm/companion-exports.js +8 -0
- package/dist/esm/companion-exports.js.map +1 -0
- package/dist/esm/currencies.shared.schemas.d.ts.map +1 -1
- package/dist/esm/currencies.shared.schemas.js +1 -1
- package/dist/esm/currencies.shared.schemas.js.map +1 -1
- package/dist/esm/files/agent-file-formats.d.ts.map +1 -1
- package/dist/esm/files/agent-file-formats.js +1 -1
- package/dist/esm/files/agent-file-formats.js.map +1 -1
- package/dist/esm/files/extension-nature-map.d.ts +1 -1
- package/dist/esm/files/extension-nature-map.d.ts.map +1 -1
- package/dist/esm/files/extension-nature-map.js +1 -1
- package/dist/esm/files/extension-nature-map.js.map +1 -1
- package/dist/esm/files/file-extensions.enum.d.ts.map +1 -1
- package/dist/esm/files/file-extensions.enum.js +1 -1
- package/dist/esm/files/file-extensions.enum.js.map +1 -1
- package/dist/esm/files/mime-registry.d.ts +1 -1
- package/dist/esm/files/mime-registry.d.ts.map +1 -1
- package/dist/esm/files/mime-registry.js +1 -1
- package/dist/esm/files/mime-registry.js.map +1 -1
- package/dist/esm/files/unified-registry.d.ts +1 -1
- package/dist/esm/files/unified-registry.d.ts.map +1 -1
- package/dist/esm/files/unified-registry.js +1 -1
- package/dist/esm/files/unified-registry.js.map +1 -1
- package/dist/esm/index.d.ts +20 -19
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +10 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/install-bigint-json-encoding.d.ts +80 -0
- package/dist/esm/install-bigint-json-encoding.d.ts.map +1 -0
- package/dist/esm/install-bigint-json-encoding.js +85 -0
- package/dist/esm/install-bigint-json-encoding.js.map +1 -0
- package/dist/esm/testing/decorated-test-schemas.d.ts +8 -8
- package/dist/esm/testing/decorated-test-schemas.d.ts.map +1 -1
- package/dist/esm/testing/decorated-test-schemas.js +1 -1
- package/dist/esm/testing/decorated-test-schemas.js.map +1 -1
- package/dist/esm/testing.d.ts +1 -1
- package/dist/esm/testing.d.ts.map +1 -1
- package/dist/esm/testing.js +1 -1
- package/dist/esm/testing.js.map +1 -1
- package/dist/esm/zod-bigdecimal.d.ts +5 -1
- package/dist/esm/zod-bigdecimal.d.ts.map +1 -1
- package/dist/esm/zod-bigdecimal.js +4 -1
- package/dist/esm/zod-bigdecimal.js.map +1 -1
- package/dist/esm/zod-code.d.ts +4 -1
- package/dist/esm/zod-code.d.ts.map +1 -1
- package/dist/esm/zod-code.js +4 -1
- package/dist/esm/zod-code.js.map +1 -1
- package/dist/esm/zod-color.d.ts.map +1 -1
- package/dist/esm/zod-color.js +1 -1
- package/dist/esm/zod-color.js.map +1 -1
- package/dist/esm/zod-decorators.types.d.ts +1410 -56
- package/dist/esm/zod-decorators.types.d.ts.map +1 -1
- package/dist/esm/zod-decorators.types.js +662 -16
- package/dist/esm/zod-decorators.types.js.map +1 -1
- package/dist/esm/zod-duration.d.ts +8 -4
- package/dist/esm/zod-duration.d.ts.map +1 -1
- package/dist/esm/zod-duration.js +2 -1
- package/dist/esm/zod-duration.js.map +1 -1
- package/dist/esm/zod-file.d.ts +75 -14
- package/dist/esm/zod-file.d.ts.map +1 -1
- package/dist/esm/zod-file.js +151 -8
- package/dist/esm/zod-file.js.map +1 -1
- package/dist/esm/zod-money.d.ts +18 -3
- package/dist/esm/zod-money.d.ts.map +1 -1
- package/dist/esm/zod-money.js +4 -1
- package/dist/esm/zod-money.js.map +1 -1
- package/dist/esm/zod-phone.d.ts +37 -1
- package/dist/esm/zod-phone.d.ts.map +1 -1
- package/dist/esm/zod-phone.js +66 -5
- package/dist/esm/zod-phone.js.map +1 -1
- package/dist/esm/zod-range.d.ts +4 -1
- package/dist/esm/zod-range.d.ts.map +1 -1
- package/dist/esm/zod-range.js +4 -1
- package/dist/esm/zod-range.js.map +1 -1
- package/dist/esm/zod-utils.shared.d.ts +411 -6
- package/dist/esm/zod-utils.shared.d.ts.map +1 -1
- package/dist/esm/zod-utils.shared.js +624 -9
- package/dist/esm/zod-utils.shared.js.map +1 -1
- package/dist/esm/zod-versioned.d.ts +1 -1
- package/dist/esm/zod-versioned.d.ts.map +1 -1
- package/dist/esm/zod-versioned.js +1 -1
- package/dist/esm/zod-versioned.js.map +1 -1
- package/dist/esm/zod.module-override.d.ts +458 -68
- package/dist/esm/zod.module-override.d.ts.map +1 -1
- package/dist/esm/zod.module-override.js +1214 -195
- package/dist/esm/zod.module-override.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +20 -11
package/dist/esm/zod-money.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { DecoratorInput, MoneySchemaOptions, SummaryFieldParams, ZodDecorator, ZodDecorator_ParamsType } from "./zod-decorators.types
|
|
1
|
+
import { DecoratorInput, MoneySchemaOptions, SummaryFieldParams, ZodDecorator, ZodDecorator_ParamsType } from "./zod-decorators.types";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import { CurrencySchema } from "./currencies.shared.schemas
|
|
3
|
+
import { CurrencySchema } from "./currencies.shared.schemas";
|
|
4
4
|
/**
|
|
5
5
|
* Money value type - represents a monetary amount with bigint storage.
|
|
6
6
|
*
|
|
@@ -12,7 +12,18 @@ import { CurrencySchema } from "./currencies.shared.schemas.js";
|
|
|
12
12
|
* Example: { amount: 1999n, currency: 'USD', decimals: 2 } = $19.99
|
|
13
13
|
*/
|
|
14
14
|
export interface MoneyValue {
|
|
15
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* Amount in smallest unit (e.g., cents). BigInt to avoid precision issues with
|
|
17
|
+
* large amounts.
|
|
18
|
+
*
|
|
19
|
+
* WIRE CONTRACT: a `bigint` has no JSON form, so on the wire (and at rest in
|
|
20
|
+
* Mongo) this amount is a decimal STRING (e.g. `"1999"`). Outbound it is encoded
|
|
21
|
+
* by `BigInt.prototype.toJSON` (`installBigIntJsonEncoding`, same package);
|
|
22
|
+
* inbound it is coerced back to `bigint` by `applyNetworkBoundaryCoercion`
|
|
23
|
+
* (`@wildo-ai/saas-models`) on the shared request/response DTO — so both the
|
|
24
|
+
* frontend and backend hold a real `bigint` at runtime. Full mechanism map:
|
|
25
|
+
* `install-bigint-json-encoding.ts`.
|
|
26
|
+
*/
|
|
16
27
|
amount: bigint;
|
|
17
28
|
/** ISO 4217 currency code (e.g., 'USD', 'EUR', 'BTC') */
|
|
18
29
|
currency: string;
|
|
@@ -28,6 +39,8 @@ export declare const MoneyValueSchema: z.ZodObject<{
|
|
|
28
39
|
decimals: z.ZodNumber;
|
|
29
40
|
}>;
|
|
30
41
|
/**
|
|
42
|
+
* @wildo_source:part:start zod.factories.money facet:layer:shared facet:family:schema-factory
|
|
43
|
+
*
|
|
31
44
|
* z_money() - Creates money schemas for financial amounts.
|
|
32
45
|
*
|
|
33
46
|
* Money values are stored as integers to avoid floating-point precision issues.
|
|
@@ -88,6 +101,7 @@ export type DecoratedMoneySchema = z.ZodObject<{
|
|
|
88
101
|
[ZodDecorator.IS_NOT_EDITABLE](params?: ZodDecorator_ParamsType[ZodDecorator.IS_NOT_EDITABLE]): DecoratedMoneySchema;
|
|
89
102
|
[ZodDecorator.IS_SUMMARY_FIELD](params?: SummaryFieldParams): DecoratedMoneySchema;
|
|
90
103
|
[ZodDecorator.IS_BACKEND_ONLY](params?: ZodDecorator_ParamsType[ZodDecorator.IS_BACKEND_ONLY]): DecoratedMoneySchema;
|
|
104
|
+
[ZodDecorator.IS_WRITE_ONLY_SECRET](params?: ZodDecorator_ParamsType[ZodDecorator.IS_WRITE_ONLY_SECRET]): DecoratedMoneySchema;
|
|
91
105
|
[ZodDecorator.EXCLUDE_FROM_CREATE](): DecoratedMoneySchema;
|
|
92
106
|
[ZodDecorator.EXCLUDE_FROM_UPDATE](): DecoratedMoneySchema;
|
|
93
107
|
addDecorators(decorators: DecoratorInput[]): DecoratedMoneySchema;
|
|
@@ -123,6 +137,7 @@ export type DecoratedMoneySchema = z.ZodObject<{
|
|
|
123
137
|
* ```
|
|
124
138
|
*/
|
|
125
139
|
export declare function z_money(options?: MoneySchemaOptions): DecoratedMoneySchema;
|
|
140
|
+
/** @wildo_source:part:end zod.factories.money */
|
|
126
141
|
/**
|
|
127
142
|
* Convert a decimal amount to bigint representation.
|
|
128
143
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod-money.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"zod-money.d.ts","sourceRoot":"","sources":["../../../src/zod-money.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAA6D,kBAAkB,EAAE,kBAAkB,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAClM,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D;;;;;;;;;GASG;AACH,MAAM,WAAW,UAAU;IACzB;;;;;;;;;;;OAWG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,yDAAyD;IACzD,QAAQ,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,eAAO,MAAM,gBAAgB,EAAE,CAAC,CAAC,SAAS,CAAC;IAAE,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC;IAAC,QAAQ,EAAE,OAAO,cAAc,CAAC;IAAC,QAAQ,EAAE,CAAC,CAAC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;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,OAAO,CACrB,OAAO,CAAC,EAAE,kBAAkB,GAC3B,oBAAoB,CAEtB;AACD,iDAAiD;AAMjD;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAExE;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAItE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CA+BzF;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAgBrG;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,UAAU,EACjB,OAAO,GAAE;IACP,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,cAAc,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;IACpC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACtB,GACL,MAAM,CA8BR"}
|
package/dist/esm/zod-money.js
CHANGED
|
@@ -14,6 +14,8 @@ export const MoneyValueSchema = z.object({
|
|
|
14
14
|
decimals: z.number().int().min(0).max(18),
|
|
15
15
|
});
|
|
16
16
|
/**
|
|
17
|
+
* @wildo_source:part:start zod.factories.money facet:layer:shared facet:family:schema-factory
|
|
18
|
+
*
|
|
17
19
|
* z_money() - Creates money schemas for financial amounts.
|
|
18
20
|
*
|
|
19
21
|
* Money values are stored as integers to avoid floating-point precision issues.
|
|
@@ -124,6 +126,7 @@ export function createMoneySchema(options = {}) {
|
|
|
124
126
|
export function z_money(options) {
|
|
125
127
|
return createMoneySchema(options);
|
|
126
128
|
}
|
|
129
|
+
/** @wildo_source:part:end zod.factories.money */
|
|
127
130
|
// ============================================================================
|
|
128
131
|
// MONEY UTILITY FUNCTIONS
|
|
129
132
|
// ============================================================================
|
|
@@ -290,4 +293,4 @@ export function formatMoney(money, options = {}) {
|
|
|
290
293
|
? `${symbol} ${formattedNumber}`
|
|
291
294
|
: `${formattedNumber} ${symbol}`;
|
|
292
295
|
}
|
|
293
|
-
//# sourceMappingURL=zod-money.js.map
|
|
296
|
+
//# sourceMappingURL=zod-money.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod-money.js","sourceRoot":"","sources":["../../src/zod-money.ts"],"names":[],"mappings":"AACA,+EAA+E;AAC/E,sBAAsB;AACtB,+EAA+E;AAE/E,OAAO,EAAkB,eAAe,EAAoF,YAAY,EAA2B,MAAM,wBAAwB,CAAC;AAClM,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAqB7D;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAiG,CAAC,CAAC,MAAM,CAAC;IACrI,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE;IAClB,QAAQ,EAAE,cAAc;IACxB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;CAC1C,CAAC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH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AC,CAAC;IAEnF,0BAA0B;IAC1B,MAAM,gBAAgB,GAAG,WAAW,CAAC,OAAO,CAAC,uBAAuB,EAAE,kBAAkB,CAAC,CAAC;IAE1F,MAAM,eAAe,GAAG,WAAW;QACjC,CAAC,CAAC,GAAG,gBAAgB,GAAG,gBAAgB,GAAG,WAAW,EAAE;QACxD,CAAC,CAAC,gBAAgB,CAAC;IAErB,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,gFAAgF;IAChF,MAAM,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC;IAE9B,OAAO,cAAc,KAAK,QAAQ;QAChC,CAAC,CAAC,GAAG,MAAM,IAAI,eAAe,EAAE;QAChC,CAAC,CAAC,GAAG,eAAe,IAAI,MAAM,EAAE,CAAC;AACrC,CAAC","sourcesContent":["\n// ============================================================================\n// MONEY SCHEMA HELPER\n// ============================================================================\n\nimport { DecoratorInput, SCHEMA_METADATA, CustomFieldMetadata, MoneySchemaMetadata, MoneySchemaOptions, SummaryFieldParams, ZodDecorator, ZodDecorator_ParamsType } from \"./zod-decorators.types\";\nimport { z } from \"zod\";\nimport { addChainableMethods } from \"./zod.module-override\";\nimport { CurrencySchema } from \"./currencies.shared.schemas\";\n\n/**\n * Money value type - represents a monetary amount with bigint storage.\n *\n * The amount is stored as a bigint in the smallest unit (e.g., cents for USD).\n * Using bigint ensures no precision loss for arbitrarily large amounts.\n * The decimals field indicates how to convert to the display value:\n * - displayValue = Number(amount) / (10 ** decimals)\n *\n * Example: { amount: 1999n, currency: 'USD', decimals: 2 } = $19.99\n */\nexport interface MoneyValue {\n /**\n * Amount in smallest unit (e.g., cents). BigInt to avoid precision issues with\n * large amounts.\n *\n * WIRE CONTRACT: a `bigint` has no JSON form, so on the wire (and at rest in\n * Mongo) this amount is a decimal STRING (e.g. `\"1999\"`). Outbound it is encoded\n * by `BigInt.prototype.toJSON` (`installBigIntJsonEncoding`, same package);\n * inbound it is coerced back to `bigint` by `applyNetworkBoundaryCoercion`\n * (`@wildo-ai/saas-models`) on the shared request/response DTO — so both the\n * frontend and backend hold a real `bigint` at runtime. Full mechanism map:\n * `install-bigint-json-encoding.ts`.\n */\n amount: bigint;\n /** ISO 4217 currency code (e.g., 'USD', 'EUR', 'BTC') */\n currency: string;\n /** Number of decimal places for display (e.g., 2 for USD, 8 for BTC) */\n decimals: number;\n}\n\n/**\n * Zod schema for MoneyValue.\n */\nexport const MoneyValueSchema: z.ZodObject<{ amount: z.ZodBigInt; currency: typeof CurrencySchema; decimals: z.ZodNumber }> = z.object({\n amount: z.bigint(),\n currency: CurrencySchema,\n decimals: z.number().int().min(0).max(18),\n});\n\n/**\n * @wildo_source:part:start zod.factories.money facet:layer:shared facet:family:schema-factory\n *\n * z_money() - Creates money schemas for financial amounts.\n *\n * Money values are stored as integers to avoid floating-point precision issues.\n * The schema creates an object with: { amount, currency, decimals }\n *\n * @example\n * ```typescript\n * import { z_money } from '@wildo-ai/zod-decorators';\n *\n * const price = z_money();\n * const fiatPrice = z_money({ currenciesAllowed: [CurrencyAllowed.FIAT] });\n * const usdPrice = z_money({ allowCurrencyChange: false }).moneyUI({ edit: { defaultCurrency: 'USD' } });\n *\n * // With decorators (chainable)\n * z_money().moneyUI({ edit: { defaultCurrency: 'EUR' } })\n * z_money({ currenciesAllowed: [CurrencyAllowed.FIAT_MAJOR] }).isHidden({ edit: true })\n * ```\n */\n\n/**\n * Creates a money schema with metadata for detection and form component rendering.\n *\n * @param options - Configuration options for money field\n * @returns A Zod object schema with metadata for money detection\n *\n * @example\n * ```typescript\n * // Simple money (all currencies)\n * const price = z_money();\n * // Infers: { amount: bigint, currency: string, decimals: number }\n *\n * // Fiat only (no crypto)\n * const fiatPrice = z_money({ currenciesAllowed: [CurrencyAllowed.FIAT] });\n *\n * // Fixed currency with amount constraints\n * const usdPrice = z_money({\n * allowCurrencyChange: false,\n * minAmount: 0n,\n * maxAmount: 100000000n // $1,000,000.00 in cents\n * }).moneyUI({ edit: { defaultCurrency: 'USD' } });\n * ```\n */\nexport function createMoneySchema(\n options: MoneySchemaOptions = {}\n): DecoratedMoneySchema {\n const {\n currenciesAllowed,\n appEnabledOnly = true,\n allowCurrencyChange = true,\n minAmount,\n maxAmount,\n } = options;\n\n // Create the amount schema with optional min/max constraints\n // Using bigint for amount to avoid precision issues with large financial amounts\n let amountSchema = z.bigint();\n if (minAmount !== undefined) {\n amountSchema = amountSchema.min(minAmount);\n }\n if (maxAmount !== undefined) {\n amountSchema = amountSchema.max(maxAmount);\n }\n\n // Create the money object schema\n const moneySchema = z.object({\n amount: amountSchema,\n currency: CurrencySchema,\n decimals: z.number().int().min(0).max(18),\n });\n\n const moneyMetadata: MoneySchemaMetadata = {\n isMoney: true,\n ...(currenciesAllowed && currenciesAllowed.length > 0 && { currenciesAllowed }),\n appEnabledOnly,\n allowCurrencyChange,\n ...(minAmount !== undefined && { minAmount }),\n ...(maxAmount !== undefined && { maxAmount }),\n };\n\n // Initialize or extend SCHEMA_METADATA with money config\n const existingMetadata: CustomFieldMetadata = (moneySchema as any)[SCHEMA_METADATA] || {};\n (moneySchema as any)[SCHEMA_METADATA] = {\n ...existingMetadata,\n moneyConfig: moneyMetadata,\n };\n\n // Add chainable decorator methods to the money schema instance\n // This allows: z_money().moneyUI({ edit: { defaultCurrency: 'EUR' } }).isHidden()\n addChainableMethods(moneySchema);\n\n return moneySchema as DecoratedMoneySchema;\n}\n\n/**\n * Return type for money schemas - includes decorator methods.\n * Note: IS_FOREIGN_KEY is not applicable to money objects.\n * IS_DB_INDEXED will index internal fields (amount, currency) for query optimization.\n *\n * This type must list all decorators applicable to ZodObject (per ApplyableTypeAllTypes).\n * Missing entries here cause TS errors when chaining decorators on z_money() fields.\n */\nexport type DecoratedMoneySchema = z.ZodObject<{\n amount: z.ZodBigInt;\n currency: typeof CurrencySchema;\n decimals: z.ZodNumber;\n}> & {\n [ZodDecorator.IS_DB_INDEXED](): DecoratedMoneySchema;\n [ZodDecorator.IS_HIDDEN](params?: ZodDecorator_ParamsType[ZodDecorator.IS_HIDDEN]): DecoratedMoneySchema;\n [ZodDecorator.IS_NOT_EDITABLE](params?: ZodDecorator_ParamsType[ZodDecorator.IS_NOT_EDITABLE]): DecoratedMoneySchema;\n // Resource-level decorators (applicable to all types including ZodObject)\n [ZodDecorator.IS_SUMMARY_FIELD](params?: SummaryFieldParams): DecoratedMoneySchema;\n [ZodDecorator.IS_BACKEND_ONLY](params?: ZodDecorator_ParamsType[ZodDecorator.IS_BACKEND_ONLY]): DecoratedMoneySchema;\n [ZodDecorator.IS_WRITE_ONLY_SECRET](params?: ZodDecorator_ParamsType[ZodDecorator.IS_WRITE_ONLY_SECRET]): DecoratedMoneySchema;\n [ZodDecorator.EXCLUDE_FROM_CREATE](): DecoratedMoneySchema;\n [ZodDecorator.EXCLUDE_FROM_UPDATE](): DecoratedMoneySchema;\n addDecorators(decorators: DecoratorInput[]): DecoratedMoneySchema;\n};\n\n/**\n * Creates a money schema for financial amounts with integer storage.\n * Named z_money to indicate it's a Zod helper function exported standalone.\n *\n * Money values are stored as: { amount: int, currency: string, decimals: int }\n * - amount: Value in smallest unit (e.g., cents for USD, satoshis for BTC)\n * - currency: ISO 4217 code (e.g., 'USD', 'EUR', 'BTC')\n * - decimals: Decimal places for display conversion (e.g., 2 for USD, 8 for BTC)\n *\n * @example\n * ```typescript\n * import { z_money } from '@wildo-ai/zod-decorators';\n *\n * // Simple usage\n * z_money() // All currencies\n *\n * // With options\n * z_money({ currenciesAllowed: [CurrencyAllowed.FIAT] })\n * z_money({ allowCurrencyChange: false }).moneyUI({ edit: { defaultCurrency: 'USD' } })\n * z_money({ currenciesAllowed: [CurrencyAllowed.FIAT_MAJOR], minAmount: 0n })\n *\n * // With decorators (chainable)\n * z_money().moneyUI({ edit: { defaultCurrency: 'USD' } })\n * z_money({ currenciesAllowed: [CurrencyAllowed.FIAT] }).isHidden({ edit: true })\n *\n * // Usage example\n * const price: MoneyValue = { amount: 1999n, currency: 'USD', decimals: 2 };\n * // Represents $19.99\n * ```\n */\nexport function z_money(\n options?: MoneySchemaOptions\n): DecoratedMoneySchema {\n return createMoneySchema(options) as DecoratedMoneySchema;\n}\n/** @wildo_source:part:end zod.factories.money */\n\n// ============================================================================\n// MONEY UTILITY FUNCTIONS\n// ============================================================================\n\n/**\n * Convert a decimal amount to bigint representation.\n *\n * **Precision caveat:** This uses floating-point arithmetic internally\n * (`Math.round(decimalAmount * 10^decimals)`), which can produce rounding\n * errors for certain values. Prefer `parseDecimalStringToAmount` when working\n * with user input strings to avoid float precision issues entirely.\n *\n * @param decimalAmount - The decimal amount (e.g., 19.99)\n * @param decimals - Number of decimal places (e.g., 2)\n * @returns BigInt amount (e.g., 1999n)\n */\nexport function toMoneyAmount(decimalAmount: number, decimals: number): bigint {\n return BigInt(Math.round(decimalAmount * Math.pow(10, decimals)));\n}\n\n/**\n * Convert a bigint amount to decimal representation.\n * @param amount - The bigint amount (e.g., 1999n)\n * @param decimals - Number of decimal places (e.g., 2)\n * @returns Decimal amount (e.g., 19.99)\n */\nexport function fromMoneyAmount(amount: bigint, decimals: number): number {\n return Number(amount) / Math.pow(10, decimals);\n}\n\n/**\n * Convert a string or number to bigint safely.\n * Useful for parsing user input or JSON values.\n * @param value - String, number, or bigint to convert\n * @returns BigInt amount\n */\nexport function toBigIntAmount(value: string | number | bigint): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') return BigInt(Math.round(value));\n return BigInt(value);\n}\n\n/**\n * Parse a decimal string directly to a bigint amount, avoiding floating-point\n * precision issues entirely.\n *\n * This is the preferred way to convert user input (e.g., from an HTML input\n * element) to a money amount. It works by splitting the string at the decimal\n * point and manipulating integer/fractional parts as strings, so no float\n * arithmetic is ever involved.\n *\n * - Extra fractional digits beyond `decimals` are **truncated** (not rounded).\n * - Missing fractional digits are **zero-padded**.\n *\n * @param input - A decimal string (e.g., \"19.99\", \"5\", \".50\", \"-12.345\")\n * @param decimals - Number of decimal places for the target currency\n * @returns BigInt amount, or `null` if the input is not a valid decimal string\n *\n * **Note:** Scientific notation strings (e.g., `\"1e+10\"`) are rejected (returns\n * `null`) since they are not valid monetary input. This is correct behavior when\n * reading from `<input type=\"number\">`, which may produce such strings for very\n * large values — those inputs should be constrained via `min`/`max` attributes.\n *\n * @example\n * ```typescript\n * parseDecimalStringToAmount(\"19.99\", 2) // → 1999n\n * parseDecimalStringToAmount(\"19.999\", 2) // → 1999n (truncates, not rounds)\n * parseDecimalStringToAmount(\"19.9\", 2) // → 1990n (pads missing decimals)\n * parseDecimalStringToAmount(\"5\", 2) // → 500n\n * parseDecimalStringToAmount(\".50\", 2) // → 50n\n * parseDecimalStringToAmount(\"-12.34\", 2) // → -1234n\n * parseDecimalStringToAmount(\"abc\", 2) // → null\n * parseDecimalStringToAmount(\"1e+10\", 2) // → null (scientific notation rejected)\n * ```\n */\nexport function parseDecimalStringToAmount(input: string, decimals: number): bigint | null {\n const trimmed = input.trim();\n if (trimmed === '' || trimmed === '.' || trimmed === '-' || trimmed === '-.') return null;\n\n // Handle sign\n const isNegative = trimmed.startsWith('-');\n const unsigned = isNegative ? trimmed.slice(1) : trimmed;\n\n // Validate: only digits and at most one decimal point\n if (!/^\\d*\\.?\\d*$/.test(unsigned)) return null;\n\n const dotIndex = unsigned.indexOf('.');\n const integerPart = dotIndex === -1 ? unsigned : (unsigned.slice(0, dotIndex) || '0');\n const fractionalRaw = dotIndex === -1 ? '' : unsigned.slice(dotIndex + 1);\n\n // Pad or truncate fractional part to exactly `decimals` digits\n const fractionalPart = decimals === 0\n ? ''\n : fractionalRaw.padEnd(decimals, '0').slice(0, decimals);\n\n // Build the combined string and convert to bigint\n const combined = integerPart + fractionalPart;\n // Guard against empty combined (shouldn't happen after validation, but be safe)\n if (combined === '') return 0n;\n\n try {\n const result = BigInt(combined);\n return isNegative ? -result : result;\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a money amount from one decimal precision to another using pure\n * bigint arithmetic (no floating-point involved).\n *\n * Use this when changing a currency (which may have different decimal places)\n * instead of the float roundtrip `fromMoneyAmount` → `toMoneyAmount`.\n *\n * - When increasing decimals (e.g., 2 → 8): multiplies by 10^(diff)\n * - When decreasing decimals (e.g., 8 → 2): divides with half-away-from-zero rounding\n *\n * @param amount - The bigint amount in the source precision\n * @param fromDecimals - Source decimal places\n * @param toDecimals - Target decimal places\n * @returns BigInt amount in the target precision\n *\n * @example\n * ```typescript\n * convertMoneyDecimals(1999n, 2, 2) // → 1999n (same decimals, no-op)\n * convertMoneyDecimals(1999n, 2, 4) // → 199900n (scale up)\n * convertMoneyDecimals(199900n, 4, 2) // → 1999n (scale down)\n * convertMoneyDecimals(12345678n, 8, 2) // → 12n (BTC satoshis to 2-decimal)\n * ```\n */\nexport function convertMoneyDecimals(amount: bigint, fromDecimals: number, toDecimals: number): bigint {\n if (fromDecimals === toDecimals) return amount;\n\n const diff = toDecimals - fromDecimals;\n\n if (diff > 0) {\n // Scale up: multiply\n return amount * (10n ** BigInt(diff));\n }\n\n // Scale down: divide with rounding (half-away-from-zero)\n const divisor = 10n ** BigInt(-diff);\n const isNegative = amount < 0n;\n const absAmount = isNegative ? -amount : amount;\n const rounded = (absAmount + divisor / 2n) / divisor;\n return isNegative ? -rounded : rounded;\n}\n\n/**\n * Format a money value for display.\n * @param money - The money value\n * @param options - Formatting options\n * @returns Formatted string (e.g., \"$19.99\" or \"19.99 USD\")\n */\nexport function formatMoney(\n money: MoneyValue,\n options: {\n showSymbol?: boolean;\n symbolPosition?: 'before' | 'after';\n thousandsSeparator?: string;\n decimalSeparator?: string;\n } = {}\n): string {\n const {\n showSymbol = true,\n symbolPosition = 'before',\n thousandsSeparator = ',',\n decimalSeparator = '.',\n } = options;\n\n const decimalValue = fromMoneyAmount(money.amount, money.decimals);\n\n // Format with proper decimal places\n const [integerPart, decimalPart] = decimalValue.toFixed(money.decimals).split('.');\n\n // Add thousands separator\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, thousandsSeparator);\n\n const formattedNumber = decimalPart\n ? `${formattedInteger}${decimalSeparator}${decimalPart}`\n : formattedInteger;\n\n if (!showSymbol) {\n return formattedNumber;\n }\n\n // For now, use currency code as symbol (can be enhanced with CURRENCY_INFO_MAP)\n const symbol = money.currency;\n\n return symbolPosition === 'before'\n ? `${symbol} ${formattedNumber}`\n : `${formattedNumber} ${symbol}`;\n}\n\n"]}
|
package/dist/esm/zod-phone.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DecoratorInput, PhoneSchemaOptions, SummaryFieldParams, ZodDecorator, ZodDecorator_ParamsType } from './zod-decorators.types
|
|
1
|
+
import type { DecoratorInput, PhoneSchemaOptions, SummaryFieldParams, ZodDecorator, ZodDecorator_ParamsType } from './zod-decorators.types';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { parsePhoneNumberFromString } from 'libphonenumber-js';
|
|
4
4
|
/** Returns country codes (e.g. "US", "FR") for form components. */
|
|
@@ -40,6 +40,40 @@ export declare function formatPhoneNumber(value: string, defaultCountry?: string
|
|
|
40
40
|
*/
|
|
41
41
|
export declare function getPhoneCountryCode(country: string): string;
|
|
42
42
|
/**
|
|
43
|
+
* Format a PARTIAL (as-you-type) national phone input for a country.
|
|
44
|
+
*
|
|
45
|
+
* Wraps libphonenumber's incomplete-number formatter so form controls can
|
|
46
|
+
* format while the user is still typing ("0612" → "06 12" for FR) without
|
|
47
|
+
* importing libphonenumber-js directly — the phone surface stays owned here.
|
|
48
|
+
*
|
|
49
|
+
* @param value - Partial national input (digits, may carry punctuation)
|
|
50
|
+
* @param country - Country code (e.g. "US", "FR") providing the format plan
|
|
51
|
+
* @returns The formatted partial, or the input unchanged when no plan applies
|
|
52
|
+
*/
|
|
53
|
+
export declare function formatPartialPhoneNumber(value: string, country?: string): string;
|
|
54
|
+
/**
|
|
55
|
+
* Example national number for a country, for use as an input placeholder
|
|
56
|
+
* (e.g. FR → "06 12 34 56 78"). Backed by libphonenumber's curated mobile
|
|
57
|
+
* example set; returns undefined for countries without an example.
|
|
58
|
+
*
|
|
59
|
+
* @param country - Country code (e.g. "US", "FR")
|
|
60
|
+
*/
|
|
61
|
+
export declare function getExamplePhoneNumber(country: string): string | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* Detect the country of a phone input that starts with an international
|
|
64
|
+
* prefix ("+..."), even while the number is still incomplete.
|
|
65
|
+
*
|
|
66
|
+
* Powers the best-practice behavior where pasting/typing "+49 30 ..." into
|
|
67
|
+
* the national input automatically switches the country selector to DE.
|
|
68
|
+
* Returns undefined when the input is not international or the country is
|
|
69
|
+
* not yet determinable (e.g. "+1" is ambiguous across NANP countries).
|
|
70
|
+
*
|
|
71
|
+
* @param value - Raw input, expected to start with "+"
|
|
72
|
+
*/
|
|
73
|
+
export declare function detectPhoneCountry(value: string): string | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* @wildo_source:part:start zod.factories.phone facet:layer:shared facet:family:schema-factory
|
|
76
|
+
*
|
|
43
77
|
* Creates a phone schema with metadata for detection and form component rendering.
|
|
44
78
|
* Values are stored as E.164 strings. Empty string passes validation.
|
|
45
79
|
*
|
|
@@ -56,6 +90,7 @@ export type DecoratedPhoneSchema = z.ZodString & {
|
|
|
56
90
|
[ZodDecorator.IS_NOT_EDITABLE](params?: ZodDecorator_ParamsType[ZodDecorator.IS_NOT_EDITABLE]): DecoratedPhoneSchema;
|
|
57
91
|
[ZodDecorator.IS_SUMMARY_FIELD](params?: SummaryFieldParams): DecoratedPhoneSchema;
|
|
58
92
|
[ZodDecorator.IS_BACKEND_ONLY](params?: ZodDecorator_ParamsType[ZodDecorator.IS_BACKEND_ONLY]): DecoratedPhoneSchema;
|
|
93
|
+
[ZodDecorator.IS_WRITE_ONLY_SECRET](params?: ZodDecorator_ParamsType[ZodDecorator.IS_WRITE_ONLY_SECRET]): DecoratedPhoneSchema;
|
|
59
94
|
[ZodDecorator.EXCLUDE_FROM_CREATE](): DecoratedPhoneSchema;
|
|
60
95
|
[ZodDecorator.EXCLUDE_FROM_UPDATE](): DecoratedPhoneSchema;
|
|
61
96
|
addDecorators(decorators: DecoratorInput[]): DecoratedPhoneSchema;
|
|
@@ -72,4 +107,5 @@ export type DecoratedPhoneSchema = z.ZodString & {
|
|
|
72
107
|
* ```
|
|
73
108
|
*/
|
|
74
109
|
export declare function z_phone(options?: PhoneSchemaOptions): DecoratedPhoneSchema;
|
|
110
|
+
/** @wildo_source:part:end zod.factories.phone */
|
|
75
111
|
//# sourceMappingURL=zod-phone.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod-phone.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"zod-phone.d.ts","sourceRoot":"","sources":["../../../src/zod-phone.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,cAAc,EAGd,kBAAkB,EAClB,kBAAkB,EAClB,YAAY,EACZ,uBAAuB,EACxB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,0BAA0B,EAQ3B,MAAM,mBAAmB,CAAC;AAM3B,mEAAmE;AACnE,wBAAgB,YAAY,IAAI,MAAM,EAAE,CAEvC;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC;AAKhC;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC,OAAO,0BAA0B,CAAC,CAMhH;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAM5E;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,MAAM,EACb,cAAc,CAAC,EAAE,MAAM,EACvB,MAAM,GAAE,eAAe,GAAG,UAA4B,GACrD,MAAM,CAIR;AAED;;;;GAIG;AACH,wBAAgB,m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,mBAAmB,CAAC,IAAI,oBAAoB,CAAC;IAC3D,aAAa,CAAC,UAAU,EAAE,cAAc,EAAE,GAAG,oBAAoB,CAAC;CACnE,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,OAAO,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,oBAAoB,CAE1E;AACD,iDAAiD"}
|
package/dist/esm/zod-phone.js
CHANGED
|
@@ -4,7 +4,11 @@
|
|
|
4
4
|
import { SCHEMA_METADATA } from './zod-decorators.types.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { addChainableMethods } from './zod.module-override.js';
|
|
7
|
-
import { parsePhoneNumberFromString, isValidPhoneNumber, getCountries as getCountriesFromLib, getCountryCallingCode, } from 'libphonenumber-js';
|
|
7
|
+
import { parsePhoneNumberFromString, isValidPhoneNumber, getCountries as getCountriesFromLib, getCountryCallingCode, formatIncompletePhoneNumber, getExampleNumber, AsYouType, } from 'libphonenumber-js';
|
|
8
|
+
// JS-module subpath (NOT the .json subpath): importable under native ESM
|
|
9
|
+
// without JSON import attributes, so the same source compiles for Node and
|
|
10
|
+
// browser consumers alike. Example numbers back per-country placeholders.
|
|
11
|
+
import phoneExamples from 'libphonenumber-js/mobile/examples';
|
|
8
12
|
/** Returns country codes (e.g. "US", "FR") for form components. */
|
|
9
13
|
export function getCountries() {
|
|
10
14
|
return getCountriesFromLib();
|
|
@@ -66,6 +70,54 @@ export function getPhoneCountryCode(country) {
|
|
|
66
70
|
return getCountryCallingCode(country);
|
|
67
71
|
}
|
|
68
72
|
/**
|
|
73
|
+
* Format a PARTIAL (as-you-type) national phone input for a country.
|
|
74
|
+
*
|
|
75
|
+
* Wraps libphonenumber's incomplete-number formatter so form controls can
|
|
76
|
+
* format while the user is still typing ("0612" → "06 12" for FR) without
|
|
77
|
+
* importing libphonenumber-js directly — the phone surface stays owned here.
|
|
78
|
+
*
|
|
79
|
+
* @param value - Partial national input (digits, may carry punctuation)
|
|
80
|
+
* @param country - Country code (e.g. "US", "FR") providing the format plan
|
|
81
|
+
* @returns The formatted partial, or the input unchanged when no plan applies
|
|
82
|
+
*/
|
|
83
|
+
export function formatPartialPhoneNumber(value, country) {
|
|
84
|
+
if (!value)
|
|
85
|
+
return value;
|
|
86
|
+
const cc = (country ?? DEFAULT_COUNTRY);
|
|
87
|
+
return formatIncompletePhoneNumber(value, cc);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Example national number for a country, for use as an input placeholder
|
|
91
|
+
* (e.g. FR → "06 12 34 56 78"). Backed by libphonenumber's curated mobile
|
|
92
|
+
* example set; returns undefined for countries without an example.
|
|
93
|
+
*
|
|
94
|
+
* @param country - Country code (e.g. "US", "FR")
|
|
95
|
+
*/
|
|
96
|
+
export function getExamplePhoneNumber(country) {
|
|
97
|
+
const example = getExampleNumber(country, phoneExamples);
|
|
98
|
+
return example?.formatNational();
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Detect the country of a phone input that starts with an international
|
|
102
|
+
* prefix ("+..."), even while the number is still incomplete.
|
|
103
|
+
*
|
|
104
|
+
* Powers the best-practice behavior where pasting/typing "+49 30 ..." into
|
|
105
|
+
* the national input automatically switches the country selector to DE.
|
|
106
|
+
* Returns undefined when the input is not international or the country is
|
|
107
|
+
* not yet determinable (e.g. "+1" is ambiguous across NANP countries).
|
|
108
|
+
*
|
|
109
|
+
* @param value - Raw input, expected to start with "+"
|
|
110
|
+
*/
|
|
111
|
+
export function detectPhoneCountry(value) {
|
|
112
|
+
if (!value?.trim().startsWith('+'))
|
|
113
|
+
return undefined;
|
|
114
|
+
const formatter = new AsYouType();
|
|
115
|
+
formatter.input(value.trim());
|
|
116
|
+
return formatter.getCountry();
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* @wildo_source:part:start zod.factories.phone facet:layer:shared facet:family:schema-factory
|
|
120
|
+
*
|
|
69
121
|
* Creates a phone schema with metadata for detection and form component rendering.
|
|
70
122
|
* Values are stored as E.164 strings. Empty string passes validation.
|
|
71
123
|
*
|
|
@@ -78,19 +130,27 @@ export function createPhoneSchema(options = {}) {
|
|
|
78
130
|
isPhone: true,
|
|
79
131
|
defaultCountry,
|
|
80
132
|
};
|
|
133
|
+
// PhoneCountryCode is libphonenumber's CountryCode union, so no cast needed.
|
|
81
134
|
const country = defaultCountry;
|
|
82
135
|
const phoneSchema = z
|
|
83
136
|
.string()
|
|
84
|
-
.
|
|
137
|
+
.trim()
|
|
85
138
|
.refine((val) => val === '' || isValidPhone(val, country), {
|
|
86
139
|
message: 'Invalid phone number',
|
|
87
140
|
})
|
|
88
|
-
.
|
|
141
|
+
// E.164 normalization is string -> string, so model it as a Zod 4
|
|
142
|
+
// overwrite rather than a transform. The runtime result is identical, but
|
|
143
|
+
// the schema remains truthfully introspectable as a string by JSON Schema /
|
|
144
|
+
// OpenAPI generators instead of degrading to an unrepresentable transform.
|
|
145
|
+
.overwrite((val) => {
|
|
89
146
|
if (val === '')
|
|
90
147
|
return '';
|
|
91
148
|
const parsed = parsePhone(val, country);
|
|
92
149
|
return parsed?.format('E.164') ?? val;
|
|
93
|
-
})
|
|
150
|
+
})
|
|
151
|
+
// Preserve the established ZodPipe surface used by decorator metadata and
|
|
152
|
+
// boundary walkers; the terminal string adds no value conversion.
|
|
153
|
+
.pipe(z.string());
|
|
94
154
|
const existingMetadata = phoneSchema[SCHEMA_METADATA] || {};
|
|
95
155
|
phoneSchema[SCHEMA_METADATA] = {
|
|
96
156
|
...existingMetadata,
|
|
@@ -113,4 +173,5 @@ export function createPhoneSchema(options = {}) {
|
|
|
113
173
|
export function z_phone(options) {
|
|
114
174
|
return createPhoneSchema(options);
|
|
115
175
|
}
|
|
116
|
-
|
|
176
|
+
/** @wildo_source:part:end zod.factories.phone */
|
|
177
|
+
//# sourceMappingURL=zod-phone.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod-phone.js","sourceRoot":"","sources":["../../src/zod-phone.ts"],"names":[],"mappings":"AAAA,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AAM,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC;IACxC,CAAC,CAAC;QACF,0EAA0E;QAC1E,kEAAkE;SACjE,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAA2B,CAAC;IAE9C,MAAM,gBAAgB,GAAyB,WAAmB,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC;IACzF,WAAmB,CAAC,eAAe,CAAC,GAAG;QACtC,GAAG,gBAAgB;QACnB,WAAW,EAAE,aAAa;KAC3B,CAAC;IAEF,mBAAmB,CAAC,WAAW,CAAC,CAAC;IAEjC,OAAO,WAA8C,CAAC;AACxD,CAAC;AAiBD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,OAAO,CAAC,OAA4B;IAClD,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC;AACD,iDAAiD","sourcesContent":["// ============================================================================\n// PHONE SCHEMA HELPER\n// ============================================================================\n\nimport type {\n DecoratorInput,\n CustomFieldMetadata,\n PhoneSchemaMetadata,\n PhoneSchemaOptions,\n SummaryFieldParams,\n ZodDecorator,\n ZodDecorator_ParamsType,\n} from './zod-decorators.types';\nimport { SCHEMA_METADATA } from './zod-decorators.types';\nimport { z } from 'zod';\nimport { addChainableMethods } from './zod.module-override';\nimport {\n parsePhoneNumberFromString,\n isValidPhoneNumber,\n getCountries as getCountriesFromLib,\n type CountryCode,\n getCountryCallingCode,\n formatIncompletePhoneNumber,\n getExampleNumber,\n AsYouType,\n} from 'libphonenumber-js';\n// JS-module subpath (NOT the .json subpath): importable under native ESM\n// without JSON import attributes, so the same source compiles for Node and\n// browser consumers alike. Example numbers back per-country placeholders.\nimport phoneExamples from 'libphonenumber-js/mobile/examples';\n\n/** Returns country codes (e.g. \"US\", \"FR\") for form components. */\nexport function getCountries(): string[] {\n return getCountriesFromLib() as string[];\n}\n\n/**\n * Phone value type — E.164 string (e.g., \"+33123456789\").\n * Use formatPhoneNumber() for display, parsePhoneNumber() for parsing.\n */\nexport type PhoneValue = string;\n\n/** Default country when parsing numbers without country code */\nconst DEFAULT_COUNTRY: CountryCode = 'US';\n\n/**\n * Parse a phone string to PhoneNumber or undefined.\n *\n * @param value - Raw input (E.164, national, or partial)\n * @param defaultCountry - Country code (e.g. \"US\", \"FR\") for numbers without +prefix\n * @returns PhoneNumber or undefined if invalid\n */\nexport function parsePhone(value: string, defaultCountry?: string): ReturnType<typeof parsePhoneNumberFromString> {\n if (!value || typeof value !== 'string') return undefined;\n const trimmed = value.trim();\n if (!trimmed) return undefined;\n const country = defaultCountry ?? DEFAULT_COUNTRY;\n return parsePhoneNumberFromString(trimmed, { defaultCountry: country as CountryCode });\n}\n\n/**\n * Validate a phone number string.\n *\n * @param value - Phone string to validate\n * @param defaultCountry - Country code (e.g. \"US\", \"FR\") for numbers without +prefix\n * @returns true if valid\n */\nexport function isValidPhone(value: string, defaultCountry?: string): boolean {\n if (!value || typeof value !== 'string') return false;\n const trimmed = value.trim();\n if (!trimmed) return false;\n const country = defaultCountry ?? DEFAULT_COUNTRY;\n return isValidPhoneNumber(trimmed, { defaultCountry: country as CountryCode });\n}\n\n/**\n * Format a phone number for display.\n *\n * @param value - E.164 or parseable phone string\n * @param defaultCountry - Country code (e.g. \"US\", \"FR\") for numbers without +prefix\n * @param format - 'international' | 'national' (default: international)\n * @returns Formatted string or original if unparseable\n */\nexport function formatPhoneNumber(\n value: string,\n defaultCountry?: string,\n format: 'international' | 'national' = 'international'\n): string {\n const parsed = parsePhone(value, defaultCountry);\n if (!parsed) return value;\n return format === 'national' ? parsed.formatNational() : parsed.formatInternational();\n}\n\n/**\n * Get country calling code (e.g., \"1\" for US).\n *\n * @param country - Country code (e.g. \"US\", \"FR\")\n */\nexport function getPhoneCountryCode(country: string): string {\n return getCountryCallingCode(country as CountryCode);\n}\n\n/**\n * Format a PARTIAL (as-you-type) national phone input for a country.\n *\n * Wraps libphonenumber's incomplete-number formatter so form controls can\n * format while the user is still typing (\"0612\" → \"06 12\" for FR) without\n * importing libphonenumber-js directly — the phone surface stays owned here.\n *\n * @param value - Partial national input (digits, may carry punctuation)\n * @param country - Country code (e.g. \"US\", \"FR\") providing the format plan\n * @returns The formatted partial, or the input unchanged when no plan applies\n */\nexport function formatPartialPhoneNumber(value: string, country?: string): string {\n if (!value) return value;\n const cc = (country ?? DEFAULT_COUNTRY) as CountryCode;\n return formatIncompletePhoneNumber(value, cc);\n}\n\n/**\n * Example national number for a country, for use as an input placeholder\n * (e.g. FR → \"06 12 34 56 78\"). Backed by libphonenumber's curated mobile\n * example set; returns undefined for countries without an example.\n *\n * @param country - Country code (e.g. \"US\", \"FR\")\n */\nexport function getExamplePhoneNumber(country: string): string | undefined {\n const example = getExampleNumber(country as CountryCode, phoneExamples);\n return example?.formatNational();\n}\n\n/**\n * Detect the country of a phone input that starts with an international\n * prefix (\"+...\"), even while the number is still incomplete.\n *\n * Powers the best-practice behavior where pasting/typing \"+49 30 ...\" into\n * the national input automatically switches the country selector to DE.\n * Returns undefined when the input is not international or the country is\n * not yet determinable (e.g. \"+1\" is ambiguous across NANP countries).\n *\n * @param value - Raw input, expected to start with \"+\"\n */\nexport function detectPhoneCountry(value: string): string | undefined {\n if (!value?.trim().startsWith('+')) return undefined;\n const formatter = new AsYouType();\n formatter.input(value.trim());\n return formatter.getCountry();\n}\n\n/**\n * @wildo_source:part:start zod.factories.phone facet:layer:shared facet:family:schema-factory\n *\n * Creates a phone schema with metadata for detection and form component rendering.\n * Values are stored as E.164 strings. Empty string passes validation.\n *\n * @param options - Configuration options for phone field\n * @returns A Zod string schema with metadata for phone detection\n */\nexport function createPhoneSchema(options: PhoneSchemaOptions = {}): DecoratedPhoneSchema {\n const { defaultCountry = DEFAULT_COUNTRY } = options;\n\n const phoneMetadata: PhoneSchemaMetadata = {\n isPhone: true,\n defaultCountry,\n };\n\n // PhoneCountryCode is libphonenumber's CountryCode union, so no cast needed.\n const country: CountryCode = defaultCountry;\n const phoneSchema = z\n .string()\n .trim()\n .refine((val) => val === '' || isValidPhone(val, country), {\n message: 'Invalid phone number',\n })\n // E.164 normalization is string -> string, so model it as a Zod 4\n // overwrite rather than a transform. The runtime result is identical, but\n // the schema remains truthfully introspectable as a string by JSON Schema /\n // OpenAPI generators instead of degrading to an unrepresentable transform.\n .overwrite((val) => {\n if (val === '') return '';\n const parsed = parsePhone(val, country);\n return parsed?.format('E.164') ?? val;\n })\n // Preserve the established ZodPipe surface used by decorator metadata and\n // boundary walkers; the terminal string adds no value conversion.\n .pipe(z.string()) as unknown as z.ZodString;\n\n const existingMetadata: CustomFieldMetadata = (phoneSchema as any)[SCHEMA_METADATA] || {};\n (phoneSchema as any)[SCHEMA_METADATA] = {\n ...existingMetadata,\n phoneConfig: phoneMetadata,\n };\n\n addChainableMethods(phoneSchema);\n\n return phoneSchema as unknown as DecoratedPhoneSchema;\n}\n\n/**\n * Return type for phone schemas - includes decorator methods.\n */\nexport type DecoratedPhoneSchema = z.ZodString & {\n [ZodDecorator.IS_DB_INDEXED](): DecoratedPhoneSchema;\n [ZodDecorator.IS_HIDDEN](params?: ZodDecorator_ParamsType[ZodDecorator.IS_HIDDEN]): DecoratedPhoneSchema;\n [ZodDecorator.IS_NOT_EDITABLE](params?: ZodDecorator_ParamsType[ZodDecorator.IS_NOT_EDITABLE]): DecoratedPhoneSchema;\n [ZodDecorator.IS_SUMMARY_FIELD](params?: SummaryFieldParams): DecoratedPhoneSchema;\n [ZodDecorator.IS_BACKEND_ONLY](params?: ZodDecorator_ParamsType[ZodDecorator.IS_BACKEND_ONLY]): DecoratedPhoneSchema;\n [ZodDecorator.IS_WRITE_ONLY_SECRET](params?: ZodDecorator_ParamsType[ZodDecorator.IS_WRITE_ONLY_SECRET]): DecoratedPhoneSchema;\n [ZodDecorator.EXCLUDE_FROM_CREATE](): DecoratedPhoneSchema;\n [ZodDecorator.EXCLUDE_FROM_UPDATE](): DecoratedPhoneSchema;\n addDecorators(decorators: DecoratorInput[]): DecoratedPhoneSchema;\n};\n\n/**\n * Creates a phone schema for E.164 phone numbers.\n *\n * @example\n * ```typescript\n * import { z_phone } from '@wildo-ai/zod-decorators';\n *\n * z_phone()\n * z_phone({ defaultCountry: 'FR' })\n * ```\n */\nexport function z_phone(options?: PhoneSchemaOptions): DecoratedPhoneSchema {\n return createPhoneSchema(options);\n}\n/** @wildo_source:part:end zod.factories.phone */\n"]}
|
package/dist/esm/zod-range.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { DecoratorInput, RangeSchemaOptions, RangeType, ZodDecorator, ZodDecorator_ParamsType } from "./zod-decorators.types
|
|
1
|
+
import { DecoratorInput, RangeSchemaOptions, RangeType, ZodDecorator, ZodDecorator_ParamsType } from "./zod-decorators.types";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
/**
|
|
4
|
+
* @wildo_source:part:start zod.factories.range facet:layer:shared facet:family:schema-factory
|
|
5
|
+
*
|
|
4
6
|
* z_range() - Creates range schemas for number, date, datetime, or time ranges.
|
|
5
7
|
*
|
|
6
8
|
* This is a standalone Zod helper function (cannot be added to frozen Zod module at runtime).
|
|
@@ -84,4 +86,5 @@ export type DecoratedRangeSchema = z.ZodObject<any> & {
|
|
|
84
86
|
* ```
|
|
85
87
|
*/
|
|
86
88
|
export declare function z_range<T extends RangeType | `${RangeType}`>(type: T, options?: RangeSchemaOptions): DecoratedRangeSchema;
|
|
89
|
+
/** @wildo_source:part:end zod.factories.range */
|
|
87
90
|
//# sourceMappingURL=zod-range.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod-range.d.ts","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"zod-range.d.ts","sourceRoot":"","sources":["../../../src/zod-range.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAA6D,kBAAkB,EAAE,SAAS,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACzL,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,SAAS,EACnD,IAAI,EAAE,CAAC,EACP,OAAO,GAAE,kBAAuB,GAC/B,oBAAoB,CAmEtB;AAED;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG;IACpD,CAAC,YAAY,CAAC,aAAa,CAAC,IAAI,oBAAoB,CAAC;IACrD,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAAE,uBAAuB,CAAC,YAAY,CAAC,SAAS,CAAC,GAAG,oBAAoB,CAAC;IACzG,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,EAAE,uBAAuB,CAAC,YAAY,CAAC,eAAe,CAAC,GAAG,oBAAoB,CAAC;IACrH,aAAa,CAAC,UAAU,EAAE,cAAc,EAAE,GAAG,oBAAoB,CAAC;CACnE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,SAAS,GAAG,GAAG,SAAS,EAAE,EAC1D,IAAI,EAAE,CAAC,EACP,OAAO,CAAC,EAAE,kBAAkB,GAC3B,oBAAoB,CAEtB;AACD,iDAAiD"}
|
package/dist/esm/zod-range.js
CHANGED
|
@@ -7,6 +7,8 @@ import { addChainableMethods } from "./zod.module-override.js";
|
|
|
7
7
|
import { BigDecimalValueSchema } from "./zod-bigdecimal.js";
|
|
8
8
|
import { MoneyValueSchema } from "./zod-money.js";
|
|
9
9
|
/**
|
|
10
|
+
* @wildo_source:part:start zod.factories.range facet:layer:shared facet:family:schema-factory
|
|
11
|
+
*
|
|
10
12
|
* z_range() - Creates range schemas for number, date, datetime, or time ranges.
|
|
11
13
|
*
|
|
12
14
|
* This is a standalone Zod helper function (cannot be added to frozen Zod module at runtime).
|
|
@@ -135,4 +137,5 @@ export function createRangeSchema(type, options = {}) {
|
|
|
135
137
|
export function z_range(type, options) {
|
|
136
138
|
return createRangeSchema(type, options);
|
|
137
139
|
}
|
|
138
|
-
|
|
140
|
+
/** @wildo_source:part:end zod.factories.range */
|
|
141
|
+
//# sourceMappingURL=zod-range.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod-range.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"zod-range.js","sourceRoot":"","sources":["../../../src/zod-range.ts"],"names":[],"mappings":"AACA,+EAA+E;AAC/E,sBAAsB;AACtB,+EAA+E;AAE/E,OAAO,EAAkB,eAAe,EAAgE,SAAS,EAAE,YAAY,EAA2B,MAAM,wBAAwB,CAAC;AACzL,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,iBAAiB,CAC/B,IAAO,EACP,UAA8B,EAAE;IAEhC,MAAM,EACJ,YAAY,GAAG,IAAI,EACnB,UAAU,GAAG,IAAI,EACjB,GAAG,EACH,GAAG,GACJ,GAAG,OAAO,CAAC;IAEZ,4CAA4C;IAC5C,IAAI,UAAwB,CAAC;IAE7B,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,SAAS,CAAC,MAAM;YACnB,UAAU,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;YACxB,MAAM;QACR,KAAK,SAAS,CAAC,IAAI;YACjB,UAAU,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YACtB,MAAM;QACR,KAAK,SAAS,CAAC,QAAQ;YACrB,UAAU,GAAG,CAAC,CAAC,GAAG,CA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;IAEjC,OAAO,WAAmC,CAAC;AAC7C,CAAC;AAcD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,OAAO,CACrB,IAAO,EACP,OAA4B;IAE5B,OAAO,iBAAiB,CAAC,IAAiB,EAAE,OAAO,CAAyB,CAAC;AAC/E,CAAC;AACD,iDAAiD","sourcesContent":["\n// ============================================================================\n// RANGE SCHEMA HELPER\n// ============================================================================\n\nimport { DecoratorInput, SCHEMA_METADATA, CustomFieldMetadata, RangeSchemaMetadata, RangeSchemaOptions, RangeType, ZodDecorator, ZodDecorator_ParamsType } from \"./zod-decorators.types\";\nimport { z } from \"zod\";\nimport { addChainableMethods } from \"./zod.module-override\";\nimport { BigDecimalValueSchema } from \"./zod-bigdecimal\";\nimport { MoneyValueSchema } from \"./zod-money\";\n\n\n/**\n * @wildo_source:part:start zod.factories.range facet:layer:shared facet:family:schema-factory\n *\n * z_range() - Creates range schemas for number, date, datetime, or time ranges.\n *\n * This is a standalone Zod helper function (cannot be added to frozen Zod module at runtime).\n *\n * @example\n * ```typescript\n * import { z_range } from '@wildo-ai/saas-models';\n *\n * const priceRange = z_range('number', { min: 0, max: 1000 });\n * const dateRange = z_range('date');\n * const timeRange = z_range('time');\n *\n * // With decorators (chainable)\n * z_range('number').numberUI({ edit: { editMode: 'SLIDER' } })\n * z_range('date', { min: new Date() }).isHidden({ edit: true })\n * ```\n */\n\n/**\n * Creates a range object schema with `from` and `to` fields.\n * Stores metadata for easy detection and form component rendering.\n *\n * @param type - The type of values in the range\n * @param options - Configuration options for optionality and constraints\n * @returns A Zod object schema with metadata for range detection\n *\n * @example\n * ```typescript\n * // Simple number range (both optional)\n * const priceRange = z.range('number');\n * // Infers: { from?: number; to?: number }\n *\n * // Date range with required 'from'\n * const eventRange = z.range('date', { fromOptional: false });\n * // Infers: { from: Date; to?: Date }\n *\n * // Number range with min/max constraints\n * const ageRange = z.range('number', { min: 0, max: 120 });\n * // Infers: { from?: number; to?: number }\n * // Metadata includes min: 0, max: 120 for UI hints\n *\n * // Both required with constraints\n * const salaryRange = z.range('number', {\n * fromOptional: false,\n * toOptional: false,\n * min: 0,\n * });\n * // Infers: { from: number; to: number }\n * ```\n */\nexport function createRangeSchema<T extends RangeType>(\n type: T,\n options: RangeSchemaOptions = {}\n): DecoratedRangeSchema {\n const {\n fromOptional = true,\n toOptional = true,\n min,\n max,\n } = options;\n\n // Create the base schema for the value type\n let baseSchema: z.ZodTypeAny;\n\n switch (type) {\n case RangeType.NUMBER:\n baseSchema = z.number();\n break;\n case RangeType.DATE:\n baseSchema = z.date();\n break;\n case RangeType.DATETIME:\n baseSchema = z.iso.datetime();\n break;\n case RangeType.TIME:\n baseSchema = z.iso.time();\n break;\n case RangeType.BIGDECIMAL:\n baseSchema = BigDecimalValueSchema;\n break;\n case RangeType.MONEY:\n baseSchema = MoneyValueSchema;\n break;\n default:\n throw new Error(`Unknown range type: ${type}`);\n }\n\n // Create from/to schemas based on optionality\n const fromSchema = fromOptional ? baseSchema.optional() : baseSchema;\n const toSchema = toOptional ? baseSchema.optional() : baseSchema;\n\n // Create the object schema\n const rangeSchema = z.object({\n from: fromSchema,\n to: toSchema,\n });\n\n // Store range metadata in SCHEMA_METADATA.rangeConfig\n const rangeMetadata: RangeSchemaMetadata = {\n isRange: true,\n type,\n fromOptional,\n toOptional,\n ...(min !== undefined && { min }),\n ...(max !== undefined && { max }),\n };\n\n // Initialize or extend SCHEMA_METADATA with range config\n const existingMetadata: CustomFieldMetadata = (rangeSchema as any)[SCHEMA_METADATA] || {};\n (rangeSchema as any)[SCHEMA_METADATA] = {\n ...existingMetadata,\n rangeType: type,\n rangeConfig: rangeMetadata,\n };\n\n // Add chainable decorator methods to the range schema instance\n // This allows: z_range('number').numberUI({ edit: { editMode: 'SLIDER' } }).isHidden()\n addChainableMethods(rangeSchema);\n\n return rangeSchema as DecoratedRangeSchema;\n}\n\n/**\n * Return type for range schemas - includes decorator methods.\n * Note: IS_FOREIGN_KEY is not applicable to range objects.\n * IS_DB_INDEXED will index internal fields (from, to) for range query optimization.\n */\nexport type DecoratedRangeSchema = z.ZodObject<any> & {\n [ZodDecorator.IS_DB_INDEXED](): DecoratedRangeSchema;\n [ZodDecorator.IS_HIDDEN](params?: ZodDecorator_ParamsType[ZodDecorator.IS_HIDDEN]): DecoratedRangeSchema;\n [ZodDecorator.IS_NOT_EDITABLE](params?: ZodDecorator_ParamsType[ZodDecorator.IS_NOT_EDITABLE]): DecoratedRangeSchema;\n addDecorators(decorators: DecoratorInput[]): DecoratedRangeSchema;\n};\n\n/**\n * Creates a range object schema with `from` and `to` fields.\n * Named z_range to indicate it's a Zod helper function exported standalone.\n *\n * @example\n * ```typescript\n * import { z_range } from '@wildo-ai/saas-models';\n *\n * // Simple usage\n * z_range('number') // { from?: number; to?: number }\n * z_range('date') // { from?: Date; to?: Date }\n *\n * // With options\n * z_range('number', { fromOptional: false, min: 0 })\n * z_range('datetime', { toOptional: false })\n *\n * // With decorators (chainable)\n * z_range('number').numberUI({ edit: { editMode: 'SLIDER' } })\n * z_range('date', { min: new Date() }).isHidden({ edit: true })\n * ```\n */\nexport function z_range<T extends RangeType | `${RangeType}`>(\n type: T,\n options?: RangeSchemaOptions\n): DecoratedRangeSchema {\n return createRangeSchema(type as RangeType, options) as DecoratedRangeSchema;\n}\n/** @wildo_source:part:end zod.factories.range */\n"]}
|