alepha 0.22.0 → 0.23.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/dist/api/jobs/index.d.ts +20 -20
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/keys/index.d.ts +6 -6
- package/dist/api/users/index.d.ts +43 -9
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/users/index.js +24 -3
- package/dist/api/users/index.js.map +1 -1
- package/dist/api/verifications/index.d.ts +13 -13
- package/dist/cli/core/index.d.ts +46 -40
- package/dist/cli/core/index.d.ts.map +1 -1
- package/dist/cli/core/index.js +51 -101
- package/dist/cli/core/index.js.map +1 -1
- package/dist/cli/i18n/index.d.ts +12 -5
- package/dist/cli/i18n/index.d.ts.map +1 -1
- package/dist/cli/i18n/index.js +45 -11
- package/dist/cli/i18n/index.js.map +1 -1
- package/dist/cli/platform-lib/index.d.ts +32 -6
- package/dist/cli/platform-lib/index.d.ts.map +1 -1
- package/dist/cli/platform-lib/index.js +82 -19
- package/dist/cli/platform-lib/index.js.map +1 -1
- package/dist/command/index.d.ts +1 -1
- package/dist/mcp/index.d.ts +9 -0
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +23 -0
- package/dist/mcp/index.js.map +1 -1
- package/dist/react/form/index.d.ts +0 -1
- package/dist/react/form/index.d.ts.map +1 -1
- package/dist/react/form/index.js +16 -15
- package/dist/react/form/index.js.map +1 -1
- package/dist/react/i18n/index.d.ts +43 -0
- package/dist/react/i18n/index.d.ts.map +1 -1
- package/dist/react/i18n/index.js +114 -10
- package/dist/react/i18n/index.js.map +1 -1
- package/dist/react/router/index.browser.js +128 -5
- package/dist/react/router/index.browser.js.map +1 -1
- package/dist/react/router/index.d.ts +108 -1
- package/dist/react/router/index.d.ts.map +1 -1
- package/dist/react/router/index.js +184 -6
- package/dist/react/router/index.js.map +1 -1
- package/dist/react/sitemap/index.browser.js +35 -0
- package/dist/react/sitemap/index.browser.js.map +1 -0
- package/dist/react/sitemap/index.d.ts +92 -0
- package/dist/react/sitemap/index.d.ts.map +1 -0
- package/dist/react/sitemap/index.js +131 -0
- package/dist/react/sitemap/index.js.map +1 -0
- package/dist/server/auth/index.d.ts +105 -1
- package/dist/server/auth/index.d.ts.map +1 -1
- package/dist/server/auth/index.js +1604 -7
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/cookies/index.d.ts +15 -0
- package/dist/server/cookies/index.d.ts.map +1 -1
- package/dist/server/cookies/index.js +22 -3
- package/dist/server/cookies/index.js.map +1 -1
- package/dist/server/core/index.d.ts +18 -0
- package/dist/server/core/index.d.ts.map +1 -1
- package/dist/server/core/index.js +25 -0
- package/dist/server/core/index.js.map +1 -1
- package/package.json +16 -3
- package/src/api/users/controllers/RealmController.ts +1 -0
- package/src/api/users/primitives/$realm.ts +26 -0
- package/src/api/users/providers/RealmProvider.ts +15 -0
- package/src/api/users/schemas/realmConfigSchema.ts +14 -0
- package/src/cli/core/atoms/buildOptions.ts +0 -12
- package/src/cli/core/commands/build.ts +0 -10
- package/src/cli/core/index.ts +0 -3
- package/src/cli/core/tasks/BuildCloudflareTask.ts +37 -17
- package/src/cli/core/tasks/BuildPrerenderTask.ts +44 -7
- package/src/cli/i18n/__tests__/I18nCheckService.spec.ts +48 -0
- package/src/cli/i18n/services/I18nCheckService.ts +65 -11
- package/src/cli/platform-lib/adapters/CloudflareAdapter.ts +128 -36
- package/src/mcp/__tests__/McpServerProvider.spec.ts +71 -0
- package/src/mcp/providers/McpServerProvider.ts +55 -0
- package/src/react/form/__tests__/FormModel-submit-loading.spec.ts +71 -0
- package/src/react/form/__tests__/form-submitting-reactive.browser.spec.tsx +96 -0
- package/src/react/form/services/FormModel.ts +57 -39
- package/src/react/i18n/__tests__/I18nProvider.spec.ts +89 -0
- package/src/react/i18n/__tests__/locale-routing.spec.ts +107 -0
- package/src/react/i18n/providers/I18nProvider.ts +171 -12
- package/src/react/router/__tests__/RouterLocaleProvider.spec.ts +127 -0
- package/src/react/router/index.browser.ts +4 -0
- package/src/react/router/index.shared.ts +1 -0
- package/src/react/router/index.ts +9 -0
- package/src/react/router/providers/ReactBrowserRouterProvider.ts +15 -1
- package/src/react/router/providers/ReactPageProvider.ts +12 -1
- package/src/react/router/providers/ReactServerProvider.ts +92 -1
- package/src/react/router/providers/RootComponentsProvider.ts +13 -0
- package/src/react/router/providers/RouterLocaleProvider.ts +125 -0
- package/src/react/router/providers/__tests__/RootComponentsProvider.spec.ts +15 -0
- package/src/react/router/providers/__tests__/rootComponents.ssr.browser.spec.tsx +67 -0
- package/src/react/sitemap/__tests__/$sitemap.spec.ts +131 -0
- package/src/react/sitemap/index.browser.ts +21 -0
- package/src/react/sitemap/index.ts +25 -0
- package/src/react/sitemap/primitives/$sitemap.browser.ts +26 -0
- package/src/react/sitemap/primitives/$sitemap.ts +196 -0
- package/src/server/auth/__tests__/appleClientSecret.spec.ts +34 -0
- package/src/server/auth/__tests__/authFederationClient.spec.ts +40 -0
- package/src/server/auth/__tests__/federationAssertion.spec.ts +146 -0
- package/src/server/auth/__tests__/federationRedirectReplay.spec.ts +44 -0
- package/src/server/auth/helpers/appleClientSecret.ts +24 -0
- package/src/server/auth/helpers/federationAssertion.ts +74 -0
- package/src/server/auth/helpers/jtiReplayGuard.ts +41 -0
- package/src/server/auth/helpers/safeRedirectPath.ts +19 -0
- package/src/server/auth/index.ts +4 -0
- package/src/server/auth/primitives/$authFederationBroker.ts +273 -0
- package/src/server/auth/primitives/$authFederationClient.ts +89 -0
- package/src/server/auth/providers/ServerAuthProvider.ts +18 -4
- package/src/server/cookies/__tests__/ServerCookiesProvider.spec.ts +70 -0
- package/src/server/cookies/providers/ServerCookiesProvider.ts +23 -3
- package/src/server/core/interfaces/ServerRequest.ts +8 -0
- package/src/server/core/primitives/$route.ts +27 -0
- package/src/cli/core/tasks/BuildSitemapTask.ts +0 -130
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/react/form/hooks/useFormState.ts","../../../src/react/form/components/FormState.tsx","../../../src/react/form/errors/FormValidationError.ts","../../../src/react/form/hooks/useFieldValue.ts","../../../src/react/form/services/FormModel.ts","../../../src/react/form/hooks/useForm.ts","../../../src/react/form/hooks/useFormQuerySync.ts","../../../src/react/form/hooks/useFormValues.ts","../../../src/react/form/services/prettyName.ts","../../../src/react/form/services/parseField.ts","../../../src/react/form/index.ts"],"sourcesContent":["import { type TObject, TypeBoxError } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useEffect, useState } from \"react\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\nexport interface UseFormStateReturn {\n loading: boolean;\n dirty: boolean;\n values?: Record<string, any>;\n error?: Error;\n}\n\nexport const useFormState = <\n T extends TObject,\n Keys extends keyof UseFormStateReturn,\n>(\n target: FormModel<T> | { form: FormModel<T>; path: string },\n _events: Keys[] = [\"loading\", \"dirty\", \"error\"] as Keys[],\n): Pick<UseFormStateReturn, Keys> => {\n const alepha = useAlepha();\n const events = _events as string[];\n\n const [dirty, setDirty] = useState(false);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [values, setValues] = useState<Record<string, any> | undefined>(\n undefined,\n );\n\n const form = \"form\" in target ? target.form : target;\n const path = \"path\" in target ? target.path : undefined;\n\n const hasValues = events.includes(\"values\");\n const hasErrors = events.includes(\"error\");\n const hasDirty = events.includes(\"dirty\");\n const hasLoading = events.includes(\"loading\");\n\n useEffect(() => {\n const listeners: Function[] = [];\n\n if (hasErrors || hasValues || hasDirty) {\n listeners.push(\n alepha.events.on(\"form:change\", (event) => {\n if (event.id === form.id) {\n if (!path || event.path === path) {\n // `initial: true` marks a programmatic reset (e.g. parent\n // re-rendering with fresh data via `setInitialValues`). Treat\n // it like a reset: clear dirty, don't mark dirty.\n if (hasDirty) {\n if (event.initial) {\n setDirty(false);\n } else {\n setDirty(true);\n }\n }\n if (hasErrors) {\n setError(undefined);\n }\n }\n if (hasValues) {\n setValues(form.currentValues);\n }\n }\n }),\n );\n }\n\n if (hasLoading) {\n listeners.push(\n alepha.events.on(\"form:submit:begin\", (event) => {\n if (event.id === form.id) {\n setLoading(true);\n }\n }),\n alepha.events.on(\"form:submit:end\", (event) => {\n if (event.id === form.id) {\n setLoading(false);\n }\n }),\n );\n }\n\n if (hasValues || hasDirty) {\n listeners.push(\n alepha.events.on(\"form:submit:success\", (event) => {\n if (event.id === form.id) {\n if (hasValues) {\n setValues(event.values);\n }\n if (hasDirty) {\n setDirty(false);\n }\n }\n }),\n );\n }\n\n if (hasDirty) {\n listeners.push(\n alepha.events.on(\"form:reset\", (event) => {\n if (event.id === form.id) {\n setDirty(false);\n }\n }),\n );\n }\n\n if (hasErrors) {\n listeners.push(\n alepha.events.on(\"form:submit:error\", (event) => {\n if (event.id === form.id) {\n if (\n !path ||\n (event.error instanceof TypeBoxError &&\n event.error.value.path === path)\n ) {\n setError(event.error);\n }\n }\n }),\n );\n }\n\n return () => {\n for (const unsub of listeners) {\n unsub();\n }\n };\n }, []);\n\n return {\n dirty,\n loading,\n error,\n values,\n } as Pick<UseFormStateReturn, Keys>;\n};\n","import type { TObject } from \"alepha\";\nimport type { ReactNode } from \"react\";\nimport { useFormState } from \"../hooks/useFormState.ts\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\nconst FormState = <T extends TObject>(props: {\n form: FormModel<T>;\n children: (state: { loading: boolean; dirty: boolean }) => ReactNode;\n}) => {\n const formState = useFormState(props.form);\n return props.children({\n loading: formState.loading,\n dirty: formState.dirty,\n });\n};\n\nexport default FormState;\n","import { TypeBoxError } from \"alepha\";\n\nexport class FormValidationError extends TypeBoxError {\n readonly name = \"ValidationError\";\n\n constructor(options: {\n message: string;\n path: string;\n }) {\n super({\n message: options.message,\n instancePath: options.path,\n schemaPath: \"\",\n keyword: \"not\",\n params: {},\n });\n }\n}\n","import { useAlepha } from \"alepha/react\";\nimport { useEffect, useState } from \"react\";\nimport type { BaseInputField } from \"../services/FormModel.ts\";\n\n/**\n * Hook to subscribe to a single form field's value.\n * Only re-renders when this specific field changes.\n *\n * @returns A tuple of [value, setValue] similar to useState.\n */\nexport const useFieldValue = (\n input: BaseInputField,\n): [any, (value: any) => void] => {\n const alepha = useAlepha();\n const [value, setValue] = useState(input?.initialValue);\n\n useEffect(() => {\n if (!input?.form || !alepha.isBrowser()) {\n return;\n }\n\n return alepha.events.on(\"form:change\", (ev) => {\n if (ev.id === input.form.id && ev.path === input.path) {\n setValue(ev.value);\n }\n });\n }, []);\n\n const setFieldValue = (newValue: any) => {\n input.set(newValue);\n };\n\n return [value, setFieldValue];\n};\n","import type { TArray } from \"alepha\";\nimport {\n $inject,\n Alepha,\n type Static,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport type { InputHTMLAttributes } from \"react\";\n\n/**\n * FormModel is a dynamic form handler that generates form inputs based on a provided TypeBox schema.\n * It manages form state, handles input changes, and processes form submissions with validation.\n *\n * It means to be injected and used within React components to provide a structured way to create and manage forms.\n *\n * @see {@link useForm}\n */\nexport class FormModel<T extends TObject> {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n protected readonly values: Record<string, any> = {};\n protected readonly initialValues: Record<string, any> = {};\n protected submitInProgress = false;\n\n public input: SchemaToInput<T>;\n\n public get submitting(): boolean {\n return this.submitInProgress;\n }\n\n constructor(\n public readonly id: string,\n public readonly options: FormCtrlOptions<T>,\n ) {\n this.options = options;\n\n // Initialize with schema defaults first, then override with initialValues\n const schemaDefaults = this.extractSchemaDefaults(options.schema);\n if (Object.keys(schemaDefaults).length > 0) {\n Object.assign(this.values, schemaDefaults);\n }\n\n if (options.initialValues) {\n // Decode against a partial of the schema so callers can supply incomplete\n // initial values (the form's whole job is to collect them). Codecs still\n // run on whatever's provided; missing fields stay undefined and only the\n // full schema is enforced at submit time.\n const decoded = this.alepha.codec.decode(\n t.partial(options.schema),\n options.initialValues,\n ) as Record<string, any>;\n Object.assign(this.values, decoded);\n }\n\n this.initialValues = { ...this.values };\n\n this.input = this.createProxyFromSchema(options, options.schema, {\n store: this.values,\n parent: \"\",\n });\n }\n\n /**\n * Extract default values from a TypeBox schema.\n * Recursively handles nested objects.\n */\n protected extractSchemaDefaults(\n schema: TObject,\n prefix: string = \"\",\n ): Record<string, any> {\n const defaults: Record<string, any> = {};\n\n if (!schema.properties) {\n return defaults;\n }\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (\"default\" in propSchema && propSchema.default !== undefined) {\n defaults[fullKey] = propSchema.default;\n } else if (\n propSchema &&\n \"type\" in propSchema &&\n propSchema.type === \"object\" &&\n \"properties\" in propSchema\n ) {\n // Recursively extract defaults from nested objects\n const nestedDefaults = this.extractSchemaDefaults(\n propSchema as TObject,\n fullKey,\n );\n Object.assign(defaults, nestedDefaults);\n }\n }\n\n return defaults;\n }\n\n public get currentValues(): Record<string, any> {\n return this.restructureValues(this.values);\n }\n\n public get props() {\n return {\n id: this.id,\n noValidate: true,\n onSubmit: (ev?: FormEventLike) => {\n ev?.preventDefault?.();\n this.submit();\n },\n onReset: (event: FormEventLike) => this.reset(event),\n };\n }\n\n public readonly setInitialValues = (values: Record<string, any>) => {\n // Same partial-decode rationale as the constructor — initial values may be\n // incomplete; full schema is enforced only at submit time.\n const decoded = this.alepha.codec.decode(\n t.partial(this.options.schema),\n values,\n ) as Record<string, any>;\n\n // Snapshot the OLD keys before we wipe — without this, fields that\n // had a value but are absent from the new initialValues never emit\n // form:change and useFieldValue subscribers keep showing the stale\n // value. Mirrors the union-of-keys pattern in reset() below.\n const oldKeys = new Set(Object.keys(this.values));\n\n for (const key in this.initialValues) {\n delete (this.initialValues as Record<string, any>)[key];\n }\n Object.assign(this.initialValues, decoded);\n\n for (const key in this.values) {\n delete this.values[key];\n }\n Object.assign(this.values, { ...this.initialValues });\n\n const keys = new Set<string>([...oldKeys, ...Object.keys(this.values)]);\n for (const key of keys) {\n const path = `/${key.replaceAll(\".\", \"/\")}`;\n this.alepha.events.emit(\n \"form:change\",\n { id: this.id, path, value: this.values[key], initial: true },\n { catch: true },\n );\n }\n };\n\n public readonly reset = (event?: FormEventLike) => {\n event?.preventDefault?.();\n // Snapshot all keys that need notification — both keys present\n // before reset (so subscribers learn the cleared value) and keys\n // restored from initialValues. Without the union, fields that were\n // typed but absent from initialValues stay visually stale.\n const keys = new Set<string>([\n ...Object.keys(this.values),\n ...Object.keys(this.initialValues),\n ]);\n for (const key in this.values) {\n delete this.values[key];\n }\n Object.assign(this.values, { ...this.initialValues });\n for (const key of keys) {\n const path = `/${key.replaceAll(\".\", \"/\")}`;\n this.alepha.events.emit(\n \"form:change\",\n { id: this.id, path, value: this.values[key] },\n { catch: true },\n );\n }\n this.alepha.events.emit(\"form:reset\", { id: this.id }, { catch: true });\n this.options.onReset?.();\n };\n\n public readonly submit = async () => {\n if (this.submitInProgress) {\n this.log.warn(\n \"Form submission already in progress, ignoring duplicate submit.\",\n );\n return;\n }\n\n // emit both action and form events\n await this.alepha.events.emit(\"react:action:begin\", {\n type: \"form\",\n id: this.id,\n });\n await this.alepha.events.emit(\"form:submit:begin\", {\n id: this.id,\n });\n\n this.submitInProgress = true;\n\n const options = this.options;\n\n try {\n let values: Record<string, any> = this.restructureValues(this.values);\n\n if (t.schema.isSchema(options.schema)) {\n values = this.alepha.codec.decode(options.schema, values) as Record<\n string,\n any\n >;\n }\n\n await options.handler(values as any);\n\n await this.alepha.events.emit(\"react:action:success\", {\n type: \"form\",\n id: this.id,\n });\n await this.alepha.events.emit(\"form:submit:success\", {\n id: this.id,\n values,\n });\n } catch (error) {\n this.log.error(\"Form submission error:\", error);\n\n options.onError?.(error as Error);\n\n await this.alepha.events.emit(\"react:action:error\", {\n type: \"form\",\n id: this.id,\n error: error as Error,\n });\n await this.alepha.events.emit(\"form:submit:error\", {\n error: error as Error,\n id: this.id,\n });\n } finally {\n this.submitInProgress = false;\n }\n\n await this.alepha.events.emit(\"react:action:end\", {\n type: \"form\",\n id: this.id,\n });\n await this.alepha.events.emit(\"form:submit:end\", {\n id: this.id,\n });\n };\n\n /**\n * Restructures flat keys like \"address.city\" into nested objects like { address: { city: ... } }\n * Values are already typed from onChange, so no conversion is needed.\n */\n protected restructureValues(store: Record<string, any>): Record<string, any> {\n const values: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(store)) {\n if (key.includes(\".\")) {\n // nested object: restructure flat key to nested structure\n this.restructureNestedValue(values, key, value);\n } else {\n // value is already typed, just copy it\n values[key] = value;\n }\n }\n\n return values;\n }\n\n /**\n * Helper to restructure a flat key like \"address.city\" into nested object structure.\n * The value is already typed, so we just assign it to the nested path.\n */\n protected restructureNestedValue(\n values: Record<string, any>,\n key: string,\n value: any,\n ) {\n const pathSegments = key.split(\".\");\n const finalPropertyKey = pathSegments.pop();\n if (!finalPropertyKey) {\n return;\n }\n\n let currentObjectLevel = values;\n\n // traverse/create the nested structure\n for (const segment of pathSegments) {\n currentObjectLevel[segment] ??= {};\n currentObjectLevel = currentObjectLevel[segment];\n }\n\n // value is already typed from onChange, just assign it\n currentObjectLevel[finalPropertyKey] = value;\n }\n\n protected createProxyFromSchema<T extends TObject>(\n options: FormCtrlOptions<T>,\n schema: TSchema,\n context: {\n parent: string;\n store: Record<string, any>;\n },\n ): SchemaToInput<T> {\n const parent = context.parent || \"\";\n return new Proxy<SchemaToInput<T>>({} as SchemaToInput<T>, {\n get: (_, prop: string) => {\n if (!options.schema || !t.schema.isObject(schema)) {\n return {};\n }\n\n if (prop in schema.properties) {\n // // it's a nested object, create another proxy\n // if (t.schema.isObject(schema.properties[prop])) {\n // return this.createProxyFromSchema(\n // options,\n // schema.properties[prop],\n // {\n // parent: parent ? `${parent}.${prop}` : prop,\n // store: context.store,\n // },\n // );\n // }\n\n return this.createInputFromSchema<T>(\n prop as keyof Static<T> & string,\n options,\n schema,\n schema.required?.includes(prop as string) || false,\n context,\n );\n }\n },\n });\n }\n\n protected createInputFromSchema<T extends TObject>(\n name: keyof Static<T> & string,\n options: FormCtrlOptions<T>,\n schema: TObject,\n required: boolean,\n context: {\n parent: string;\n store: Record<string, any>;\n },\n ): BaseInputField {\n const parent = context.parent || \"\";\n const field = schema.properties?.[name];\n if (!field) {\n return {\n path: \"\",\n required,\n initialValue: undefined,\n props: {} as InputHTMLAttributes<unknown>,\n schema: schema,\n set: () => {},\n form: this,\n };\n }\n\n const isRequired = schema.required?.includes(name) ?? false;\n const key = parent ? `${parent}.${name}` : name;\n const path = `/${key.replaceAll(\".\", \"/\")}`;\n\n const set = (value: any) => {\n const typedValue = this.getValueFromInput(value, field);\n context.store[key] = typedValue;\n if (options.onChange) {\n options.onChange(key, typedValue, context.store);\n }\n this.alepha.events.emit(\n \"form:change\",\n { id: this.id, path: path, value: typedValue },\n { catch: true },\n );\n };\n\n const attr: InputHTMLAttributesLike = {\n name: key,\n };\n\n // Use the form's runtime id (always set — comes from `useId()` when\n // no explicit `options.id` was provided). This guarantees stable\n // per-field DOM ids without forcing callers to pass `id`.\n attr.id = `${this.id}-${key}`;\n (attr as any)[\"data-testid\"] = attr.id;\n\n if (t.schema.isString(field)) {\n if (field.maxLength != null) {\n attr.maxLength = Number(field.maxLength);\n }\n\n if (field.minLength != null) {\n attr.minLength = Number(field.minLength);\n }\n }\n\n if (isRequired) {\n attr.required = true;\n }\n\n if (\"description\" in field && typeof field.description === \"string\") {\n attr[\"aria-label\"] = field.description;\n }\n\n if (t.schema.isInteger(field) || t.schema.isNumber(field)) {\n attr.type = \"number\";\n } else if (name === \"password\") {\n attr.type = \"password\";\n } else if (name === \"email\") {\n attr.type = \"email\";\n } else if (name === \"url\") {\n attr.type = \"url\";\n } else if (t.schema.isString(field)) {\n if (field.format === \"binary\") {\n attr.type = \"file\";\n } else if (field.format === \"date\") {\n attr.type = \"date\";\n } else if (field.format === \"time\") {\n attr.type = \"time\";\n } else if (field.format === \"date-time\") {\n attr.type = \"datetime-local\";\n } else {\n attr.type = \"text\";\n }\n } else if (t.schema.isBoolean(field)) {\n attr.type = \"checkbox\";\n }\n\n if (options.onCreateField) {\n const customAttr = options.onCreateField(name, field);\n Object.assign(attr, customAttr);\n }\n\n // if type = object, add items: { [key: string]: InputField }\n if (t.schema.isObject(field)) {\n return {\n path,\n props: attr,\n schema: field,\n set,\n form: this,\n required,\n initialValue: context.store[key],\n items: this.createProxyFromSchema(options, field, {\n parent: key,\n store: context.store,\n }),\n } as ObjectInputField<any>;\n }\n\n // if type = array, add items: InputField[]\n if (t.schema.isArray(field)) {\n return {\n path,\n props: attr,\n schema: field,\n set,\n form: this,\n required,\n initialValue: context.store[key],\n items: [], // <- will be populated dynamically in the UI\n } as ArrayInputField<any>;\n }\n\n return {\n path,\n props: attr,\n schema: field,\n set,\n form: this,\n required,\n initialValue: context.store[key],\n };\n }\n\n /**\n * Convert an input value to the correct type based on the schema.\n * Handles raw DOM values (strings, booleans from checkboxes, Files, etc.)\n */\n protected getValueFromInput(input: any, schema: TSchema): any {\n // Treat null/undefined as \"unset\" for every schema. Without this the\n // string branch below stringifies them to \"null\"/\"undefined\" (and\n // the date branches throw on `new Date(undefined)`), which then\n // round-trips into controlled inputs as literal text — most\n // visible after the Clear (X) affordance in Control sets\n // value=undefined and the input promptly displays \"undefined\".\n if (input === null || input === undefined) {\n return undefined;\n }\n if (input instanceof File) {\n // for file inputs, return the File object directly\n if (t.schema.isString(schema) && schema.format === \"binary\") {\n return input;\n }\n // for now, ignore other formats\n return null;\n }\n\n if (t.schema.isBoolean(schema)) {\n // Handle string representations from Select components (Yes/No dropdown)\n if (input === \"true\") return true;\n if (input === \"false\") return false;\n if (input === \"\" || input === null || input === undefined)\n return undefined;\n // Handle actual boolean values\n return !!input;\n }\n\n if (t.schema.isNumber(schema)) {\n const num = Number(input);\n return Number.isNaN(num) ? null : num;\n }\n\n if (t.schema.isString(schema)) {\n if (schema.format === \"date\") {\n return new Date(input).toISOString().slice(0, 10); // For date input\n }\n if (schema.format === \"time\") {\n return new Date(`1970-01-01T${input}`).toISOString().slice(11, 16); // For time input\n }\n if (schema.format === \"date-time\") {\n return new Date(input).toISOString(); // For datetime-local input\n }\n return String(input);\n }\n\n return input; // fallback for other types\n }\n}\n\nexport type SchemaToInput<T extends TObject> = {\n [K in keyof T[\"properties\"]]: InputField<T[\"properties\"][K]>;\n};\n\nexport interface FormEventLike {\n preventDefault?: () => void;\n stopPropagation?: () => void;\n}\n\nexport type InputField<T extends TSchema> = T extends TObject\n ? ObjectInputField<T>\n : T extends TArray<infer U>\n ? ArrayInputField<U>\n : BaseInputField;\n\nexport interface BaseInputField {\n path: string;\n required: boolean;\n initialValue: any;\n props: InputHTMLAttributesLike;\n schema: TSchema;\n set: (value: any) => void;\n form: FormModel<any>;\n items?: any;\n}\n\nexport interface ObjectInputField<T extends TObject> extends BaseInputField {\n items: SchemaToInput<T>;\n}\n\nexport interface ArrayInputField<T extends TSchema> extends BaseInputField {\n items: Array<InputField<T>>;\n}\n\nexport type InputHTMLAttributesLike = Pick<\n InputHTMLAttributes<unknown>,\n | \"id\"\n | \"name\"\n | \"type\"\n | \"value\"\n | \"required\"\n | \"maxLength\"\n | \"minLength\"\n | \"aria-label\"\n> & {\n value?: any;\n};\n\nexport type FormCtrlOptions<T extends TObject> = {\n /**\n * The schema defining the structure and validation rules for the form.\n * This should be a TypeBox schema object.\n */\n schema: T;\n\n /**\n * Callback function to handle form submission.\n * This function will receive the parsed and validated form values.\n */\n handler: (values: Static<T>) => unknown;\n\n /**\n * Optional initial values for the form fields.\n * This can be used to pre-populate the form with existing data.\n */\n initialValues?: Partial<Static<T>>;\n\n /**\n * Optional function to create custom field attributes.\n * This can be used to add custom validation, styles, or other attributes.\n */\n onCreateField?: (\n name: keyof Static<T> & string,\n schema: TSchema,\n ) => InputHTMLAttributes<unknown>;\n\n /**\n * If defined, this will generate a unique ID for each field, prefixed with this string.\n *\n * > \"username\" with id=\"form-123\" will become \"form-123-username\".\n *\n * If omitted, IDs will not be generated.\n */\n id?: string;\n\n onError?: (error: Error) => void;\n\n onChange?: (key: string, value: any, store: Record<string, any>) => void;\n\n onReset?: () => void;\n};\n","import type { TObject } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useEffect, useId, useMemo, useRef } from \"react\";\nimport { type FormCtrlOptions, FormModel } from \"../services/FormModel.ts\";\n\n/**\n * Custom hook to create a form with validation and field management.\n * This hook uses TypeBox schemas to define the structure and validation rules for the form.\n * It provides a way to handle form submission, field creation, and value management.\n *\n * @example\n * ```tsx\n * import { t } from \"alepha\";\n *\n * const form = useForm({\n * schema: t.object({\n * username: t.text(),\n * password: t.text(),\n * }),\n * handler: (values) => {\n * console.log(\"Form submitted with values:\", values);\n * },\n * });\n *\n * return (\n * <form {...form.props}>\n * <input {...form.input.username.props} />\n * <input {...form.input.password.props} />\n * <button type=\"submit\">Submit</button>\n * </form>\n * );\n * ```\n */\n/**\n * Shallow / structural equality for form initial-value objects. Form values\n * are plain data (strings, numbers, arrays, plain objects) so JSON.stringify\n * is both fast enough and exact. Wrapped in try/catch to fall back to\n * reference equality if anything exotic sneaks in (e.g. circular refs).\n */\nconst stableEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true;\n if (a == null || b == null) return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n};\n\nexport const useForm = <T extends TObject>(\n options: FormCtrlOptions<T>,\n deps: any[] = [],\n): FormModel<T> => {\n const alepha = useAlepha();\n const formId = useId();\n const initialValuesRef = useRef(options.initialValues);\n\n const form = useMemo(() => {\n return alepha.inject(FormModel<T>, {\n lifetime: \"transient\",\n args: [options.id || formId, options],\n });\n }, deps);\n\n useEffect(() => {\n // Reference inequality alone is unsafe: callers commonly build the\n // `initialValues` object inline at the top of their render, which yields\n // a fresh reference every commit. Reinitializing on every render wipes\n // user-typed values via `setInitialValues` while leaving the DOM stale,\n // producing the \"I filled the form but submit says it's empty\" bug.\n //\n // Deep-equality (JSON-compare) catches the common case where the inline\n // literal is rebuilt with the same content. Callers who legitimately\n // need to swap initial values mid-edit (e.g. editing quest A → quest B)\n // still see a different JSON shape and trigger the reinit.\n if (stableEqual(initialValuesRef.current, options.initialValues)) {\n return;\n }\n initialValuesRef.current = options.initialValues;\n if (options.initialValues) {\n form.setInitialValues(options.initialValues as Record<string, any>);\n }\n }, [options.initialValues]);\n\n return form;\n};\n","import type { TObject } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useRouter, useRouterState } from \"alepha/react/router\";\nimport { useEffect, useRef } from \"react\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\nexport interface UseFormQuerySyncOptions<TKey extends string> {\n /**\n * Form field keys to mirror to/from the URL query. Fields not listed\n * here stay local to the form and never leak into the address bar.\n */\n keys: readonly TKey[];\n}\n\n/**\n * Two-way bind a `useForm` instance to the URL query params, keyed\n * per-field (so the URL stays human-readable: `?status=new&zone=ops`).\n *\n * Direction 1 — URL → form:\n * - On mount AND every time one of the watched query keys changes\n * (typically via browser back/forward or external `router.push`),\n * call `form.input[key].set(value)` for each listed key. Missing /\n * empty params clear the field (set to `undefined`).\n *\n * Direction 2 — form → URL:\n * - Subscribe to the form's `form:change` event for the listed keys.\n * Each emission writes the current values for all listed keys to the\n * URL via `router.setQueryParams` (replace-state, no history spam).\n * Empty values (`undefined` / `\"\"`) are stripped from the URL so the\n * address bar stays clean.\n *\n * Replaces ad-hoc `localStorage` filter persistence: the URL becomes\n * the canonical store, so the view is shareable via copy-paste and\n * navigable via back/forward.\n *\n * @example\n * const form = useForm({ schema: t.object({ status: t.string(), q: t.string() }) });\n * useFormQuerySync(form, { keys: [\"status\", \"q\"] });\n */\nexport const useFormQuerySync = <T extends TObject, TKey extends string>(\n form: FormModel<T>,\n options: UseFormQuerySyncOptions<TKey>,\n): void => {\n const alepha = useAlepha();\n const router = useRouter();\n const state = useRouterState();\n const keys = options.keys;\n\n // URL → form. Recompute a stable signature of the watched slice of\n // router.query so the effect fires precisely when it changes.\n const querySig = keys\n .map((k) => {\n const raw = state.query?.[k];\n return typeof raw === \"string\" ? raw : \"\";\n })\n .join(\"\u0000\");\n\n // First-mount semantics differ from later URL changes: when the URL\n // is empty AND the form has an initial value (e.g. status: \"new\"),\n // preserve that initial value — and write it back to the URL so the\n // URL becomes the source of truth from then on. Without this guard\n // the mount would clear the form's defaults, defeating the whole\n // \"default lane\" pattern.\n const initialized = useRef(false);\n useEffect(() => {\n const isFirstRun = !initialized.current;\n initialized.current = true;\n const values = (form as unknown as { currentValues: Record<string, any> })\n .currentValues;\n const missingInitials: Record<string, string> = {};\n for (const key of keys) {\n const raw = state.query?.[key];\n const next = typeof raw === \"string\" && raw !== \"\" ? raw : undefined;\n const current = values[key];\n if (\n isFirstRun &&\n next === undefined &&\n current != null &&\n current !== \"\"\n ) {\n // URL missing this key on first mount but the form has a\n // default — keep the default, queue it to be written below.\n missingInitials[key] = String(current);\n continue;\n }\n // Skip when already in sync — avoids bouncing form:change ↔\n // setQueryParams and re-triggering subscribers.\n if ((current ?? undefined) !== next) {\n const input = (form.input as Record<string, any>)[key];\n if (input && typeof input.set === \"function\") {\n input.set(next);\n }\n }\n }\n if (isFirstRun && Object.keys(missingInitials).length > 0) {\n // Merge with whatever URL params ARE present so we don't clobber\n // unrelated keys the page also uses.\n const merged: Record<string, string> = {};\n for (const key of keys) {\n const raw = state.query?.[key];\n if (typeof raw === \"string\" && raw !== \"\") {\n merged[key] = raw;\n }\n }\n for (const [k, v] of Object.entries(missingInitials)) {\n merged[k] = v;\n }\n router.setQueryParams(merged);\n }\n // querySig is the meaningful trigger; form/keys/router are stable.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [querySig]);\n\n // form → URL. Listen for changes on the watched keys only.\n useEffect(() => {\n if (!alepha.isBrowser()) return;\n const off = alepha.events.on(\"form:change\", (e: any) => {\n if (e.id !== form.id) return;\n if (!keys.includes(e.path)) return;\n const next: Record<string, string> = {};\n const values = (form as unknown as { currentValues: Record<string, any> })\n .currentValues;\n for (const key of keys) {\n const value = values[key];\n if (value != null && value !== \"\") {\n next[key] = String(value);\n }\n }\n // Replace-state (default) — filters shouldn't pollute history.\n router.setQueryParams(next);\n });\n return off;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [alepha, form, router]);\n};\n","import type { TObject } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useEffect, useState } from \"react\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\n/**\n * Hook to subscribe to all form values.\n * Re-renders on every field change — use only when needed (debug panels, live previews).\n */\nexport const useFormValues = <T extends TObject>(\n form: FormModel<T>,\n): Record<string, any> => {\n const alepha = useAlepha();\n const [values, setValues] = useState<Record<string, any>>(form.currentValues);\n\n useEffect(() => {\n if (!alepha.isBrowser()) {\n return;\n }\n\n return alepha.events.on(\"form:change\", (ev) => {\n if (ev.id === form.id) {\n setValues(form.currentValues);\n }\n });\n }, []);\n\n return values;\n};\n","/**\n * Converts a path or identifier string into a pretty display name.\n * For paths like \"/contacts/0/name\", extracts just the field name \"Name\".\n * Handles camelCase and snake_case conversion to Title Case.\n *\n * @example\n * prettyName(\"/userName\") // \"User Name\"\n * prettyName(\"/contacts/0/email\") // \"Email\"\n * prettyName(\"/address/streetName\") // \"Street Name\"\n * prettyName(\"first_name\") // \"First Name\"\n */\nexport const prettyName = (name: string): string => {\n const segments = name.split(\"/\").filter((s) => s && !/^\\d+$/.test(s));\n const fieldName = segments[segments.length - 1] || name.replaceAll(\"/\", \"\");\n return fieldName\n .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase());\n};\n","import { type TSchema, TypeBoxError } from \"alepha\";\nimport type { BaseInputField } from \"./FormModel.ts\";\nimport { prettyName } from \"./prettyName.ts\";\n\n/**\n * Semantic icon hint derived from schema metadata. UI layers map this\n * to their own icon set — this module is headless and ships no JSX.\n */\nexport type IconHint =\n | \"email\"\n | \"password\"\n | \"phone\"\n | \"url\"\n | \"number\"\n | \"calendar\"\n | \"clock\"\n | \"list\"\n | \"text\"\n | \"user\"\n | \"file\"\n | \"switch\";\n\nexport interface FieldConstraints {\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n}\n\nexport interface FieldMeta {\n id?: string;\n label: string;\n description?: string;\n error?: string;\n required: boolean;\n type?: string;\n format?: string;\n isEnum: boolean;\n isArray: boolean;\n isObject: boolean;\n isArrayOfObjects: boolean;\n enum?: readonly unknown[];\n iconHint?: IconHint;\n constraints: FieldConstraints;\n testId?: string;\n schema: TSchema;\n /**\n * Raw `$control` value from the schema, untyped here. The UI layer\n * (`alepha/react/ui`) provides the strict {@link SchemaControl} type and\n * a `resolveSchemaControl` helper to evaluate the function form.\n */\n control?: unknown;\n}\n\nexport interface ParseFieldOptions {\n label?: string;\n description?: string;\n error?: Error;\n}\n\n/**\n * Derives a {@link FieldMeta} from an `InputField` (from `useForm`) plus\n * optional overrides. Pure — no React, no JSX, no UI library coupling.\n *\n * UI components consume this metadata to render labels, descriptions,\n * error messages, icons, and validation constraints.\n */\nexport const parseField = (\n input: BaseInputField,\n options: ParseFieldOptions = {},\n): FieldMeta => {\n const schema = input.schema as TSchema & {\n type?: string;\n format?: string;\n title?: string;\n description?: string;\n enum?: readonly unknown[];\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n properties?: unknown;\n items?: { properties?: unknown };\n $control?: unknown;\n };\n\n const label =\n options.label ??\n (typeof schema.title === \"string\" ? schema.title : undefined) ??\n prettyName(input.path);\n\n const description =\n options.description ??\n (typeof schema.description === \"string\" ? schema.description : undefined);\n\n const error =\n options.error instanceof TypeBoxError\n ? (options.error as TypeBoxError).value?.message\n : undefined;\n\n const type = schema.type;\n const format = typeof schema.format === \"string\" ? schema.format : undefined;\n const isEnum = Array.isArray(schema.enum);\n const isArray = type === \"array\";\n const isObject = type === \"object\" && Boolean(schema.properties);\n const isArrayOfObjects =\n isArray && Boolean(schema.items && (schema.items as any).properties);\n\n const name = input.props.name;\n const iconHint = inferIconHint({ type, format, name, isEnum, isArray });\n\n const constraints: FieldConstraints = {};\n if (typeof schema.minLength === \"number\")\n constraints.minLength = schema.minLength;\n if (typeof schema.maxLength === \"number\")\n constraints.maxLength = schema.maxLength;\n if (typeof schema.minimum === \"number\") constraints.minimum = schema.minimum;\n if (typeof schema.maximum === \"number\") constraints.maximum = schema.maximum;\n if (typeof schema.pattern === \"string\") constraints.pattern = schema.pattern;\n\n return {\n id: input.props.id,\n label,\n description,\n error,\n required: input.required,\n type,\n format,\n isEnum,\n isArray,\n isObject,\n isArrayOfObjects,\n enum: schema.enum,\n iconHint,\n constraints,\n testId: (input.props as Record<string, unknown>)[\"data-testid\"] as\n | string\n | undefined,\n schema: input.schema,\n control: schema.$control,\n };\n};\n\nconst inferIconHint = (params: {\n type?: string;\n format?: string;\n name?: string;\n isEnum: boolean;\n isArray: boolean;\n}): IconHint | undefined => {\n const { type, format, name, isEnum, isArray } = params;\n\n if (format === \"email\") return \"email\";\n if (format === \"url\" || format === \"uri\") return \"url\";\n if (format === \"tel\" || format === \"phone\") return \"phone\";\n if (format === \"date\" || format === \"date-time\") return \"calendar\";\n if (format === \"time\") return \"clock\";\n\n if (name?.toLowerCase().includes(\"password\")) return \"password\";\n if (name?.toLowerCase().includes(\"email\")) return \"email\";\n if (name?.toLowerCase().includes(\"phone\")) return \"phone\";\n\n if (type === \"boolean\") return \"switch\";\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (isEnum || isArray) return \"list\";\n if (type === \"string\") return \"text\";\n\n return undefined;\n};\n","import { $module } from \"alepha\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport { default as FormState } from \"./components/FormState.tsx\";\nexport * from \"./errors/FormValidationError.ts\";\nexport * from \"./hooks/useFieldValue.ts\";\nexport * from \"./hooks/useForm.ts\";\nexport * from \"./hooks/useFormQuerySync.ts\";\nexport * from \"./hooks/useFormState.ts\";\nexport * from \"./hooks/useFormValues.ts\";\nexport * from \"./services/FormModel.ts\";\nexport * from \"./services/parseField.ts\";\nexport * from \"./services/prettyName.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha\" {\n interface Hooks {\n \"form:change\": {\n id: string;\n path: string;\n value: any;\n /**\n * Programmatic reset (e.g. `setInitialValues` after the parent updates\n * its state). Subscribers tracking dirty state should ignore these.\n */\n initial?: boolean;\n };\n \"form:submit:begin\": { id: string };\n \"form:submit:success\": { id: string; values: Record<string, any> };\n \"form:submit:error\": { id: string; error: Error };\n \"form:submit:end\": { id: string };\n \"form:reset\": { id: string };\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Type-safe forms with validation.\n *\n * **Features:**\n * - Form state management\n * - TypeBox schema validation\n * - Field-level error handling\n * - Submit handling with loading state\n * - Form reset\n *\n * @module alepha.react.form\n */\nexport const AlephaReactForm = $module({\n name: \"alepha.react.form\",\n});\n"],"mappings":";;;;;;AAYA,MAAa,gBAIX,QACA,UAAkB;CAAC;CAAW;CAAS;AAAO,MACX;CACnC,MAAM,SAAS,UAAU;CACzB,MAAM,SAAS;CAEf,MAAM,CAAC,OAAO,YAAY,SAAS,KAAK;CACxC,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAC5C,MAAM,CAAC,OAAO,YAAY,SAA4B,KAAA,CAAS;CAC/D,MAAM,CAAC,QAAQ,aAAa,SAC1B,KAAA,CACF;CAEA,MAAM,OAAO,UAAU,SAAS,OAAO,OAAO;CAC9C,MAAM,OAAO,UAAU,SAAS,OAAO,OAAO,KAAA;CAE9C,MAAM,YAAY,OAAO,SAAS,QAAQ;CAC1C,MAAM,YAAY,OAAO,SAAS,OAAO;CACzC,MAAM,WAAW,OAAO,SAAS,OAAO;CACxC,MAAM,aAAa,OAAO,SAAS,SAAS;CAE5C,gBAAgB;EACd,MAAM,YAAwB,CAAC;EAE/B,IAAI,aAAa,aAAa,UAC5B,UAAU,KACR,OAAO,OAAO,GAAG,gBAAgB,UAAU;GACzC,IAAI,MAAM,OA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OAAO,OAAO;CACjD,IAAI,WAAW,SAAS,WAAW,SAAS,OAAO;CACnD,IAAI,WAAW,UAAU,WAAW,aAAa,OAAO;CACxD,IAAI,WAAW,QAAQ,OAAO;CAE9B,IAAI,MAAM,YAAY,EAAE,SAAS,UAAU,GAAG,OAAO;CACrD,IAAI,MAAM,YAAY,EAAE,SAAS,OAAO,GAAG,OAAO;CAClD,IAAI,MAAM,YAAY,EAAE,SAAS,OAAO,GAAG,OAAO;CAElD,IAAI,SAAS,WAAW,OAAO;CAC/B,IAAI,SAAS,YAAY,SAAS,WAAW,OAAO;CACpD,IAAI,UAAU,SAAS,OAAO;CAC9B,IAAI,SAAS,UAAU,OAAO;AAGhC;;;;;;;;;;;;;;;ACvHA,MAAa,kBAAkB,QAAQ,EACrC,MAAM,oBACR,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/react/form/hooks/useFormState.ts","../../../src/react/form/components/FormState.tsx","../../../src/react/form/errors/FormValidationError.ts","../../../src/react/form/hooks/useFieldValue.ts","../../../src/react/form/services/FormModel.ts","../../../src/react/form/hooks/useForm.ts","../../../src/react/form/hooks/useFormQuerySync.ts","../../../src/react/form/hooks/useFormValues.ts","../../../src/react/form/services/prettyName.ts","../../../src/react/form/services/parseField.ts","../../../src/react/form/index.ts"],"sourcesContent":["import { type TObject, TypeBoxError } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useEffect, useState } from \"react\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\nexport interface UseFormStateReturn {\n loading: boolean;\n dirty: boolean;\n values?: Record<string, any>;\n error?: Error;\n}\n\nexport const useFormState = <\n T extends TObject,\n Keys extends keyof UseFormStateReturn,\n>(\n target: FormModel<T> | { form: FormModel<T>; path: string },\n _events: Keys[] = [\"loading\", \"dirty\", \"error\"] as Keys[],\n): Pick<UseFormStateReturn, Keys> => {\n const alepha = useAlepha();\n const events = _events as string[];\n\n const [dirty, setDirty] = useState(false);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [values, setValues] = useState<Record<string, any> | undefined>(\n undefined,\n );\n\n const form = \"form\" in target ? target.form : target;\n const path = \"path\" in target ? target.path : undefined;\n\n const hasValues = events.includes(\"values\");\n const hasErrors = events.includes(\"error\");\n const hasDirty = events.includes(\"dirty\");\n const hasLoading = events.includes(\"loading\");\n\n useEffect(() => {\n const listeners: Function[] = [];\n\n if (hasErrors || hasValues || hasDirty) {\n listeners.push(\n alepha.events.on(\"form:change\", (event) => {\n if (event.id === form.id) {\n if (!path || event.path === path) {\n // `initial: true` marks a programmatic reset (e.g. parent\n // re-rendering with fresh data via `setInitialValues`). Treat\n // it like a reset: clear dirty, don't mark dirty.\n if (hasDirty) {\n if (event.initial) {\n setDirty(false);\n } else {\n setDirty(true);\n }\n }\n if (hasErrors) {\n setError(undefined);\n }\n }\n if (hasValues) {\n setValues(form.currentValues);\n }\n }\n }),\n );\n }\n\n if (hasLoading) {\n listeners.push(\n alepha.events.on(\"form:submit:begin\", (event) => {\n if (event.id === form.id) {\n setLoading(true);\n }\n }),\n alepha.events.on(\"form:submit:end\", (event) => {\n if (event.id === form.id) {\n setLoading(false);\n }\n }),\n );\n }\n\n if (hasValues || hasDirty) {\n listeners.push(\n alepha.events.on(\"form:submit:success\", (event) => {\n if (event.id === form.id) {\n if (hasValues) {\n setValues(event.values);\n }\n if (hasDirty) {\n setDirty(false);\n }\n }\n }),\n );\n }\n\n if (hasDirty) {\n listeners.push(\n alepha.events.on(\"form:reset\", (event) => {\n if (event.id === form.id) {\n setDirty(false);\n }\n }),\n );\n }\n\n if (hasErrors) {\n listeners.push(\n alepha.events.on(\"form:submit:error\", (event) => {\n if (event.id === form.id) {\n if (\n !path ||\n (event.error instanceof TypeBoxError &&\n event.error.value.path === path)\n ) {\n setError(event.error);\n }\n }\n }),\n );\n }\n\n return () => {\n for (const unsub of listeners) {\n unsub();\n }\n };\n }, []);\n\n return {\n dirty,\n loading,\n error,\n values,\n } as Pick<UseFormStateReturn, Keys>;\n};\n","import type { TObject } from \"alepha\";\nimport type { ReactNode } from \"react\";\nimport { useFormState } from \"../hooks/useFormState.ts\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\nconst FormState = <T extends TObject>(props: {\n form: FormModel<T>;\n children: (state: { loading: boolean; dirty: boolean }) => ReactNode;\n}) => {\n const formState = useFormState(props.form);\n return props.children({\n loading: formState.loading,\n dirty: formState.dirty,\n });\n};\n\nexport default FormState;\n","import { TypeBoxError } from \"alepha\";\n\nexport class FormValidationError extends TypeBoxError {\n readonly name = \"ValidationError\";\n\n constructor(options: {\n message: string;\n path: string;\n }) {\n super({\n message: options.message,\n instancePath: options.path,\n schemaPath: \"\",\n keyword: \"not\",\n params: {},\n });\n }\n}\n","import { useAlepha } from \"alepha/react\";\nimport { useEffect, useState } from \"react\";\nimport type { BaseInputField } from \"../services/FormModel.ts\";\n\n/**\n * Hook to subscribe to a single form field's value.\n * Only re-renders when this specific field changes.\n *\n * @returns A tuple of [value, setValue] similar to useState.\n */\nexport const useFieldValue = (\n input: BaseInputField,\n): [any, (value: any) => void] => {\n const alepha = useAlepha();\n const [value, setValue] = useState(input?.initialValue);\n\n useEffect(() => {\n if (!input?.form || !alepha.isBrowser()) {\n return;\n }\n\n return alepha.events.on(\"form:change\", (ev) => {\n if (ev.id === input.form.id && ev.path === input.path) {\n setValue(ev.value);\n }\n });\n }, []);\n\n const setFieldValue = (newValue: any) => {\n input.set(newValue);\n };\n\n return [value, setFieldValue];\n};\n","import type { TArray } from \"alepha\";\nimport {\n $inject,\n Alepha,\n type Static,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport type { InputHTMLAttributes } from \"react\";\n\n/**\n * FormModel is a dynamic form handler that generates form inputs based on a provided TypeBox schema.\n * It manages form state, handles input changes, and processes form submissions with validation.\n *\n * It means to be injected and used within React components to provide a structured way to create and manage forms.\n *\n * @see {@link useForm}\n */\nexport class FormModel<T extends TObject> {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n protected readonly values: Record<string, any> = {};\n protected readonly initialValues: Record<string, any> = {};\n protected submitInProgress = false;\n\n public input: SchemaToInput<T>;\n\n constructor(\n public readonly id: string,\n public readonly options: FormCtrlOptions<T>,\n ) {\n this.options = options;\n\n // Initialize with schema defaults first, then override with initialValues\n const schemaDefaults = this.extractSchemaDefaults(options.schema);\n if (Object.keys(schemaDefaults).length > 0) {\n Object.assign(this.values, schemaDefaults);\n }\n\n if (options.initialValues) {\n // Decode against a partial of the schema so callers can supply incomplete\n // initial values (the form's whole job is to collect them). Codecs still\n // run on whatever's provided; missing fields stay undefined and only the\n // full schema is enforced at submit time.\n const decoded = this.alepha.codec.decode(\n t.partial(options.schema),\n options.initialValues,\n ) as Record<string, any>;\n Object.assign(this.values, decoded);\n }\n\n this.initialValues = { ...this.values };\n\n this.input = this.createProxyFromSchema(options, options.schema, {\n store: this.values,\n parent: \"\",\n });\n }\n\n /**\n * Extract default values from a TypeBox schema.\n * Recursively handles nested objects.\n */\n protected extractSchemaDefaults(\n schema: TObject,\n prefix: string = \"\",\n ): Record<string, any> {\n const defaults: Record<string, any> = {};\n\n if (!schema.properties) {\n return defaults;\n }\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (\"default\" in propSchema && propSchema.default !== undefined) {\n defaults[fullKey] = propSchema.default;\n } else if (\n propSchema &&\n \"type\" in propSchema &&\n propSchema.type === \"object\" &&\n \"properties\" in propSchema\n ) {\n // Recursively extract defaults from nested objects\n const nestedDefaults = this.extractSchemaDefaults(\n propSchema as TObject,\n fullKey,\n );\n Object.assign(defaults, nestedDefaults);\n }\n }\n\n return defaults;\n }\n\n public get currentValues(): Record<string, any> {\n return this.restructureValues(this.values);\n }\n\n public get props() {\n return {\n id: this.id,\n noValidate: true,\n onSubmit: (ev?: FormEventLike) => {\n ev?.preventDefault?.();\n this.submit();\n },\n onReset: (event: FormEventLike) => this.reset(event),\n };\n }\n\n public readonly setInitialValues = (values: Record<string, any>) => {\n // Same partial-decode rationale as the constructor — initial values may be\n // incomplete; full schema is enforced only at submit time.\n const decoded = this.alepha.codec.decode(\n t.partial(this.options.schema),\n values,\n ) as Record<string, any>;\n\n // Snapshot the OLD keys before we wipe — without this, fields that\n // had a value but are absent from the new initialValues never emit\n // form:change and useFieldValue subscribers keep showing the stale\n // value. Mirrors the union-of-keys pattern in reset() below.\n const oldKeys = new Set(Object.keys(this.values));\n\n for (const key in this.initialValues) {\n delete (this.initialValues as Record<string, any>)[key];\n }\n Object.assign(this.initialValues, decoded);\n\n for (const key in this.values) {\n delete this.values[key];\n }\n Object.assign(this.values, { ...this.initialValues });\n\n const keys = new Set<string>([...oldKeys, ...Object.keys(this.values)]);\n for (const key of keys) {\n const path = `/${key.replaceAll(\".\", \"/\")}`;\n this.alepha.events.emit(\n \"form:change\",\n { id: this.id, path, value: this.values[key], initial: true },\n { catch: true },\n );\n }\n };\n\n public readonly reset = (event?: FormEventLike) => {\n event?.preventDefault?.();\n // Snapshot all keys that need notification — both keys present\n // before reset (so subscribers learn the cleared value) and keys\n // restored from initialValues. Without the union, fields that were\n // typed but absent from initialValues stay visually stale.\n const keys = new Set<string>([\n ...Object.keys(this.values),\n ...Object.keys(this.initialValues),\n ]);\n for (const key in this.values) {\n delete this.values[key];\n }\n Object.assign(this.values, { ...this.initialValues });\n for (const key of keys) {\n const path = `/${key.replaceAll(\".\", \"/\")}`;\n this.alepha.events.emit(\n \"form:change\",\n { id: this.id, path, value: this.values[key] },\n { catch: true },\n );\n }\n this.alepha.events.emit(\"form:reset\", { id: this.id }, { catch: true });\n this.options.onReset?.();\n };\n\n public readonly submit = async () => {\n if (this.submitInProgress) {\n this.log.warn(\n \"Form submission already in progress, ignoring duplicate submit.\",\n );\n return;\n }\n\n // Lifecycle events are best-effort NOTIFICATIONS (loading spinners, toasts,\n // analytics). A misbehaving listener must never break form state or reject\n // submit() — hence `{ catch: true }` on every emit below. Without it, a\n // throwing `react:action:error`/`form:submit:error` listener would skip the\n // `form:submit:end` \"loading off\" signal and leave submit buttons stuck in\n // their loading state forever.\n await this.alepha.events.emit(\n \"react:action:begin\",\n { type: \"form\", id: this.id },\n { catch: true },\n );\n await this.alepha.events.emit(\n \"form:submit:begin\",\n { id: this.id },\n { catch: true },\n );\n\n this.submitInProgress = true;\n\n const options = this.options;\n\n try {\n let values: Record<string, any> = this.restructureValues(this.values);\n\n if (t.schema.isSchema(options.schema)) {\n values = this.alepha.codec.decode(options.schema, values) as Record<\n string,\n any\n >;\n }\n\n await options.handler(values as any);\n\n await this.alepha.events.emit(\n \"react:action:success\",\n { type: \"form\", id: this.id },\n { catch: true },\n );\n await this.alepha.events.emit(\n \"form:submit:success\",\n { id: this.id, values },\n { catch: true },\n );\n } catch (error) {\n this.log.error(\"Form submission error:\", error);\n\n // A throwing onError callback must not abort the lifecycle either.\n try {\n options.onError?.(error as Error);\n } catch (handlerError) {\n this.log.error(\"Form onError handler threw:\", handlerError);\n }\n\n await this.alepha.events.emit(\n \"react:action:error\",\n { type: \"form\", id: this.id, error: error as Error },\n { catch: true },\n );\n await this.alepha.events.emit(\n \"form:submit:error\",\n { error: error as Error, id: this.id },\n { catch: true },\n );\n } finally {\n this.submitInProgress = false;\n\n // The \"loading off\" signals live in `finally` so they ALWAYS fire,\n // even if something above threw — guaranteeing the begin/end pairing\n // that drives submit-button loading state.\n await this.alepha.events.emit(\n \"react:action:end\",\n { type: \"form\", id: this.id },\n { catch: true },\n );\n await this.alepha.events.emit(\n \"form:submit:end\",\n { id: this.id },\n { catch: true },\n );\n }\n };\n\n /**\n * Restructures flat keys like \"address.city\" into nested objects like { address: { city: ... } }\n * Values are already typed from onChange, so no conversion is needed.\n */\n protected restructureValues(store: Record<string, any>): Record<string, any> {\n const values: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(store)) {\n if (key.includes(\".\")) {\n // nested object: restructure flat key to nested structure\n this.restructureNestedValue(values, key, value);\n } else {\n // value is already typed, just copy it\n values[key] = value;\n }\n }\n\n return values;\n }\n\n /**\n * Helper to restructure a flat key like \"address.city\" into nested object structure.\n * The value is already typed, so we just assign it to the nested path.\n */\n protected restructureNestedValue(\n values: Record<string, any>,\n key: string,\n value: any,\n ) {\n const pathSegments = key.split(\".\");\n const finalPropertyKey = pathSegments.pop();\n if (!finalPropertyKey) {\n return;\n }\n\n let currentObjectLevel = values;\n\n // traverse/create the nested structure\n for (const segment of pathSegments) {\n currentObjectLevel[segment] ??= {};\n currentObjectLevel = currentObjectLevel[segment];\n }\n\n // value is already typed from onChange, just assign it\n currentObjectLevel[finalPropertyKey] = value;\n }\n\n protected createProxyFromSchema<T extends TObject>(\n options: FormCtrlOptions<T>,\n schema: TSchema,\n context: {\n parent: string;\n store: Record<string, any>;\n },\n ): SchemaToInput<T> {\n const parent = context.parent || \"\";\n return new Proxy<SchemaToInput<T>>({} as SchemaToInput<T>, {\n get: (_, prop: string) => {\n if (!options.schema || !t.schema.isObject(schema)) {\n return {};\n }\n\n if (prop in schema.properties) {\n // // it's a nested object, create another proxy\n // if (t.schema.isObject(schema.properties[prop])) {\n // return this.createProxyFromSchema(\n // options,\n // schema.properties[prop],\n // {\n // parent: parent ? `${parent}.${prop}` : prop,\n // store: context.store,\n // },\n // );\n // }\n\n return this.createInputFromSchema<T>(\n prop as keyof Static<T> & string,\n options,\n schema,\n schema.required?.includes(prop as string) || false,\n context,\n );\n }\n },\n });\n }\n\n protected createInputFromSchema<T extends TObject>(\n name: keyof Static<T> & string,\n options: FormCtrlOptions<T>,\n schema: TObject,\n required: boolean,\n context: {\n parent: string;\n store: Record<string, any>;\n },\n ): BaseInputField {\n const parent = context.parent || \"\";\n const field = schema.properties?.[name];\n if (!field) {\n return {\n path: \"\",\n required,\n initialValue: undefined,\n props: {} as InputHTMLAttributes<unknown>,\n schema: schema,\n set: () => {},\n form: this,\n };\n }\n\n const isRequired = schema.required?.includes(name) ?? false;\n const key = parent ? `${parent}.${name}` : name;\n const path = `/${key.replaceAll(\".\", \"/\")}`;\n\n const set = (value: any) => {\n const typedValue = this.getValueFromInput(value, field);\n context.store[key] = typedValue;\n if (options.onChange) {\n options.onChange(key, typedValue, context.store);\n }\n this.alepha.events.emit(\n \"form:change\",\n { id: this.id, path: path, value: typedValue },\n { catch: true },\n );\n };\n\n const attr: InputHTMLAttributesLike = {\n name: key,\n };\n\n // Use the form's runtime id (always set — comes from `useId()` when\n // no explicit `options.id` was provided). This guarantees stable\n // per-field DOM ids without forcing callers to pass `id`.\n attr.id = `${this.id}-${key}`;\n (attr as any)[\"data-testid\"] = attr.id;\n\n if (t.schema.isString(field)) {\n if (field.maxLength != null) {\n attr.maxLength = Number(field.maxLength);\n }\n\n if (field.minLength != null) {\n attr.minLength = Number(field.minLength);\n }\n }\n\n if (isRequired) {\n attr.required = true;\n }\n\n if (\"description\" in field && typeof field.description === \"string\") {\n attr[\"aria-label\"] = field.description;\n }\n\n if (t.schema.isInteger(field) || t.schema.isNumber(field)) {\n attr.type = \"number\";\n } else if (name === \"password\") {\n attr.type = \"password\";\n } else if (name === \"email\") {\n attr.type = \"email\";\n } else if (name === \"url\") {\n attr.type = \"url\";\n } else if (t.schema.isString(field)) {\n if (field.format === \"binary\") {\n attr.type = \"file\";\n } else if (field.format === \"date\") {\n attr.type = \"date\";\n } else if (field.format === \"time\") {\n attr.type = \"time\";\n } else if (field.format === \"date-time\") {\n attr.type = \"datetime-local\";\n } else {\n attr.type = \"text\";\n }\n } else if (t.schema.isBoolean(field)) {\n attr.type = \"checkbox\";\n }\n\n if (options.onCreateField) {\n const customAttr = options.onCreateField(name, field);\n Object.assign(attr, customAttr);\n }\n\n // if type = object, add items: { [key: string]: InputField }\n if (t.schema.isObject(field)) {\n return {\n path,\n props: attr,\n schema: field,\n set,\n form: this,\n required,\n initialValue: context.store[key],\n items: this.createProxyFromSchema(options, field, {\n parent: key,\n store: context.store,\n }),\n } as ObjectInputField<any>;\n }\n\n // if type = array, add items: InputField[]\n if (t.schema.isArray(field)) {\n return {\n path,\n props: attr,\n schema: field,\n set,\n form: this,\n required,\n initialValue: context.store[key],\n items: [], // <- will be populated dynamically in the UI\n } as ArrayInputField<any>;\n }\n\n return {\n path,\n props: attr,\n schema: field,\n set,\n form: this,\n required,\n initialValue: context.store[key],\n };\n }\n\n /**\n * Convert an input value to the correct type based on the schema.\n * Handles raw DOM values (strings, booleans from checkboxes, Files, etc.)\n */\n protected getValueFromInput(input: any, schema: TSchema): any {\n // Treat null/undefined as \"unset\" for every schema. Without this the\n // string branch below stringifies them to \"null\"/\"undefined\" (and\n // the date branches throw on `new Date(undefined)`), which then\n // round-trips into controlled inputs as literal text — most\n // visible after the Clear (X) affordance in Control sets\n // value=undefined and the input promptly displays \"undefined\".\n if (input === null || input === undefined) {\n return undefined;\n }\n if (input instanceof File) {\n // for file inputs, return the File object directly\n if (t.schema.isString(schema) && schema.format === \"binary\") {\n return input;\n }\n // for now, ignore other formats\n return null;\n }\n\n if (t.schema.isBoolean(schema)) {\n // Handle string representations from Select components (Yes/No dropdown)\n if (input === \"true\") return true;\n if (input === \"false\") return false;\n if (input === \"\" || input === null || input === undefined)\n return undefined;\n // Handle actual boolean values\n return !!input;\n }\n\n if (t.schema.isNumber(schema)) {\n const num = Number(input);\n return Number.isNaN(num) ? null : num;\n }\n\n if (t.schema.isString(schema)) {\n if (schema.format === \"date\") {\n return new Date(input).toISOString().slice(0, 10); // For date input\n }\n if (schema.format === \"time\") {\n return new Date(`1970-01-01T${input}`).toISOString().slice(11, 16); // For time input\n }\n if (schema.format === \"date-time\") {\n return new Date(input).toISOString(); // For datetime-local input\n }\n return String(input);\n }\n\n return input; // fallback for other types\n }\n}\n\nexport type SchemaToInput<T extends TObject> = {\n [K in keyof T[\"properties\"]]: InputField<T[\"properties\"][K]>;\n};\n\nexport interface FormEventLike {\n preventDefault?: () => void;\n stopPropagation?: () => void;\n}\n\nexport type InputField<T extends TSchema> = T extends TObject\n ? ObjectInputField<T>\n : T extends TArray<infer U>\n ? ArrayInputField<U>\n : BaseInputField;\n\nexport interface BaseInputField {\n path: string;\n required: boolean;\n initialValue: any;\n props: InputHTMLAttributesLike;\n schema: TSchema;\n set: (value: any) => void;\n form: FormModel<any>;\n items?: any;\n}\n\nexport interface ObjectInputField<T extends TObject> extends BaseInputField {\n items: SchemaToInput<T>;\n}\n\nexport interface ArrayInputField<T extends TSchema> extends BaseInputField {\n items: Array<InputField<T>>;\n}\n\nexport type InputHTMLAttributesLike = Pick<\n InputHTMLAttributes<unknown>,\n | \"id\"\n | \"name\"\n | \"type\"\n | \"value\"\n | \"required\"\n | \"maxLength\"\n | \"minLength\"\n | \"aria-label\"\n> & {\n value?: any;\n};\n\nexport type FormCtrlOptions<T extends TObject> = {\n /**\n * The schema defining the structure and validation rules for the form.\n * This should be a TypeBox schema object.\n */\n schema: T;\n\n /**\n * Callback function to handle form submission.\n * This function will receive the parsed and validated form values.\n */\n handler: (values: Static<T>) => unknown;\n\n /**\n * Optional initial values for the form fields.\n * This can be used to pre-populate the form with existing data.\n */\n initialValues?: Partial<Static<T>>;\n\n /**\n * Optional function to create custom field attributes.\n * This can be used to add custom validation, styles, or other attributes.\n */\n onCreateField?: (\n name: keyof Static<T> & string,\n schema: TSchema,\n ) => InputHTMLAttributes<unknown>;\n\n /**\n * If defined, this will generate a unique ID for each field, prefixed with this string.\n *\n * > \"username\" with id=\"form-123\" will become \"form-123-username\".\n *\n * If omitted, IDs will not be generated.\n */\n id?: string;\n\n onError?: (error: Error) => void;\n\n onChange?: (key: string, value: any, store: Record<string, any>) => void;\n\n onReset?: () => void;\n};\n","import type { TObject } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useEffect, useId, useMemo, useRef } from \"react\";\nimport { type FormCtrlOptions, FormModel } from \"../services/FormModel.ts\";\n\n/**\n * Custom hook to create a form with validation and field management.\n * This hook uses TypeBox schemas to define the structure and validation rules for the form.\n * It provides a way to handle form submission, field creation, and value management.\n *\n * @example\n * ```tsx\n * import { t } from \"alepha\";\n *\n * const form = useForm({\n * schema: t.object({\n * username: t.text(),\n * password: t.text(),\n * }),\n * handler: (values) => {\n * console.log(\"Form submitted with values:\", values);\n * },\n * });\n *\n * return (\n * <form {...form.props}>\n * <input {...form.input.username.props} />\n * <input {...form.input.password.props} />\n * <button type=\"submit\">Submit</button>\n * </form>\n * );\n * ```\n */\n/**\n * Shallow / structural equality for form initial-value objects. Form values\n * are plain data (strings, numbers, arrays, plain objects) so JSON.stringify\n * is both fast enough and exact. Wrapped in try/catch to fall back to\n * reference equality if anything exotic sneaks in (e.g. circular refs).\n */\nconst stableEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true;\n if (a == null || b == null) return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n};\n\nexport const useForm = <T extends TObject>(\n options: FormCtrlOptions<T>,\n deps: any[] = [],\n): FormModel<T> => {\n const alepha = useAlepha();\n const formId = useId();\n const initialValuesRef = useRef(options.initialValues);\n\n const form = useMemo(() => {\n return alepha.inject(FormModel<T>, {\n lifetime: \"transient\",\n args: [options.id || formId, options],\n });\n }, deps);\n\n useEffect(() => {\n // Reference inequality alone is unsafe: callers commonly build the\n // `initialValues` object inline at the top of their render, which yields\n // a fresh reference every commit. Reinitializing on every render wipes\n // user-typed values via `setInitialValues` while leaving the DOM stale,\n // producing the \"I filled the form but submit says it's empty\" bug.\n //\n // Deep-equality (JSON-compare) catches the common case where the inline\n // literal is rebuilt with the same content. Callers who legitimately\n // need to swap initial values mid-edit (e.g. editing quest A → quest B)\n // still see a different JSON shape and trigger the reinit.\n if (stableEqual(initialValuesRef.current, options.initialValues)) {\n return;\n }\n initialValuesRef.current = options.initialValues;\n if (options.initialValues) {\n form.setInitialValues(options.initialValues as Record<string, any>);\n }\n }, [options.initialValues]);\n\n return form;\n};\n","import type { TObject } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useRouter, useRouterState } from \"alepha/react/router\";\nimport { useEffect, useRef } from \"react\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\nexport interface UseFormQuerySyncOptions<TKey extends string> {\n /**\n * Form field keys to mirror to/from the URL query. Fields not listed\n * here stay local to the form and never leak into the address bar.\n */\n keys: readonly TKey[];\n}\n\n/**\n * Two-way bind a `useForm` instance to the URL query params, keyed\n * per-field (so the URL stays human-readable: `?status=new&zone=ops`).\n *\n * Direction 1 — URL → form:\n * - On mount AND every time one of the watched query keys changes\n * (typically via browser back/forward or external `router.push`),\n * call `form.input[key].set(value)` for each listed key. Missing /\n * empty params clear the field (set to `undefined`).\n *\n * Direction 2 — form → URL:\n * - Subscribe to the form's `form:change` event for the listed keys.\n * Each emission writes the current values for all listed keys to the\n * URL via `router.setQueryParams` (replace-state, no history spam).\n * Empty values (`undefined` / `\"\"`) are stripped from the URL so the\n * address bar stays clean.\n *\n * Replaces ad-hoc `localStorage` filter persistence: the URL becomes\n * the canonical store, so the view is shareable via copy-paste and\n * navigable via back/forward.\n *\n * @example\n * const form = useForm({ schema: t.object({ status: t.string(), q: t.string() }) });\n * useFormQuerySync(form, { keys: [\"status\", \"q\"] });\n */\nexport const useFormQuerySync = <T extends TObject, TKey extends string>(\n form: FormModel<T>,\n options: UseFormQuerySyncOptions<TKey>,\n): void => {\n const alepha = useAlepha();\n const router = useRouter();\n const state = useRouterState();\n const keys = options.keys;\n\n // URL → form. Recompute a stable signature of the watched slice of\n // router.query so the effect fires precisely when it changes.\n const querySig = keys\n .map((k) => {\n const raw = state.query?.[k];\n return typeof raw === \"string\" ? raw : \"\";\n })\n .join(\"\u0000\");\n\n // First-mount semantics differ from later URL changes: when the URL\n // is empty AND the form has an initial value (e.g. status: \"new\"),\n // preserve that initial value — and write it back to the URL so the\n // URL becomes the source of truth from then on. Without this guard\n // the mount would clear the form's defaults, defeating the whole\n // \"default lane\" pattern.\n const initialized = useRef(false);\n useEffect(() => {\n const isFirstRun = !initialized.current;\n initialized.current = true;\n const values = (form as unknown as { currentValues: Record<string, any> })\n .currentValues;\n const missingInitials: Record<string, string> = {};\n for (const key of keys) {\n const raw = state.query?.[key];\n const next = typeof raw === \"string\" && raw !== \"\" ? raw : undefined;\n const current = values[key];\n if (\n isFirstRun &&\n next === undefined &&\n current != null &&\n current !== \"\"\n ) {\n // URL missing this key on first mount but the form has a\n // default — keep the default, queue it to be written below.\n missingInitials[key] = String(current);\n continue;\n }\n // Skip when already in sync — avoids bouncing form:change ↔\n // setQueryParams and re-triggering subscribers.\n if ((current ?? undefined) !== next) {\n const input = (form.input as Record<string, any>)[key];\n if (input && typeof input.set === \"function\") {\n input.set(next);\n }\n }\n }\n if (isFirstRun && Object.keys(missingInitials).length > 0) {\n // Merge with whatever URL params ARE present so we don't clobber\n // unrelated keys the page also uses.\n const merged: Record<string, string> = {};\n for (const key of keys) {\n const raw = state.query?.[key];\n if (typeof raw === \"string\" && raw !== \"\") {\n merged[key] = raw;\n }\n }\n for (const [k, v] of Object.entries(missingInitials)) {\n merged[k] = v;\n }\n router.setQueryParams(merged);\n }\n // querySig is the meaningful trigger; form/keys/router are stable.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [querySig]);\n\n // form → URL. Listen for changes on the watched keys only.\n useEffect(() => {\n if (!alepha.isBrowser()) return;\n const off = alepha.events.on(\"form:change\", (e: any) => {\n if (e.id !== form.id) return;\n if (!keys.includes(e.path)) return;\n const next: Record<string, string> = {};\n const values = (form as unknown as { currentValues: Record<string, any> })\n .currentValues;\n for (const key of keys) {\n const value = values[key];\n if (value != null && value !== \"\") {\n next[key] = String(value);\n }\n }\n // Replace-state (default) — filters shouldn't pollute history.\n router.setQueryParams(next);\n });\n return off;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [alepha, form, router]);\n};\n","import type { TObject } from \"alepha\";\nimport { useAlepha } from \"alepha/react\";\nimport { useEffect, useState } from \"react\";\nimport type { FormModel } from \"../services/FormModel.ts\";\n\n/**\n * Hook to subscribe to all form values.\n * Re-renders on every field change — use only when needed (debug panels, live previews).\n */\nexport const useFormValues = <T extends TObject>(\n form: FormModel<T>,\n): Record<string, any> => {\n const alepha = useAlepha();\n const [values, setValues] = useState<Record<string, any>>(form.currentValues);\n\n useEffect(() => {\n if (!alepha.isBrowser()) {\n return;\n }\n\n return alepha.events.on(\"form:change\", (ev) => {\n if (ev.id === form.id) {\n setValues(form.currentValues);\n }\n });\n }, []);\n\n return values;\n};\n","/**\n * Converts a path or identifier string into a pretty display name.\n * For paths like \"/contacts/0/name\", extracts just the field name \"Name\".\n * Handles camelCase and snake_case conversion to Title Case.\n *\n * @example\n * prettyName(\"/userName\") // \"User Name\"\n * prettyName(\"/contacts/0/email\") // \"Email\"\n * prettyName(\"/address/streetName\") // \"Street Name\"\n * prettyName(\"first_name\") // \"First Name\"\n */\nexport const prettyName = (name: string): string => {\n const segments = name.split(\"/\").filter((s) => s && !/^\\d+$/.test(s));\n const fieldName = segments[segments.length - 1] || name.replaceAll(\"/\", \"\");\n return fieldName\n .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase());\n};\n","import { type TSchema, TypeBoxError } from \"alepha\";\nimport type { BaseInputField } from \"./FormModel.ts\";\nimport { prettyName } from \"./prettyName.ts\";\n\n/**\n * Semantic icon hint derived from schema metadata. UI layers map this\n * to their own icon set — this module is headless and ships no JSX.\n */\nexport type IconHint =\n | \"email\"\n | \"password\"\n | \"phone\"\n | \"url\"\n | \"number\"\n | \"calendar\"\n | \"clock\"\n | \"list\"\n | \"text\"\n | \"user\"\n | \"file\"\n | \"switch\";\n\nexport interface FieldConstraints {\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n}\n\nexport interface FieldMeta {\n id?: string;\n label: string;\n description?: string;\n error?: string;\n required: boolean;\n type?: string;\n format?: string;\n isEnum: boolean;\n isArray: boolean;\n isObject: boolean;\n isArrayOfObjects: boolean;\n enum?: readonly unknown[];\n iconHint?: IconHint;\n constraints: FieldConstraints;\n testId?: string;\n schema: TSchema;\n /**\n * Raw `$control` value from the schema, untyped here. The UI layer\n * (`alepha/react/ui`) provides the strict {@link SchemaControl} type and\n * a `resolveSchemaControl` helper to evaluate the function form.\n */\n control?: unknown;\n}\n\nexport interface ParseFieldOptions {\n label?: string;\n description?: string;\n error?: Error;\n}\n\n/**\n * Derives a {@link FieldMeta} from an `InputField` (from `useForm`) plus\n * optional overrides. Pure — no React, no JSX, no UI library coupling.\n *\n * UI components consume this metadata to render labels, descriptions,\n * error messages, icons, and validation constraints.\n */\nexport const parseField = (\n input: BaseInputField,\n options: ParseFieldOptions = {},\n): FieldMeta => {\n const schema = input.schema as TSchema & {\n type?: string;\n format?: string;\n title?: string;\n description?: string;\n enum?: readonly unknown[];\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n properties?: unknown;\n items?: { properties?: unknown };\n $control?: unknown;\n };\n\n const label =\n options.label ??\n (typeof schema.title === \"string\" ? schema.title : undefined) ??\n prettyName(input.path);\n\n const description =\n options.description ??\n (typeof schema.description === \"string\" ? schema.description : undefined);\n\n const error =\n options.error instanceof TypeBoxError\n ? (options.error as TypeBoxError).value?.message\n : undefined;\n\n const type = schema.type;\n const format = typeof schema.format === \"string\" ? schema.format : undefined;\n const isEnum = Array.isArray(schema.enum);\n const isArray = type === \"array\";\n const isObject = type === \"object\" && Boolean(schema.properties);\n const isArrayOfObjects =\n isArray && Boolean(schema.items && (schema.items as any).properties);\n\n const name = input.props.name;\n const iconHint = inferIconHint({ type, format, name, isEnum, isArray });\n\n const constraints: FieldConstraints = {};\n if (typeof schema.minLength === \"number\")\n constraints.minLength = schema.minLength;\n if (typeof schema.maxLength === \"number\")\n constraints.maxLength = schema.maxLength;\n if (typeof schema.minimum === \"number\") constraints.minimum = schema.minimum;\n if (typeof schema.maximum === \"number\") constraints.maximum = schema.maximum;\n if (typeof schema.pattern === \"string\") constraints.pattern = schema.pattern;\n\n return {\n id: input.props.id,\n label,\n description,\n error,\n required: input.required,\n type,\n format,\n isEnum,\n isArray,\n isObject,\n isArrayOfObjects,\n enum: schema.enum,\n iconHint,\n constraints,\n testId: (input.props as Record<string, unknown>)[\"data-testid\"] as\n | string\n | undefined,\n schema: input.schema,\n control: schema.$control,\n };\n};\n\nconst inferIconHint = (params: {\n type?: string;\n format?: string;\n name?: string;\n isEnum: boolean;\n isArray: boolean;\n}): IconHint | undefined => {\n const { type, format, name, isEnum, isArray } = params;\n\n if (format === \"email\") return \"email\";\n if (format === \"url\" || format === \"uri\") return \"url\";\n if (format === \"tel\" || format === \"phone\") return \"phone\";\n if (format === \"date\" || format === \"date-time\") return \"calendar\";\n if (format === \"time\") return \"clock\";\n\n if (name?.toLowerCase().includes(\"password\")) return \"password\";\n if (name?.toLowerCase().includes(\"email\")) return \"email\";\n if (name?.toLowerCase().includes(\"phone\")) return \"phone\";\n\n if (type === \"boolean\") return \"switch\";\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (isEnum || isArray) return \"list\";\n if (type === \"string\") return \"text\";\n\n return undefined;\n};\n","import { $module } from \"alepha\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport { default as FormState } from \"./components/FormState.tsx\";\nexport * from \"./errors/FormValidationError.ts\";\nexport * from \"./hooks/useFieldValue.ts\";\nexport * from \"./hooks/useForm.ts\";\nexport * from \"./hooks/useFormQuerySync.ts\";\nexport * from \"./hooks/useFormState.ts\";\nexport * from \"./hooks/useFormValues.ts\";\nexport * from \"./services/FormModel.ts\";\nexport * from \"./services/parseField.ts\";\nexport * from \"./services/prettyName.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha\" {\n interface Hooks {\n \"form:change\": {\n id: string;\n path: string;\n value: any;\n /**\n * Programmatic reset (e.g. `setInitialValues` after the parent updates\n * its state). Subscribers tracking dirty state should ignore these.\n */\n initial?: boolean;\n };\n \"form:submit:begin\": { id: string };\n \"form:submit:success\": { id: string; values: Record<string, any> };\n \"form:submit:error\": { id: string; error: Error };\n \"form:submit:end\": { id: string };\n \"form:reset\": { id: string };\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Type-safe forms with validation.\n *\n * **Features:**\n * - Form state management\n * - TypeBox schema validation\n * - Field-level error handling\n * - Submit handling with loading state\n * - Form reset\n *\n * @module alepha.react.form\n */\nexport const AlephaReactForm = $module({\n name: \"alepha.react.form\",\n});\n"],"mappings":";;;;;;AAYA,MAAa,gBAIX,QACA,UAAkB;CAAC;CAAW;CAAS;AAAO,MACX;CACnC,MAAM,SAAS,UAAU;CACzB,MAAM,SAAS;CAEf,MAAM,CAAC,OAAO,YAAY,SAAS,KAAK;CACxC,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAC5C,MAAM,CAAC,OAAO,YAAY,SAA4B,KAAA,CAAS;CAC/D,MAAM,CAAC,QAAQ,aAAa,SAC1B,KAAA,CACF;CAEA,MAAM,OAAO,UAAU,SAAS,OAAO,OAAO;CAC9C,MAAM,OAAO,UAAU,SAAS,OAAO,OAAO,KAAA;CAE9C,MAAM,YAAY,OAAO,SAAS,QAAQ;CAC1C,MAAM,YAAY,OAAO,SAAS,OAAO;CACzC,MAAM,WAAW,OAAO,SAAS,OAAO;CACxC,MAAM,aAAa,OAAO,SAAS,SAAS;CAE5C,gBAAgB;EACd,MAAM,YAAwB,CAAC;EAE/B,IAAI,aAAa,aAAa,UAC5B,UAAU,KACR,OAAO,OAAO,GAAG,gBAAgB,UAAU;GACzC,IAAI,MAAM,OAAO,KAAK,IAAI;IACxB,IAAI,CAAC,QAAQ,MAAM,SAAS,MAAM;KAIhC,IAAI,UACF,IAAI,MAAM,SACR,SAAS,KAAK;UAEd,SAAS,IAAI;KAGjB,IAAI,WACF,SAAS,KAAA,CAAS;IAEtB;IACA,IAAI,WACF,UAAU,KAAK,aAAa;GAEhC;EACF,CAAC,CACH;EAGF,IAAI,YACF,UAAU,KACR,OAAO,OAAO,GAAG,sBAAsB,UAAU;GAC/C,IAAI,M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W,UAAU,WAAW,aAAa,OAAO;CACxD,IAAI,WAAW,QAAQ,OAAO;CAE9B,IAAI,MAAM,YAAY,EAAE,SAAS,UAAU,GAAG,OAAO;CACrD,IAAI,MAAM,YAAY,EAAE,SAAS,OAAO,GAAG,OAAO;CAClD,IAAI,MAAM,YAAY,EAAE,SAAS,OAAO,GAAG,OAAO;CAElD,IAAI,SAAS,WAAW,OAAO;CAC/B,IAAI,SAAS,YAAY,SAAS,WAAW,OAAO;CACpD,IAAI,UAAU,SAAS,OAAO;CAC9B,IAAI,SAAS,UAAU,OAAO;AAGhC;;;;;;;;;;;;;;;ACvHA,MAAa,kBAAkB,QAAQ,EACrC,MAAM,oBACR,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Alepha, Async, KIND, Primitive, TypeBoxError } from "alepha";
|
|
2
2
|
import { DateTime, DateTimeProvider } from "alepha/datetime";
|
|
3
|
+
import { RouterLocaleProvider } from "alepha/react/router";
|
|
3
4
|
|
|
4
5
|
//#region ../../src/react/i18n/components/Localize.d.ts
|
|
5
6
|
interface LocalizeProps {
|
|
@@ -83,7 +84,17 @@ declare class I18nProvider<S extends object, K extends keyof ServiceDictionary<S
|
|
|
83
84
|
}>;
|
|
84
85
|
options: {
|
|
85
86
|
fallbackLang: string;
|
|
87
|
+
autoDetect: boolean;
|
|
88
|
+
routing: "none" | "prefix";
|
|
86
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* Lazily-resolved locale-prefix router integration. Present only when both
|
|
92
|
+
* the router module is registered AND `routing: "prefix"` was configured —
|
|
93
|
+
* otherwise i18n stays fully standalone.
|
|
94
|
+
*/
|
|
95
|
+
protected localeProviderResolved: boolean;
|
|
96
|
+
protected localeProviderRef?: RouterLocaleProvider;
|
|
97
|
+
protected get localeProvider(): RouterLocaleProvider | undefined;
|
|
87
98
|
dateFormat: {
|
|
88
99
|
format: (value: Date) => string;
|
|
89
100
|
};
|
|
@@ -92,9 +103,41 @@ declare class I18nProvider<S extends object, K extends keyof ServiceDictionary<S
|
|
|
92
103
|
};
|
|
93
104
|
get languages(): string[];
|
|
94
105
|
constructor();
|
|
106
|
+
/**
|
|
107
|
+
* Configure locale-prefix routing on the router, before the SSR routes are
|
|
108
|
+
* registered (`priority: "first"` runs ahead of the router's own `configure`
|
|
109
|
+
* hook). No-op unless `routing: "prefix"` and the router module is present.
|
|
110
|
+
*/
|
|
111
|
+
protected readonly onConfigure: import("alepha").HookPrimitive<"configure">;
|
|
95
112
|
protected readonly onRender: import("alepha").HookPrimitive<"server:onRequest">;
|
|
113
|
+
/**
|
|
114
|
+
* Detects the language carried by the request URL when `routing: "prefix"` is
|
|
115
|
+
* active. Returns the locale for any URL (the prefixed one for `/fr/...`, the
|
|
116
|
+
* default for an unprefixed path), or `undefined` when prefix routing is off.
|
|
117
|
+
*/
|
|
118
|
+
protected detectUrlLocale(pathname: string | undefined): string | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* Resolves the UI language for an incoming server request.
|
|
121
|
+
*
|
|
122
|
+
* Priority:
|
|
123
|
+
* 0. the URL locale prefix (`routing: "prefix"`) — the URL is the source of
|
|
124
|
+
* truth and wins over everything, with no redirect;
|
|
125
|
+
* 1. the `lang` cookie — a language the user manually selected;
|
|
126
|
+
* 2. the `Accept-Language` header (when `autoDetect` is enabled) — but only
|
|
127
|
+
* when the detected language is actually registered, so we never switch to
|
|
128
|
+
* a locale we have no dictionary for. A region-qualified header (`en-US`)
|
|
129
|
+
* matches an exact registration first, then its base language (`en`);
|
|
130
|
+
* 3. `fallbackLang`.
|
|
131
|
+
*/
|
|
132
|
+
protected resolveRequestLang(cookieLang: string | undefined, headerLang: string | undefined, urlLocale?: string): string;
|
|
96
133
|
protected readonly onStart: import("alepha").HookPrimitive<"start">;
|
|
97
134
|
protected refreshLocale(): void;
|
|
135
|
+
/**
|
|
136
|
+
* Activates a language: lazily loads its dictionaries (browser), updates the
|
|
137
|
+
* lang state, and refreshes the locale-bound formatters. Does NOT persist a
|
|
138
|
+
* cookie or navigate — that is the caller's concern.
|
|
139
|
+
*/
|
|
140
|
+
protected applyLang: (lang: string) => Promise<void>;
|
|
98
141
|
setLang: (lang: string) => Promise<void>;
|
|
99
142
|
protected readonly mutate: import("alepha").HookPrimitive<"state:mutate">;
|
|
100
143
|
get fallbackLang(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/react/i18n/components/Localize.tsx","../../../src/react/i18n/components/Translate.tsx","../../../src/react/i18n/providers/I18nProvider.ts","../../../src/react/i18n/primitives/$dictionary.ts","../../../src/react/i18n/hooks/useI18n.ts","../../../src/react/i18n/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/react/i18n/components/Localize.tsx","../../../src/react/i18n/components/Translate.tsx","../../../src/react/i18n/providers/I18nProvider.ts","../../../src/react/i18n/primitives/$dictionary.ts","../../../src/react/i18n/hooks/useI18n.ts","../../../src/react/i18n/index.ts"],"mappings":";;;;;UAIiB,aAAA;EACf,KAAA,oBAAyB,IAAA,GAAO,QAAA,GAAW,YAAA;;AAD7C;;;EAME,MAAA,GAAS,IAAA,CAAK,mBAAA;EALkB;;;;;;;;;EAehC,IAAA,wBAA4B,IAAA,CAAK,qBAAA;EAVjC;;;;;EAgBA,QAAA;AAAA;AAAA,cAGI,QAAA,GAAY,KAAoB,EAAb,aAAa;;;UC3BrB,cAAA;;;;EAIf,CAAA;EDFe;;;ECMf,IAAA;EDLgC;;;;ECUhC,QAAA;AAAA;;;;;;;;;;;;;ADWQ;AACT;;;;AAEqC;cCOzB,SAAA,GAAa,KAAA,EAAO,cAAc,iCAAA,GAAA,CAAA,OAAA;;;AAlC/C;cA0Ca,EAAA,GAAE,KAAA,EARkB,cAAc,iCAAA,GAAA,CAAA,OAAA;;;cC3BlC,YAAA,mCAEK,iBAAA,CAAkB,CAAA;EAAA,UAExB,GAAA,0BAAG,MAAA;EAAA,UACH,MAAA,EAAM,M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AO,QAAA,GAAW,YAAA;AAAA,UAElD,mBAAA;EA3Zf;;;;EAgaA,MAAA,GAAS,IAAA,CAAK,mBAAA;EA7ZJ;;;;;;;;;EAuaV,IAAA,wBAA4B,IAAA,CAAK,qBAAqB;EA5ZpD;;;;;EAkaF,QAAA;AAAA;;;;;;AFvbF;;;;;;;;;;;;;;;;;;;;;;AAsBU;AACT;;;;AAEqC;cGKzB,WAAA;EAAA,WAAyB,MAAA,kBAAsB,OAAA,EACjD,0BAAA,CAA2B,CAAA,IACnC,mBAAA,CAAoB,CAAA;EAAA;;UAMN,0BAAA,WAAqC,MAAA;EACpD,IAAA;EACA,IAAA;EACA,IAAA,QAAY,KAAA;IAAQ,OAAA,EAAS,CAAA;EAAA;AAAA;AAAA,cAKlB,mBAAA,WACD,MAAA,0BACF,SAAA,CAAU,0BAAA,CAA2B,CAAA;EAAA,UACnC,QAAA,EAAQ,YAAA;EAAA,UACR,MAAA;AAAA;;;;;;cC/CC,OAAA,qCAEK,iBAAA,CAAkB,CAAA,QAC/B,YAAA,CAAa,CAAA,EAAG,CAAA;AAAA,KAKT,iBAAA,mCACE,CAAA,GAAI,CAAA,CAAE,CAAA,UAAW,mBAAA,YAA+B,CAAA;;;;YCC3C,KAAA;IACf,wBAAwB;EAAA;AAAA;;;;;;;;;;;cAgBf,eAAA,mBAAe,OAAA,kBAAA,MAAA"}
|
package/dist/react/i18n/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { $hook, $inject, $module, Alepha, KIND, Primitive, TypeBoxError, TypeProvider, createPrimitive, t } from "alepha";
|
|
2
2
|
import { DateTimeProvider } from "alepha/datetime";
|
|
3
3
|
import { $logger } from "alepha/logger";
|
|
4
|
+
import { RouterLocaleProvider } from "alepha/react/router";
|
|
4
5
|
import { $cookie } from "alepha/server/cookies";
|
|
5
6
|
import { useInject, useStore } from "alepha/react";
|
|
6
7
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
@@ -15,7 +16,42 @@ var I18nProvider = class {
|
|
|
15
16
|
ttl: [1, "year"]
|
|
16
17
|
});
|
|
17
18
|
registry = [];
|
|
18
|
-
options = {
|
|
19
|
+
options = {
|
|
20
|
+
fallbackLang: "en",
|
|
21
|
+
/**
|
|
22
|
+
* When true (the default), the UI language for a first-time visitor (one
|
|
23
|
+
* with no `lang` cookie) is detected server-side from the `Accept-Language`
|
|
24
|
+
* header. A manually-selected language (the cookie) always takes
|
|
25
|
+
* precedence, so this never overrides an explicit user choice. Set to false
|
|
26
|
+
* to always start in `fallbackLang` regardless of the browser's preferred
|
|
27
|
+
* language.
|
|
28
|
+
*/
|
|
29
|
+
autoDetect: true,
|
|
30
|
+
/**
|
|
31
|
+
* URL strategy for languages:
|
|
32
|
+
* - `"none"` (default): language lives in a cookie; URLs are not localized.
|
|
33
|
+
* - `"prefix"`: each non-default language gets a path prefix (`/fr/about`),
|
|
34
|
+
* making every language a distinct, crawlable URL for SEO. The default
|
|
35
|
+
* language (`fallbackLang`) stays unprefixed. Requires the router module.
|
|
36
|
+
* The URL becomes the source of truth for language (it wins over the
|
|
37
|
+
* cookie / `Accept-Language`), and there is no automatic redirect.
|
|
38
|
+
*/
|
|
39
|
+
routing: "none"
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Lazily-resolved locale-prefix router integration. Present only when both
|
|
43
|
+
* the router module is registered AND `routing: "prefix"` was configured —
|
|
44
|
+
* otherwise i18n stays fully standalone.
|
|
45
|
+
*/
|
|
46
|
+
localeProviderResolved = false;
|
|
47
|
+
localeProviderRef;
|
|
48
|
+
get localeProvider() {
|
|
49
|
+
if (!this.localeProviderResolved) {
|
|
50
|
+
this.localeProviderResolved = true;
|
|
51
|
+
if (this.alepha.has(RouterLocaleProvider)) this.localeProviderRef = this.alepha.inject(RouterLocaleProvider);
|
|
52
|
+
}
|
|
53
|
+
return this.localeProviderRef;
|
|
54
|
+
}
|
|
19
55
|
dateFormat = new Intl.DateTimeFormat(this.lang);
|
|
20
56
|
numberFormat = new Intl.NumberFormat(this.lang);
|
|
21
57
|
get languages() {
|
|
@@ -26,19 +62,69 @@ var I18nProvider = class {
|
|
|
26
62
|
constructor() {
|
|
27
63
|
this.refreshLocale();
|
|
28
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Configure locale-prefix routing on the router, before the SSR routes are
|
|
67
|
+
* registered (`priority: "first"` runs ahead of the router's own `configure`
|
|
68
|
+
* hook). No-op unless `routing: "prefix"` and the router module is present.
|
|
69
|
+
*/
|
|
70
|
+
onConfigure = $hook({
|
|
71
|
+
on: "configure",
|
|
72
|
+
priority: "first",
|
|
73
|
+
handler: () => {
|
|
74
|
+
const localeProvider = this.localeProvider;
|
|
75
|
+
if (this.options.routing === "prefix" && localeProvider) localeProvider.configure({
|
|
76
|
+
enabled: true,
|
|
77
|
+
defaultLocale: this.fallbackLang,
|
|
78
|
+
locales: this.languages
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
});
|
|
29
82
|
onRender = $hook({
|
|
30
83
|
on: "server:onRequest",
|
|
31
84
|
priority: "last",
|
|
32
85
|
handler: async ({ request }) => {
|
|
33
|
-
this.alepha.store.set("alepha.react.i18n.lang", this.cookie.get(request));
|
|
86
|
+
this.alepha.store.set("alepha.react.i18n.lang", this.resolveRequestLang(this.cookie.get(request), request.language, this.detectUrlLocale(request.url?.pathname)));
|
|
34
87
|
}
|
|
35
88
|
});
|
|
89
|
+
/**
|
|
90
|
+
* Detects the language carried by the request URL when `routing: "prefix"` is
|
|
91
|
+
* active. Returns the locale for any URL (the prefixed one for `/fr/...`, the
|
|
92
|
+
* default for an unprefixed path), or `undefined` when prefix routing is off.
|
|
93
|
+
*/
|
|
94
|
+
detectUrlLocale(pathname) {
|
|
95
|
+
const localeProvider = this.localeProvider;
|
|
96
|
+
if (localeProvider?.enabled && pathname) return localeProvider.detect(pathname).locale || void 0;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Resolves the UI language for an incoming server request.
|
|
100
|
+
*
|
|
101
|
+
* Priority:
|
|
102
|
+
* 0. the URL locale prefix (`routing: "prefix"`) — the URL is the source of
|
|
103
|
+
* truth and wins over everything, with no redirect;
|
|
104
|
+
* 1. the `lang` cookie — a language the user manually selected;
|
|
105
|
+
* 2. the `Accept-Language` header (when `autoDetect` is enabled) — but only
|
|
106
|
+
* when the detected language is actually registered, so we never switch to
|
|
107
|
+
* a locale we have no dictionary for. A region-qualified header (`en-US`)
|
|
108
|
+
* matches an exact registration first, then its base language (`en`);
|
|
109
|
+
* 3. `fallbackLang`.
|
|
110
|
+
*/
|
|
111
|
+
resolveRequestLang(cookieLang, headerLang, urlLocale) {
|
|
112
|
+
if (urlLocale) return urlLocale;
|
|
113
|
+
if (cookieLang) return cookieLang;
|
|
114
|
+
if (this.options.autoDetect && headerLang) {
|
|
115
|
+
const registered = this.languages;
|
|
116
|
+
for (const candidate of [headerLang, headerLang.split("-")[0]]) if (registered.includes(candidate)) return candidate;
|
|
117
|
+
}
|
|
118
|
+
return this.fallbackLang;
|
|
119
|
+
}
|
|
36
120
|
onStart = $hook({
|
|
37
121
|
on: "start",
|
|
38
122
|
handler: async () => {
|
|
39
123
|
if (this.alepha.isBrowser()) {
|
|
40
|
-
|
|
41
|
-
|
|
124
|
+
if (!this.localeProvider?.enabled) {
|
|
125
|
+
const cookieLang = this.cookie.get();
|
|
126
|
+
if (cookieLang) this.alepha.store.set("alepha.react.i18n.lang", cookieLang);
|
|
127
|
+
}
|
|
42
128
|
for (const item of this.registry) if (item.lang === this.lang || item.lang === this.fallbackLang) {
|
|
43
129
|
this.log.trace("Loading language", {
|
|
44
130
|
lang: item.lang,
|
|
@@ -58,20 +144,38 @@ var I18nProvider = class {
|
|
|
58
144
|
this.dateTimeProvider.setLocale(this.lang);
|
|
59
145
|
TypeProvider.setLocale(this.lang);
|
|
60
146
|
}
|
|
61
|
-
|
|
147
|
+
/**
|
|
148
|
+
* Activates a language: lazily loads its dictionaries (browser), updates the
|
|
149
|
+
* lang state, and refreshes the locale-bound formatters. Does NOT persist a
|
|
150
|
+
* cookie or navigate — that is the caller's concern.
|
|
151
|
+
*/
|
|
152
|
+
applyLang = async (lang) => {
|
|
62
153
|
if (this.alepha.isBrowser()) {
|
|
63
|
-
for (const item of this.registry) if (lang === item.lang)
|
|
64
|
-
if (Object.keys(item.translations).length > 0) continue;
|
|
65
|
-
item.translations = await item.loader();
|
|
66
|
-
}
|
|
67
|
-
this.cookie.set(lang);
|
|
154
|
+
for (const item of this.registry) if (lang === item.lang && Object.keys(item.translations).length === 0) item.translations = await item.loader();
|
|
68
155
|
}
|
|
69
156
|
this.alepha.store.set("alepha.react.i18n.lang", lang);
|
|
70
157
|
this.refreshLocale();
|
|
71
158
|
};
|
|
159
|
+
setLang = async (lang) => {
|
|
160
|
+
const localeProvider = this.localeProvider;
|
|
161
|
+
if (localeProvider?.enabled) {
|
|
162
|
+
const { ReactRouter } = await import("alepha/react/router");
|
|
163
|
+
const router = this.alepha.inject(ReactRouter);
|
|
164
|
+
const canonical = localeProvider.detect(router.pathname).pathname;
|
|
165
|
+
await router.push(localeProvider.withPrefix(canonical, lang));
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
await this.applyLang(lang);
|
|
169
|
+
if (this.alepha.isBrowser()) this.cookie.set(lang);
|
|
170
|
+
};
|
|
72
171
|
mutate = $hook({
|
|
73
172
|
on: "state:mutate",
|
|
74
173
|
handler: async ({ key, value }) => {
|
|
174
|
+
if (key === "alepha.react.router.locale" && this.localeProvider?.enabled) {
|
|
175
|
+
const lang = value || this.fallbackLang;
|
|
176
|
+
if (lang !== this.lang) await this.applyLang(lang);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
75
179
|
if (key === "alepha.react.i18n.lang" && this.alepha.isBrowser()) {
|
|
76
180
|
let hasChanged = false;
|
|
77
181
|
for (const item of this.registry) if (value === item.lang) {
|