index.cjs 23 KB

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