index.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. import { isReactive, isReadonly, computed, unref, ref, watch, isRef, reactive, nextTick, inject, provide, getCurrentInstance, onBeforeMount, onBeforeUnmount } from 'vue-demi';
  2. function ownKeys(object, enumerableOnly) {
  3. var keys = Object.keys(object);
  4. if (Object.getOwnPropertySymbols) {
  5. var symbols = Object.getOwnPropertySymbols(object);
  6. enumerableOnly && (symbols = symbols.filter(function (sym) {
  7. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  8. })), keys.push.apply(keys, symbols);
  9. }
  10. return keys;
  11. }
  12. function _objectSpread2(target) {
  13. for (var i = 1; i < arguments.length; i++) {
  14. var source = null != arguments[i] ? arguments[i] : {};
  15. i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
  16. _defineProperty(target, key, source[key]);
  17. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
  18. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  19. });
  20. }
  21. return target;
  22. }
  23. function _defineProperty(obj, key, value) {
  24. if (key in obj) {
  25. Object.defineProperty(obj, key, {
  26. value: value,
  27. enumerable: true,
  28. configurable: true,
  29. writable: true
  30. });
  31. } else {
  32. obj[key] = value;
  33. }
  34. return obj;
  35. }
  36. function unwrapObj(obj) {
  37. let ignoreKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  38. return Object.keys(obj).reduce((o, k) => {
  39. if (ignoreKeys.includes(k)) return o;
  40. o[k] = unref(obj[k]);
  41. return o;
  42. }, {});
  43. }
  44. function isFunction(val) {
  45. return typeof val === 'function';
  46. }
  47. function isProxy(value) {
  48. return isReactive(value) || isReadonly(value);
  49. }
  50. function get(obj, stringPath, def) {
  51. let current = obj;
  52. const path = stringPath.split('.');
  53. for (let i = 0; i < path.length; i++) {
  54. if (!current[path[i]]) return def;
  55. current = current[path[i]];
  56. }
  57. return current;
  58. }
  59. function gatherBooleanGroupProperties(group, nestedResults, property) {
  60. return computed(() => {
  61. return group.some(path => {
  62. return get(nestedResults, path, {
  63. [property]: false
  64. })[property];
  65. });
  66. });
  67. }
  68. function gatherArrayGroupProperties(group, nestedResults, property) {
  69. return computed(() => {
  70. return group.reduce((all, path) => {
  71. const fetchedProperty = get(nestedResults, path, {
  72. [property]: false
  73. })[property] || [];
  74. return all.concat(fetchedProperty);
  75. }, []);
  76. });
  77. }
  78. function callRule(rule, value, siblingState, instance) {
  79. return rule.call(instance, unref(value), unref(siblingState), instance);
  80. }
  81. function normalizeValidatorResponse(result) {
  82. return result.$valid !== undefined ? !result.$valid : !result;
  83. }
  84. function createAsyncResult(rule, model, $pending, $dirty, _ref, $response, instance) {
  85. let {
  86. $lazy,
  87. $rewardEarly
  88. } = _ref;
  89. let watchTargets = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : [];
  90. let siblingState = arguments.length > 8 ? arguments[8] : undefined;
  91. let $lastInvalidState = arguments.length > 9 ? arguments[9] : undefined;
  92. let $lastCommittedOn = arguments.length > 10 ? arguments[10] : undefined;
  93. const $invalid = ref(!!$dirty.value);
  94. const $pendingCounter = ref(0);
  95. $pending.value = false;
  96. const $unwatch = watch([model, $dirty].concat(watchTargets, $lastCommittedOn), () => {
  97. if ($lazy && !$dirty.value || $rewardEarly && !$lastInvalidState.value && !$pending.value) {
  98. return;
  99. }
  100. let ruleResult;
  101. try {
  102. ruleResult = callRule(rule, model, siblingState, instance);
  103. } catch (err) {
  104. ruleResult = Promise.reject(err);
  105. }
  106. $pendingCounter.value++;
  107. $pending.value = !!$pendingCounter.value;
  108. $invalid.value = false;
  109. Promise.resolve(ruleResult).then(data => {
  110. $pendingCounter.value--;
  111. $pending.value = !!$pendingCounter.value;
  112. $response.value = data;
  113. $invalid.value = normalizeValidatorResponse(data);
  114. }).catch(error => {
  115. $pendingCounter.value--;
  116. $pending.value = !!$pendingCounter.value;
  117. $response.value = error;
  118. $invalid.value = true;
  119. });
  120. }, {
  121. immediate: true,
  122. deep: typeof model === 'object'
  123. });
  124. return {
  125. $invalid,
  126. $unwatch
  127. };
  128. }
  129. function createSyncResult(rule, model, $dirty, _ref2, $response, instance, siblingState, $lastInvalidState) {
  130. let {
  131. $lazy,
  132. $rewardEarly
  133. } = _ref2;
  134. const $unwatch = () => ({});
  135. const $invalid = computed(() => {
  136. if ($lazy && !$dirty.value || $rewardEarly && !$lastInvalidState.value) {
  137. return false;
  138. }
  139. let returnValue = true;
  140. try {
  141. const result = callRule(rule, model, siblingState, instance);
  142. $response.value = result;
  143. returnValue = normalizeValidatorResponse(result);
  144. } catch (err) {
  145. $response.value = err;
  146. }
  147. return returnValue;
  148. });
  149. return {
  150. $unwatch,
  151. $invalid
  152. };
  153. }
  154. function createValidatorResult(rule, model, $dirty, config, instance, validatorName, propertyKey, propertyPath, siblingState, $lastInvalidState, $lastCommittedOn) {
  155. const $pending = ref(false);
  156. const $params = rule.$params || {};
  157. const $response = ref(null);
  158. let $invalid;
  159. let $unwatch;
  160. if (rule.$async) {
  161. ({
  162. $invalid,
  163. $unwatch
  164. } = createAsyncResult(rule.$validator, model, $pending, $dirty, config, $response, instance, rule.$watchTargets, siblingState, $lastInvalidState, $lastCommittedOn));
  165. } else {
  166. ({
  167. $invalid,
  168. $unwatch
  169. } = createSyncResult(rule.$validator, model, $dirty, config, $response, instance, siblingState, $lastInvalidState));
  170. }
  171. const message = rule.$message;
  172. const $message = isFunction(message) ? computed(() => message(unwrapObj({
  173. $pending,
  174. $invalid,
  175. $params: unwrapObj($params),
  176. $model: model,
  177. $response,
  178. $validator: validatorName,
  179. $propertyPath: propertyPath,
  180. $property: propertyKey
  181. }))) : message || '';
  182. return {
  183. $message,
  184. $params,
  185. $pending,
  186. $invalid,
  187. $response,
  188. $unwatch
  189. };
  190. }
  191. function sortValidations() {
  192. let validationsRaw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  193. const validations = unref(validationsRaw);
  194. const validationKeys = Object.keys(validations);
  195. const rules = {};
  196. const nestedValidators = {};
  197. const config = {};
  198. let validationGroups = null;
  199. validationKeys.forEach(key => {
  200. const v = validations[key];
  201. switch (true) {
  202. case isFunction(v.$validator):
  203. rules[key] = v;
  204. break;
  205. case isFunction(v):
  206. rules[key] = {
  207. $validator: v
  208. };
  209. break;
  210. case key === '$validationGroups':
  211. validationGroups = v;
  212. break;
  213. case key.startsWith('$'):
  214. config[key] = v;
  215. break;
  216. default:
  217. nestedValidators[key] = v;
  218. }
  219. });
  220. return {
  221. rules,
  222. nestedValidators,
  223. config,
  224. validationGroups
  225. };
  226. }
  227. const ROOT_PATH = '__root';
  228. function createValidationResults(rules, model, key, resultsCache, path, config, instance, externalResults, siblingState) {
  229. const ruleKeys = Object.keys(rules);
  230. const cachedResult = resultsCache.get(path, rules);
  231. const $dirty = ref(false);
  232. const $lastInvalidState = ref(false);
  233. const $lastCommittedOn = ref(0);
  234. if (cachedResult) {
  235. if (!cachedResult.$partial) return cachedResult;
  236. cachedResult.$unwatch();
  237. $dirty.value = cachedResult.$dirty.value;
  238. }
  239. const result = {
  240. $dirty,
  241. $path: path,
  242. $touch: () => {
  243. if (!$dirty.value) $dirty.value = true;
  244. },
  245. $reset: () => {
  246. if ($dirty.value) $dirty.value = false;
  247. },
  248. $commit: () => {}
  249. };
  250. if (!ruleKeys.length) {
  251. cachedResult && resultsCache.set(path, rules, result);
  252. return result;
  253. }
  254. ruleKeys.forEach(ruleKey => {
  255. result[ruleKey] = createValidatorResult(rules[ruleKey], model, result.$dirty, config, instance, ruleKey, key, path, siblingState, $lastInvalidState, $lastCommittedOn);
  256. });
  257. result.$externalResults = computed(() => {
  258. if (!externalResults.value) return [];
  259. return [].concat(externalResults.value).map((stringError, index) => ({
  260. $propertyPath: path,
  261. $property: key,
  262. $validator: '$externalResults',
  263. $uid: `${path}-externalResult-${index}`,
  264. $message: stringError,
  265. $params: {},
  266. $response: null,
  267. $pending: false
  268. }));
  269. });
  270. result.$invalid = computed(() => {
  271. const r = ruleKeys.some(ruleKey => unref(result[ruleKey].$invalid));
  272. $lastInvalidState.value = r;
  273. return !!result.$externalResults.value.length || r;
  274. });
  275. result.$pending = computed(() => ruleKeys.some(ruleKey => unref(result[ruleKey].$pending)));
  276. result.$error = computed(() => result.$dirty.value ? result.$pending.value || result.$invalid.value : false);
  277. result.$silentErrors = computed(() => ruleKeys.filter(ruleKey => unref(result[ruleKey].$invalid)).map(ruleKey => {
  278. const res = result[ruleKey];
  279. return reactive({
  280. $propertyPath: path,
  281. $property: key,
  282. $validator: ruleKey,
  283. $uid: `${path}-${ruleKey}`,
  284. $message: res.$message,
  285. $params: res.$params,
  286. $response: res.$response,
  287. $pending: res.$pending
  288. });
  289. }).concat(result.$externalResults.value));
  290. result.$errors = computed(() => result.$dirty.value ? result.$silentErrors.value : []);
  291. result.$unwatch = () => ruleKeys.forEach(ruleKey => {
  292. result[ruleKey].$unwatch();
  293. });
  294. result.$commit = () => {
  295. $lastInvalidState.value = true;
  296. $lastCommittedOn.value = Date.now();
  297. };
  298. resultsCache.set(path, rules, result);
  299. return result;
  300. }
  301. function collectNestedValidationResults(validations, nestedState, path, resultsCache, config, instance, nestedExternalResults) {
  302. const nestedValidationKeys = Object.keys(validations);
  303. if (!nestedValidationKeys.length) return {};
  304. return nestedValidationKeys.reduce((results, nestedKey) => {
  305. results[nestedKey] = setValidations({
  306. validations: validations[nestedKey],
  307. state: nestedState,
  308. key: nestedKey,
  309. parentKey: path,
  310. resultsCache,
  311. globalConfig: config,
  312. instance,
  313. externalResults: nestedExternalResults
  314. });
  315. return results;
  316. }, {});
  317. }
  318. function createMetaFields(results, nestedResults, childResults) {
  319. const allResults = computed(() => [nestedResults, childResults].filter(res => res).reduce((allRes, res) => {
  320. return allRes.concat(Object.values(unref(res)));
  321. }, []));
  322. const $dirty = computed({
  323. get() {
  324. return results.$dirty.value || (allResults.value.length ? allResults.value.every(r => r.$dirty) : false);
  325. },
  326. set(v) {
  327. results.$dirty.value = v;
  328. }
  329. });
  330. const $silentErrors = computed(() => {
  331. const modelErrors = unref(results.$silentErrors) || [];
  332. const nestedErrors = allResults.value.filter(result => (unref(result).$silentErrors || []).length).reduce((errors, result) => {
  333. return errors.concat(...result.$silentErrors);
  334. }, []);
  335. return modelErrors.concat(nestedErrors);
  336. });
  337. const $errors = computed(() => {
  338. const modelErrors = unref(results.$errors) || [];
  339. const nestedErrors = allResults.value.filter(result => (unref(result).$errors || []).length).reduce((errors, result) => {
  340. return errors.concat(...result.$errors);
  341. }, []);
  342. return modelErrors.concat(nestedErrors);
  343. });
  344. const $invalid = computed(() => allResults.value.some(r => r.$invalid) || unref(results.$invalid) || false);
  345. const $pending = computed(() => allResults.value.some(r => unref(r.$pending)) || unref(results.$pending) || false);
  346. const $anyDirty = computed(() => allResults.value.some(r => r.$dirty) || allResults.value.some(r => r.$anyDirty) || $dirty.value);
  347. const $error = computed(() => $dirty.value ? $pending.value || $invalid.value : false);
  348. const $touch = () => {
  349. results.$touch();
  350. allResults.value.forEach(result => {
  351. result.$touch();
  352. });
  353. };
  354. const $commit = () => {
  355. results.$commit();
  356. allResults.value.forEach(result => {
  357. result.$commit();
  358. });
  359. };
  360. const $reset = () => {
  361. results.$reset();
  362. allResults.value.forEach(result => {
  363. result.$reset();
  364. });
  365. };
  366. if (allResults.value.length && allResults.value.every(nr => nr.$dirty)) $touch();
  367. return {
  368. $dirty,
  369. $errors,
  370. $invalid,
  371. $anyDirty,
  372. $error,
  373. $pending,
  374. $touch,
  375. $reset,
  376. $silentErrors,
  377. $commit
  378. };
  379. }
  380. function setValidations(_ref) {
  381. let {
  382. validations,
  383. state,
  384. key,
  385. parentKey,
  386. childResults,
  387. resultsCache,
  388. globalConfig = {},
  389. instance,
  390. externalResults
  391. } = _ref;
  392. const path = parentKey ? `${parentKey}.${key}` : key;
  393. const {
  394. rules,
  395. nestedValidators,
  396. config,
  397. validationGroups
  398. } = sortValidations(validations);
  399. const mergedConfig = _objectSpread2(_objectSpread2({}, globalConfig), config);
  400. const nestedState = key ? computed(() => {
  401. const s = unref(state);
  402. return s ? unref(s[key]) : undefined;
  403. }) : state;
  404. const cachedExternalResults = _objectSpread2({}, unref(externalResults) || {});
  405. const nestedExternalResults = computed(() => {
  406. const results = unref(externalResults);
  407. if (!key) return results;
  408. return results ? unref(results[key]) : undefined;
  409. });
  410. const results = createValidationResults(rules, nestedState, key, resultsCache, path, mergedConfig, instance, nestedExternalResults, state);
  411. const nestedResults = collectNestedValidationResults(nestedValidators, nestedState, path, resultsCache, mergedConfig, instance, nestedExternalResults);
  412. const $validationGroups = {};
  413. if (validationGroups) {
  414. Object.entries(validationGroups).forEach(_ref2 => {
  415. let [key, group] = _ref2;
  416. $validationGroups[key] = {
  417. $invalid: gatherBooleanGroupProperties(group, nestedResults, '$invalid'),
  418. $error: gatherBooleanGroupProperties(group, nestedResults, '$error'),
  419. $pending: gatherBooleanGroupProperties(group, nestedResults, '$pending'),
  420. $errors: gatherArrayGroupProperties(group, nestedResults, '$errors'),
  421. $silentErrors: gatherArrayGroupProperties(group, nestedResults, '$silentErrors')
  422. };
  423. });
  424. }
  425. const {
  426. $dirty,
  427. $errors,
  428. $invalid,
  429. $anyDirty,
  430. $error,
  431. $pending,
  432. $touch,
  433. $reset,
  434. $silentErrors,
  435. $commit
  436. } = createMetaFields(results, nestedResults, childResults);
  437. const $model = key ? computed({
  438. get: () => unref(nestedState),
  439. set: val => {
  440. $dirty.value = true;
  441. const s = unref(state);
  442. const external = unref(externalResults);
  443. if (external) {
  444. external[key] = cachedExternalResults[key];
  445. }
  446. if (isRef(s[key])) {
  447. s[key].value = val;
  448. } else {
  449. s[key] = val;
  450. }
  451. }
  452. }) : null;
  453. if (key && mergedConfig.$autoDirty) {
  454. watch(nestedState, () => {
  455. if (!$dirty.value) $touch();
  456. const external = unref(externalResults);
  457. if (external) {
  458. external[key] = cachedExternalResults[key];
  459. }
  460. }, {
  461. flush: 'sync'
  462. });
  463. }
  464. async function $validate() {
  465. $touch();
  466. if (mergedConfig.$rewardEarly) {
  467. $commit();
  468. await nextTick();
  469. }
  470. await nextTick();
  471. return new Promise(resolve => {
  472. if (!$pending.value) return resolve(!$invalid.value);
  473. const unwatch = watch($pending, () => {
  474. resolve(!$invalid.value);
  475. unwatch();
  476. });
  477. });
  478. }
  479. function $getResultsForChild(key) {
  480. return (childResults.value || {})[key];
  481. }
  482. function $clearExternalResults() {
  483. if (isRef(externalResults)) {
  484. externalResults.value = cachedExternalResults;
  485. } else {
  486. if (Object.keys(cachedExternalResults).length === 0) {
  487. Object.keys(externalResults).forEach(k => {
  488. delete externalResults[k];
  489. });
  490. } else {
  491. Object.assign(externalResults, cachedExternalResults);
  492. }
  493. }
  494. }
  495. return reactive(_objectSpread2(_objectSpread2(_objectSpread2({}, results), {}, {
  496. $model,
  497. $dirty,
  498. $error,
  499. $errors,
  500. $invalid,
  501. $anyDirty,
  502. $pending,
  503. $touch,
  504. $reset,
  505. $path: path || ROOT_PATH,
  506. $silentErrors,
  507. $validate,
  508. $commit
  509. }, childResults && {
  510. $getResultsForChild,
  511. $clearExternalResults,
  512. $validationGroups
  513. }), nestedResults));
  514. }
  515. class ResultsStorage {
  516. constructor() {
  517. this.storage = new Map();
  518. }
  519. set(path, rules, result) {
  520. this.storage.set(path, {
  521. rules,
  522. result
  523. });
  524. }
  525. checkRulesValidity(path, rules, storedRules) {
  526. const storedRulesKeys = Object.keys(storedRules);
  527. const newRulesKeys = Object.keys(rules);
  528. if (newRulesKeys.length !== storedRulesKeys.length) return false;
  529. const hasAllValidators = newRulesKeys.every(ruleKey => storedRulesKeys.includes(ruleKey));
  530. if (!hasAllValidators) return false;
  531. return newRulesKeys.every(ruleKey => {
  532. if (!rules[ruleKey].$params) return true;
  533. return Object.keys(rules[ruleKey].$params).every(paramKey => {
  534. return unref(storedRules[ruleKey].$params[paramKey]) === unref(rules[ruleKey].$params[paramKey]);
  535. });
  536. });
  537. }
  538. get(path, rules) {
  539. const storedRuleResultPair = this.storage.get(path);
  540. if (!storedRuleResultPair) return undefined;
  541. const {
  542. rules: storedRules,
  543. result
  544. } = storedRuleResultPair;
  545. const isValidCache = this.checkRulesValidity(path, rules, storedRules);
  546. const $unwatch = result.$unwatch ? result.$unwatch : () => ({});
  547. if (!isValidCache) return {
  548. $dirty: result.$dirty,
  549. $partial: true,
  550. $unwatch
  551. };
  552. return result;
  553. }
  554. }
  555. const CollectFlag = {
  556. COLLECT_ALL: true,
  557. COLLECT_NONE: false
  558. };
  559. const VuelidateInjectChildResults = Symbol('vuelidate#injectChildResults');
  560. const VuelidateRemoveChildResults = Symbol('vuelidate#removeChildResults');
  561. function nestedValidations(_ref) {
  562. let {
  563. $scope,
  564. instance
  565. } = _ref;
  566. const childResultsRaw = {};
  567. const childResultsKeys = ref([]);
  568. const childResults = computed(() => childResultsKeys.value.reduce((results, key) => {
  569. results[key] = unref(childResultsRaw[key]);
  570. return results;
  571. }, {}));
  572. function injectChildResultsIntoParent(results, _ref2) {
  573. let {
  574. $registerAs: key,
  575. $scope: childScope,
  576. $stopPropagation
  577. } = _ref2;
  578. if ($stopPropagation || $scope === CollectFlag.COLLECT_NONE || childScope === CollectFlag.COLLECT_NONE || $scope !== CollectFlag.COLLECT_ALL && $scope !== childScope) return;
  579. childResultsRaw[key] = results;
  580. childResultsKeys.value.push(key);
  581. }
  582. instance.__vuelidateInjectInstances = [].concat(instance.__vuelidateInjectInstances || [], injectChildResultsIntoParent);
  583. function removeChildResultsFromParent(key) {
  584. childResultsKeys.value = childResultsKeys.value.filter(childKey => childKey !== key);
  585. delete childResultsRaw[key];
  586. }
  587. instance.__vuelidateRemoveInstances = [].concat(instance.__vuelidateRemoveInstances || [], removeChildResultsFromParent);
  588. const sendValidationResultsToParent = inject(VuelidateInjectChildResults, []);
  589. provide(VuelidateInjectChildResults, instance.__vuelidateInjectInstances);
  590. const removeValidationResultsFromParent = inject(VuelidateRemoveChildResults, []);
  591. provide(VuelidateRemoveChildResults, instance.__vuelidateRemoveInstances);
  592. return {
  593. childResults,
  594. sendValidationResultsToParent,
  595. removeValidationResultsFromParent
  596. };
  597. }
  598. function ComputedProxyFactory(target) {
  599. return new Proxy(target, {
  600. get(target, prop) {
  601. return typeof target[prop] === 'object' ? ComputedProxyFactory(target[prop]) : computed(() => target[prop]);
  602. }
  603. });
  604. }
  605. let uid = 0;
  606. function useVuelidate(validations, state) {
  607. var _getCurrentInstance;
  608. let globalConfig = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  609. if (arguments.length === 1) {
  610. globalConfig = validations;
  611. validations = undefined;
  612. state = undefined;
  613. }
  614. let {
  615. $registerAs,
  616. $scope = CollectFlag.COLLECT_ALL,
  617. $stopPropagation,
  618. $externalResults,
  619. currentVueInstance
  620. } = globalConfig;
  621. const instance = currentVueInstance || ((_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy);
  622. const componentOptions = instance ? instance.$options : {};
  623. if (!$registerAs) {
  624. uid += 1;
  625. $registerAs = `_vuelidate_${uid}`;
  626. }
  627. const validationResults = ref({});
  628. const resultsCache = new ResultsStorage();
  629. const {
  630. childResults,
  631. sendValidationResultsToParent,
  632. removeValidationResultsFromParent
  633. } = instance ? nestedValidations({
  634. $scope,
  635. instance
  636. }) : {
  637. childResults: ref({})
  638. };
  639. if (!validations && componentOptions.validations) {
  640. const rules = componentOptions.validations;
  641. state = ref({});
  642. onBeforeMount(() => {
  643. state.value = instance;
  644. watch(() => isFunction(rules) ? rules.call(state.value, new ComputedProxyFactory(state.value)) : rules, validations => {
  645. validationResults.value = setValidations({
  646. validations,
  647. state,
  648. childResults,
  649. resultsCache,
  650. globalConfig,
  651. instance,
  652. externalResults: $externalResults || instance.vuelidateExternalResults
  653. });
  654. }, {
  655. immediate: true
  656. });
  657. });
  658. globalConfig = componentOptions.validationsConfig || globalConfig;
  659. } else {
  660. const validationsWatchTarget = isRef(validations) || isProxy(validations) ? validations : reactive(validations || {});
  661. watch(validationsWatchTarget, newValidationRules => {
  662. validationResults.value = setValidations({
  663. validations: newValidationRules,
  664. state,
  665. childResults,
  666. resultsCache,
  667. globalConfig,
  668. instance: instance !== null && instance !== void 0 ? instance : {},
  669. externalResults: $externalResults
  670. });
  671. }, {
  672. immediate: true
  673. });
  674. }
  675. if (instance) {
  676. sendValidationResultsToParent.forEach(f => f(validationResults, {
  677. $registerAs,
  678. $scope,
  679. $stopPropagation
  680. }));
  681. onBeforeUnmount(() => removeValidationResultsFromParent.forEach(f => f($registerAs)));
  682. }
  683. return computed(() => {
  684. return _objectSpread2(_objectSpread2({}, unref(validationResults.value)), childResults.value);
  685. });
  686. }
  687. export { CollectFlag, useVuelidate as default, useVuelidate };