jsfe 1.102.1 → 1.104.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.
@@ -1 +1 @@
1
- {"version":3,"file":"address-flows.d.ts","sourceRoot":"","sources":["../../src/forms/address-flows.js"],"names":[],"mappings":"AAiDA,0BAAmF"}
1
+ {"version":3,"file":"address-flows.d.ts","sourceRoot":"","sources":["../../src/forms/address-flows.js"],"names":[],"mappings":"AA+EA,0BAA0H"}
@@ -1,6 +1,6 @@
1
1
  /** Shared geocoded mailing-address collector over host-provided geocode tools. */
2
2
  import { defineForm, defineWorker } from './contracts.js';
3
- import { addressDraft, zipLocation, cityChoices, streetLocation, resolvedAddress } from '../helpers/address.js';
3
+ import { addressDraft, zipLocation, cityChoices, streetLocation, resolvedAddress, listedPlace, addressLine, addressVerdict, streetCheck, checkDeclined, unitQuestion, unitPrecheck, unitResult, unitsGiven, streetAccepted } from '../helpers/address.js';
4
4
  const S = (id, variable, value) => ({ id, type: 'SET', variable, value });
5
5
  const F = (id, value, parameters = {}, callType = 'call') => ({ id, type: 'FLOW', value, parameters, callType });
6
6
  const W = (id, condition, step) => ({ id, type: 'CASE', branches: { ['condition: ' + condition]: step, default: S(id + '_skip', 'noop', 'true') } });
@@ -8,34 +8,64 @@ const V = o => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, { type:
8
8
  const E = (fn, ...args) => `(${fn.toString()})(${args.join(',')})`;
9
9
  const P = (name, type = 'string') => ({ name, type, description: name });
10
10
  const C = (id, summary, steps, extra = {}) => defineWorker({ id, name: id.split('-').map(w => w[0].toUpperCase() + w.slice(1)).join(''), description: summary, ...extra, contract: { role: 'worker', summary, ...extra.contract }, steps });
11
+ // The unit question once Google says the building has units (owner 2026-12-05); a card left blank comes back with it.
12
+ const BUILDING = JSON.stringify({ en: 'This building has apartments. What is the apartment number?', es: 'Este edificio tiene apartamentos. ¿Cuál es el número de apartamento?' });
11
13
  const streetPattern = '\\b\\d{1,6}\\s+(?:[A-Za-z0-9.\\xC0-\\xFF-]+\\s+){1,8}(?:st(?:reet)?|ave(?:nue)?|blvd|boulevard|rd|road|ln|lane|dr(?:ive)?|way|ct|court|pl(?:ace)?|pkwy|parkway|cir(?:cle)?|ter(?:race)?)\\b';
12
- const address = defineForm({ id: 'collect-geocoded-address', name: 'CollectGeocodedAddress', version: '1.1.0', description: 'Collect a mailing address in any order, project geocoder evidence, and read the complete address back for confirmation.', contract: { summary: 'Collect and confirm a geocoded mailing address', result: { path: 'form result.resolved', type: 'object' } }, parameters: [P('given')], extraVars: { given: '', zip: '', street: '', unit: '', draft: null, address_result: null, address_spec: null, address_label: 'new address', address_label_es: 'nueva dirección', exit_context: 'your address', exit_context_es: 'su dirección' },
13
- before: [S('address_given', 'given', "given || (cargo.forms[cargo.forms[form_instance].parent] || {}).context && (cargo.forms[cargo.forms[form_instance].parent].context.given || '') || ''"), S('address_draft', 'draft', E(addressDraft, "given || (cargo.forms[form_instance].seeds && cargo.forms[form_instance].seeds.given) || ''")), S('address_seed_zip', 'zip', "zip || draft.zip"), S('address_seed_street', 'street', "street || draft.street"), S('address_seed_unit', 'unit', "unit || draft.unit"), S('address_data', 'noop', "(cargo.forms[form_instance].data=Object.assign({need_city:false},cargo.forms[form_instance].data || {}), draft.street ? (cargo.addressDraft={said:draft.street}) : null, true)"),
14
+ const address = defineForm({ id: 'collect-geocoded-address', name: 'CollectGeocodedAddress', version: '1.2.0', description: 'Collect a mailing address in any order, project geocoder evidence, check it with Google Address Validation, and read the complete address back for confirmation.', contract: { summary: 'Collect and confirm a geocoded mailing address', result: { path: 'form result.resolved', type: 'object' } }, parameters: [P('given')], validator: 'address-form-validate', extraVars: { given: '', zip: '', street: '', unit: '', draft: null, address_result: null, address_spec: null, address_label: 'new address', address_label_es: 'nueva dirección', exit_context: 'your address', exit_context_es: 'su dirección' },
15
+ before: [S('address_given', 'given', "given || (cargo.forms[cargo.forms[form_instance].parent] || {}).context && (cargo.forms[cargo.forms[form_instance].parent].context.given || '') || ''"), S('address_draft', 'draft', E(addressDraft, "given || (cargo.forms[form_instance].seeds && cargo.forms[form_instance].seeds.given) || ''")), S('address_seed_zip', 'zip', "zip || draft.zip"), S('address_seed_street', 'street', "street || draft.street"), S('address_seed_unit', 'unit', "unit || draft.unit"), S('address_data', 'noop', "(cargo.forms[form_instance].data=Object.assign({need_city:false,city_ask:'yes'},cargo.forms[form_instance].data || {}), draft.street ? (cargo.addressDraft={said:draft.street}) : null, true)"),
14
16
  // The calling form's own label for this input names what is being changed ("new delivery address") in every question and the read-back;
15
17
  // without one, today's wording.
16
- S('address_spec', 'address_spec', "(function(f){var p=f&&f.parent?cargo.forms[f.parent]:null,s=p&&p.specs,n=f&&f.result_input,x=null;if(n&&Array.isArray(s)){for(var i=0;i<s.length;i++){if(s[i]&&s[i].name===n){x=s[i];break;}}}else if(n&&s&&typeof s==='object'){x=s[n]||null;}return x||{};})(cargo.forms[form_instance])"), S('address_label', 'address_label', "typeof address_spec.label==='string'&&address_spec.label.trim()?address_spec.label.trim():'new address'"), S('address_label_es', 'address_label_es', "typeof address_spec.label_es==='string'&&address_spec.label_es.trim()?address_spec.label_es.trim():'nueva dirección'"), S('address_label_data', 'noop', "(function(d,labelled){d.label=address_label;d.label_es=address_label_es;d.labelled=labelled;d.city_state_question=labelled?'What city and state is your '+address_label+' in?':'What city and state is that in?';d.city_state_question_es=labelled?'¿En qué ciudad y estado está su '+address_label_es+'?':'¿En qué ciudad y estado está?';d.unit_question=labelled?'Is there an apartment or unit number in your '+address_label+'? '+channelVerb('en',cargo,true)+' the number, or NONE.':'Is there an apartment or unit number? '+channelVerb('en',cargo,true)+' the number, or NONE.';d.unit_question_es=labelled?'¿Hay un número de apartamento o unidad en su '+address_label_es+'? '+channelVerb('es',cargo,true)+' el número, o NINGUNO.':'¿Hay un número de apartamento o unidad? '+channelVerb('es',cargo,true)+' el número, o NINGUNO.';return true;})(cargo.forms[form_instance].data,typeof address_spec.label==='string'&&!!address_spec.label.trim())")],
18
+ S('address_spec', 'address_spec', "(function(f){var p=f&&f.parent?cargo.forms[f.parent]:null,s=p&&p.specs,n=f&&f.result_input,x=null;if(n&&Array.isArray(s)){for(var i=0;i<s.length;i++){if(s[i]&&s[i].name===n){x=s[i];break;}}}else if(n&&s&&typeof s==='object'){x=s[n]||null;}return x||{};})(cargo.forms[form_instance])"), S('address_label', 'address_label', "typeof address_spec.label==='string'&&address_spec.label.trim()?address_spec.label.trim():'new address'"), S('address_label_es', 'address_label_es', "typeof address_spec.label_es==='string'&&address_spec.label_es.trim()?address_spec.label_es.trim():'nueva dirección'"), S('address_label_data', 'noop', "(function(d,labelled){d.label=address_label;d.label_es=address_label_es;d.labelled=labelled;d.city_state_question=labelled?'What city and state is your '+address_label+' in?':'What city and state is that in?';d.city_state_question_es=labelled?'¿En qué ciudad y estado está su '+address_label_es+'?':'¿En qué ciudad y estado está?';d.unit_question=labelled?'Is there an apartment or unit number in your '+address_label+'? '+channelVerb('en',cargo,true)+' the number, or NONE.':'Is there an apartment or unit number? '+channelVerb('en',cargo,true)+' the number, or NONE.';d.unit_question_es=labelled?'¿Hay un número de apartamento o unidad en su '+address_label_es+'? '+channelVerb('es',cargo,true)+' el número, o NINGUNO.':'¿Hay un número de apartamento o unidad? '+channelVerb('es',cargo,true)+' el número, o NINGUNO.';return true;})(cargo.forms[form_instance].data,typeof address_spec.label==='string'&&!!address_spec.label.trim())"), S('address_unit_question', 'noop', ("(cargo.forms[form_instance].data.unit_question_plain=undefined," + E(unitQuestion, 'cargo.forms[form_instance].data', BUILDING) + ')'))],
17
19
  inputs: [{ name: 'zip', field: 'zip', argument_description: '5-digit ZIP code', names: ['zip', 'zip code', 'postal code', 'código postal', 'codigo postal'], validator: 'address-zip-validate', prepare: 'address-zip-prompt', question_from: 'zip_question', question: 'What is the 5-digit zip code of your new address?', question_es: '¿Cuál es el código postal de 5 dígitos de su nueva dirección?', form_client: { control: 'postal', regions: ['us'], fills: { city: 'locality' }, autofill: 'postal-code' } },
18
- { name: 'city', argument_description: 'city name alone', label: 'city', label_es: 'ciudad', names: ['city', 'ciudad'], profile: { kind: 'choice', choices: [], accept_other: true, other_needs_letter: true }, choices_from: 'city_choices', when: { 'form.data.city_known': true }, depends_on: ['zip'], reset_on: ['zip'], prepare: 'address-city-prompt', question_from: 'city_question', question: 'Which city is it?', question_es: '¿Qué ciudad es?', form_client: { control: 'combobox', autofill: 'address-level2' } },
20
+ { name: 'city', argument_description: 'city name alone', label: 'city', label_es: 'ciudad', names: ['city', 'ciudad'], profile: { kind: 'choice', choices: [], accept_other: true, other_needs_letter: true }, choices_from: 'city_choices', validator: 'address-city-validate', when: { 'form.data.city_known': true }, required_when: { 'form.data.city_ask': 'yes' }, depends_on: ['zip'], reset_on: ['zip'], prepare: 'address-city-prompt', question_from: 'city_question', question: 'Which city is it?', question_es: '¿Qué ciudad es?', form_client: { control: 'combobox', autofill: 'address-level2' } },
19
21
  { name: 'city_state', argument_description: 'city and state', label: 'city and state', label_es: 'ciudad y estado', names: ['city', 'ciudad'], profile: { kind: 'text' }, when: { 'form.data.need_city': true }, depends_on: ['zip'], question_from: 'city_state_question', question: 'What city and state is that in?', question_es: '¿En qué ciudad y estado está?' },
20
- { name: 'street', argument_description: 'street number and street name, without the apartment', label: 'street address', label_es: 'dirección', names: ['street', 'calle'], profile: { kind: 'pattern', regex: streetPattern, spoken_digits: 'house_number', accept_other: true }, depends_on: ['zip'], validator: 'address-street-validate', prepare: 'address-street-prompt', question_from: 'street_question', question: 'What is the street address?', question_es: '¿Cuál es la dirección?', form_client: { control: 'place', types: 'address', regions: ['us'], fills: { zip: 'postal_code', city: 'locality' }, autofill: 'address-line1' } },
21
- { name: 'unit', declinable: true, argument_description: 'apartment or unit number alone, such as 4 or 12B', reset_on: ['street'], label: 'apartment or unit', label_es: 'apartamento o unidad', names: ['apartment', 'apt', 'unit', 'apartamento', 'unidad', 'departamento'], profile: { kind: 'pattern', regex: '(?:\\bapartment|\\bapartamento|\\bdepartamento|\\bapt\\.?|\\bunit|\\bunidad|#)\\s*([\\w-]+)', group: 1, spoken_digits: true, accept_other: true }, question_from: 'unit_question', question: 'Is there an apartment or unit number? {{channelVerb(\'en\', cargo, true)}} the number, or NONE.', question_es: '¿Hay un número de apartamento o unidad? {{channelVerb(\'es\', cargo, true)}} el número, o NINGUNO.', form_client: { autofill: 'address-line2' } }],
22
+ { name: 'street', argument_description: 'street number and street name, without the apartment', label: 'street address', label_es: 'dirección', names: ['street', 'calle'], profile: { kind: 'pattern', regex: streetPattern, spoken_digits: 'house_number', accept_other: true }, depends_on: ['zip'], validator: 'address-street-validate', after: 'address-street-accepted', prepare: 'address-street-prompt', question_from: 'street_question', question: 'What is the street address?', question_es: '¿Cuál es la dirección?', form_client: { control: 'place', types: 'address', regions: ['us'], fills: { zip: 'postal_code', city: 'locality' }, autofill: 'address-line1' } },
23
+ { name: 'unit', declinable: true, validator: 'address-unit-validate', argument_description: 'apartment or unit number alone, such as 4 or 12B', depends_on: ['street'], reset_on: ['street'], label: 'apartment or unit', label_es: 'apartamento o unidad', names: ['apartment', 'apt', 'unit', 'apartamento', 'unidad', 'departamento'], profile: { kind: 'pattern', regex: '(?:\\bapartment|\\bapartamento|\\bdepartamento|\\bapt\\.?|\\bunit|\\bunidad|#)\\s*([\\w-]+)', group: 1, spoken_digits: true, accept_other: true }, question_from: 'unit_question', question: 'Is there an apartment or unit number? {{channelVerb(\'en\', cargo, true)}} the number, or NONE.', question_es: '¿Hay un número de apartamento o unidad? {{channelVerb(\'es\', cargo, true)}} el número, o NINGUNO.', form_client: { autofill: 'address-line2' } }],
22
24
  before_confirm: [S('address_resolved', 'address_result', E(resolvedAddress, 'cargo.forms[form_instance].values', 'cargo.forms[form_instance].data'))],
23
25
  confirm: { named_fields: true, reply_context: 'This is a mailing address read back for confirmation. A reply may correct one part or several at once: the street number, street name or street type, the apartment or unit, the city, or the ZIP code.', no_keys: ['2', 'not right', 'not correct', 'incorrect', 'wrong', 'no es correcto', 'no es correcta', 'incorrecta'], question: "Your {{address_label}} is {{address_result.line}}. Is that correct? {{yesNoKeys('en', cargo)}}", question_es: "Su {{address_label_es}} es {{address_result.line}}. ¿Es correcta? {{yesNoKeys('es', cargo)}}" },
24
26
  after: [S('address_result_store', 'noop', '(cargo.forms[form_instance].values.resolved = address_result, cargo.address = address_result, cargo.addressDraft = null, true)')], declined: [S('address_retry_noop', 'noop', 'true')] });
25
27
  const zip = C('address-zip-validate', 'Read city and state from geocoder evidence for the proposed ZIP; missing geocoder data requires an explicit city.', [
26
28
  S('address_zip_components', 'components', "'postal_code:'+value+'|country:US'"), { id: 'address_zip_tool', type: 'CALL-TOOL', tool: 'geocode-zip', variable: 'result', args: { components: '{{components}}', address: '' }, onFail: S('address_zip_failed', 'result', 'null') },
27
29
  S('address_zip_location', 'location', E(zipLocation, 'result')),
28
- S('address_zip_result', 'noop', "(cargo.forms[form].data=Object.assign({},cargo.forms[form].data,{location:location,need_city:!location,city_known:!!location,city_choice:!!(location&&location.cities.length),city_choices:" + E(cityChoices, 'location') + "}), location&&!location.cities.length&&cargo.forms[form].values.city===undefined?(cargo.forms[form].values.city=location.city,cargo.forms[form].accepted.city={origin:'derived',revision:cargo.forms[form].revision||0}):null, cargo.inputCheck={ok:true,value:String(value)}, true)")
30
+ S('address_zip_result', 'noop', "(cargo.forms[form].data=Object.assign({},cargo.forms[form].data,{location:location,need_city:!location,city_known:!!location,city_choice:!!(location&&location.cities.length),city_ask:location&&location.cities.length?'no':'yes',city_choices:" + E(cityChoices, 'location') + "}), location&&!location.cities.length&&cargo.forms[form].values.city===undefined?(cargo.forms[form].values.city=location.city,cargo.forms[form].accepted.city={origin:'derived',revision:cargo.forms[form].revision||0}):null, cargo.inputCheck={ok:true,value:String(value)}, true)")
29
31
  ], { parameters: [P('form'), P('value')], variables: V({ components: '', result: null, location: null }), contract: { tools: ['geocode-zip'], result: { path: 'cargo.inputCheck', type: 'object' } } });
30
32
  const street = C('address-street-validate', 'Validate a proposed street against its ZIP; retain unverified wording when geocoding is inconclusive.', [
31
33
  S('address_street_said', 'value', "joinSpokenDigits(String(value),'house_number')"),
32
34
  W('address_street_malformed', "!/^\\d{1,6}\\s+(?:\\d{1,3}\\s+)?[A-Za-z\\xC0-\\xFF]/.test(String(value))", S('address_street_invalid', 'noop', "(cargo.inputCheck={ok:false,message:'Please give the street number and street name.',message_es:'Indique el número y nombre de la calle.'},true)")), W('address_street_stop', "!/^\\d{1,6}\\s+(?:\\d{1,3}\\s+)?[A-Za-z\\xC0-\\xFF]/.test(String(value))", { id: 'address_street_invalid_end', type: 'END' }),
33
- S('address_street_components', 'components', "'postal_code:'+values.zip+'|country:US'"), { id: 'address_street_tool', type: 'CALL-TOOL', tool: 'geocode-street', variable: 'result', args: { address: '{{value}}', components: '{{components}}' }, onFail: S('address_street_failed', 'result', 'null') },
34
- S('address_street_projection', 'location', E(streetLocation, 'result', 'value', 'values.zip')),
35
- S('address_street_result', 'noop', "(cargo.forms[form].data.street=location, location.city&&cargo.forms[form].accepted&&cargo.forms[form].accepted.city&&cargo.forms[form].accepted.city.origin==='derived'&&cargo.forms[form].values.city!==location.city?(cargo.forms[form].values.city=location.city):null, cargo.inputCheck={ok:true,value:String(value)}, true)")
36
- ], { parameters: [P('form'), P('value'), P('values', 'object')], variables: V({ components: '', result: null, location: null }), contract: { tools: ['geocode-street'], result: { path: 'cargo.inputCheck', type: 'object' } } });
35
+ S('address_street_components', 'components', "'postal_code:'+values.zip+'|country:US'"), S('address_street_held', 'held', '!!(reading && reading.proposalResume && cargo.forms[form].data.check)'),
36
+ W('address_street_lookup', '!held', { id: 'address_street_tool', type: 'CALL-TOOL', tool: 'geocode-street', variable: 'result', args: { address: '{{value}}', components: '{{components}}' }, onFail: S('address_street_failed', 'result', 'null') }),
37
+ W('address_street_located', '!held', S('address_street_projection', 'location', E(streetLocation, 'result', 'value', 'values.zip'))),
38
+ W('address_street_derive', '!held', S('address_street_result', 'noop', "(cargo.forms[form].data.street=location, location.city&&cargo.forms[form].accepted&&cargo.forms[form].accepted.city&&cargo.forms[form].accepted.city.origin==='derived'&&cargo.forms[form].values.city!==location.city?(cargo.forms[form].values.city=location.city):null, true)")),
39
+ // The whole address, checked once by Google Address Validation (owner 2026-12-05). Its failure leaves the form as before.
40
+ S('address_street_line', 'line', E(addressLine, 'value', "''", 'Object.assign({},cargo.forms[form].values,values)', 'cargo.forms[form].data')),
41
+ W('address_street_check', '!held', { id: 'address_street_validate', type: 'CALL-TOOL', tool: 'validate-address', variable: 'checked', args: { address: '{{line}}', previous_response_id: '' }, onFail: S('address_street_check_failed', 'checked', 'null') }),
42
+ S('address_street_verdict', 'verdict', E(addressVerdict, 'checked', 'value')),
43
+ S('address_street_checked', 'noop', '(cargo.inputCheck=' + E(streetCheck, 'cargo.forms[form]', 'values', 'verdict', 'value', 'reading', "({en:yesNoKeys('en',cargo),es:yesNoKeys('es',cargo)})") + ', true)'),
44
+ S('address_street_unit_question', 'noop', E(unitQuestion, 'cargo.forms[form].data', BUILDING))
45
+ ], { parameters: [P('form'), P('value'), P('values', 'object'), P('reading', 'object')], variables: V({ components: '', result: null, location: null, held: false, line: '', checked: null, verdict: null }), contract: { tools: ['geocode-street', 'validate-address'], result: { path: 'cargo.inputCheck', type: 'object' } } });
46
+ // A ZIP code with several place names: the city is one of them (accents, case and edge punctuation folded), never other text.
47
+ const city = C('address-city-validate', 'Match a city to the ZIP code\'s listed place names; any city when the ZIP code lists none.', [
48
+ S('address_city_check', 'noop', "(function(choices,listed){cargo.inputCheck=!choices.length?{ok:true,value:String(value)}:listed?{ok:true,value:listed}:{ok:false,quiet:true};return true;})(cargo.forms[form].data.city_choices || []," + E(listedPlace, 'value', 'cargo.forms[form].data.city_choices') + ")")
49
+ ], { parameters: [P('form'), P('value')], contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
50
+ // A unit answer holds a unit number or letter; with Google, the address is checked again with it.
51
+ const unit = C('address-unit-validate', 'Refuse a unit answer that is not a unit; check the address with its unit when Google checked the street.', [
52
+ S('address_unit_pre', 'pre', E(unitPrecheck, 'cargo.forms[form].data', 'value')),
53
+ S('address_unit_line', 'line', "pre.check ? " + E(addressLine, 'cargo.forms[form].data.check_street', 'pre.unit', 'Object.assign({},cargo.forms[form].values,values)', 'cargo.forms[form].data') + " : ''"),
54
+ S('address_unit_rid', 'rid', "String(cargo.forms[form].data.check_rid || '')"),
55
+ W('address_unit_check', 'pre.check === true', { id: 'address_unit_validate', type: 'CALL-TOOL', tool: 'validate-address', variable: 'checked', args: { address: '{{line}}', previous_response_id: '{{rid}}' }, onFail: S('address_unit_check_failed', 'checked', 'null') }),
56
+ S('address_unit_result', 'noop', '(cargo.inputCheck=' + E(unitResult, 'cargo.forms[form].data', 'pre', 'checked') + ', true)')
57
+ ], { parameters: [P('form'), P('value'), P('values', 'object')], variables: V({ pre: null, line: '', rid: '', checked: null }), contract: { tools: ['validate-address'], result: { path: 'cargo.inputCheck', type: 'object' } } });
58
+ const formCheck = C('address-form-validate', 'The whole address: a card that left the unit blank on a building with units is asked it once.', [
59
+ S('address_form_check', 'noop', '(cargo.formCheck=' + E(unitsGiven, 'cargo.forms[form]') + ', true)')
60
+ ], { parameters: [P('form'), P('values', 'object')], contract: { result: { path: 'cargo.formCheck', type: 'object' } } });
61
+ const streetDone = C('address-street-accepted', 'After the street: the city Google named fills a missing city; otherwise the city is asked.', [
62
+ S('address_street_accepted', 'noop', E(streetAccepted, 'cargo.forms[form]'))
63
+ ], { parameters: [P('form'), P('input'), P('value')] });
64
+ const checkNo = C('address-check-declined', 'NO to Google\'s version of the address: ask that part again once; the next answer is kept as given.', [
65
+ S('address_check_declined', 'noop', E(checkDeclined, 'cargo', 'form', 'acceptFormReadings', 'resetFormInputs'))
66
+ ], { parameters: [P('form'), P('input'), P('value'), P('reading', 'object')] });
37
67
  const zipPrompt = C('address-zip-prompt', 'Render the ZIP question from the owned address instance, naming the calling form\'s label.', [S('address_zip_prompt', 'noop', "(cargo.forms[form].data.zip_question=(cargo.forms[form].data.retry ? \"Let's try again. \" : '')+'What is the 5-digit zip code of your '+(cargo.forms[form].data.label||'new address')+'?',cargo.forms[form].data.zip_question_es=(cargo.forms[form].data.retry?'Intentémoslo otra vez. ':'')+'¿Cuál es el código postal de 5 dígitos de su '+(cargo.forms[form].data.label_es||'nueva dirección')+'?',true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
38
- const streetPrompt = C('address-street-prompt', 'Include the ZIP-derived location when asking for the street.', [S('address_street_prompt', 'noop', "(cargo.forms[form].data.street_question=(cargo.forms[form].data.location?'Got it, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'What is the street of your '+cargo.forms[form].data.label+'?':'What is the street address?'),cargo.forms[form].data.street_question_es=(cargo.forms[form].data.location?'Entendido, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'¿Cuál es la calle de su '+cargo.forms[form].data.label_es+'?':'¿Cuál es la dirección?'),true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
68
+ const streetPrompt = C('address-street-prompt', 'Include the ZIP-derived location when asking for the street.', [S('address_street_prompt', 'noop', "(cargo.forms[form].data.street_question=(cargo.forms[form].data.city_choice&&!cargo.forms[form].values.city?'Got it. ':cargo.forms[form].data.location?'Got it, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'What is the street of your '+cargo.forms[form].data.label+'?':'What is the street address?'),cargo.forms[form].data.street_question_es=(cargo.forms[form].data.city_choice&&!cargo.forms[form].values.city?'Entendido. ':cargo.forms[form].data.location?'Entendido, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'¿Cuál es la calle de su '+cargo.forms[form].data.label_es+'?':'¿Cuál es la dirección?'),true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
39
69
  const cityPrompt = C('address-city-prompt', 'Ask which of the ZIP code\'s place names the address carries.', [S('address_city_prompt', 'noop', "(function(data,voice){var names=(data.location&&data.location.cities)||[],n=names.length,list=function(and){return names.slice(0,-1).join(', ')+' '+and+' '+names[n-1];};if(n<2){data.city_question=data.labelled?'What city is your '+data.label+' in?':'What city is it?';data.city_question_es=data.labelled?'¿En qué ciudad está su '+data.label_es+'?':'¿Qué ciudad es?';return true;}data.city_question=(data.labelled?'Which city is your '+data.label+' in: ':'Which city is it: ')+list('or')+'? '+(voice?names.map(function(c,i){return (i?'':'Press ')+(i+1)+' for '+c;}).join(', ')+'.':'Type the city or its number, 1 to '+n+'.');data.city_question_es=(data.labelled?'¿En qué ciudad está su '+data.label_es+': ':'¿Qué ciudad es: ')+list('o')+'? '+(voice?names.map(function(c,i){return (i?'':'Presione ')+(i+1)+' para '+c;}).join(', ')+'.':'Escriba la ciudad o su número, del 1 al '+n+'.');return true;})(cargo.forms[form].data,cargo.voice===true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
40
70
  // NO at the read-back asks which part is wrong and re-asks only that part; ALL starts over.
41
71
  const PARTS = [{ key: 'zip', label: 'ZIP code', label_es: 'Código postal', phrases: ['1', 'zip', 'zip code', 'postal code', 'código postal', 'codigo postal'] }, { key: 'city', label: 'City', label_es: 'Ciudad', phrases: ['2', 'city', 'ciudad'] }, { key: 'street', label: 'Street', label_es: 'Calle', phrases: ['3', 'street', 'calle'] }, { key: 'unit', label: 'Apartment', label_es: 'Apartamento', phrases: ['4', 'apartment', 'apt', 'unit', 'apartamento', 'unidad', 'departamento'] }, { key: 'all', label: 'Everything', label_es: 'Todo', phrases: ['5', 'all', 'everything', 'all of it', 'todo', 'toda'] }];
@@ -44,7 +74,7 @@ const declined = C('collect-geocoded-address-declined', 'Ask which part of the d
44
74
  S('address_retry_part_q', 'part_question', "'Which part is wrong: 1 the zip code, 2 the city, 3 the street, or 4 the apartment? Or '+channelVerb('en',cargo)+' ALL to start over.'"), S('address_retry_part_q_es', 'part_question_es', "'¿Qué parte está mal: 1 el código postal, 2 la ciudad, 3 la calle, o 4 el apartamento? O '+channelVerb('es',cargo)+' TODO para empezar de nuevo.'"),
45
75
  F('address_retry_part_ask', 'ask-choice', { question: '{{part_question}}', question_es: '{{part_question_es}}', choices: '{{parts}}', rank: 'insist' }),
46
76
  S('address_retry_part', 'part', "['zip','city','street','unit','all'].indexOf(cargo.choice)>=0 ? cargo.choice : 'all'"),
47
- S('address_retry_clear', 'noop', "(part==='all' ? (resetFormInputs(cargo,form_instance,['zip','city','city_state','street','unit']),cargo.forms[form_instance].data={retry:true,need_city:false}) : resetFormInputs(cargo,form_instance,[part==='city' ? (cargo.forms[form_instance].data.city_choice ? 'city' : 'city_state') : part]),true)"),
77
+ S('address_retry_clear', 'noop', "(part==='all' ? (resetFormInputs(cargo,form_instance,['zip','city','city_state','street','unit']),cargo.forms[form_instance].data={retry:true,need_city:false}) : resetFormInputs(cargo,form_instance,[part==='city' ? (cargo.forms[form_instance].data.city_choice ? 'city' : 'city_state') : part]),part!=='city' && part!=='unit' ? (cargo.forms[form_instance].data.check_declined=false,cargo.forms[form_instance].data.unit_retry=false) : null,true)"),
48
78
  F('address_retry', 'collect-geocoded-address', { form_instance: '{{form_instance}}', parent_form: '{{parent_form}}', result_input: '{{result_input}}' }, 'replace')
49
79
  ], { parameters: [P('form_instance')], variables: V({ parent_form: '', result_input: '', part: '', parts: PARTS, part_question: '', part_question_es: '' }) });
50
- export const FLOWS = [address, zip, street, zipPrompt, cityPrompt, streetPrompt, declined];
80
+ export const FLOWS = [address, zip, street, streetDone, city, unit, formCheck, checkNo, zipPrompt, cityPrompt, streetPrompt, declined];
@@ -1 +1 @@
1
- {"version":3,"file":"identity-flows.d.ts","sourceRoot":"","sources":["../../src/forms/identity-flows.js"],"names":[],"mappings":"AAkDA,+GAA+G;AAC/G,oFAOC;AAQD,wFAAwF;AACxF,iDAGC;AACD,0CAYC;AACD,qHAQC;AASD,qHAAqH;AACrH,6FAKC;AACD,4EAYC;AAED;;kGAEkG;AAClG,0FASC;AAED;kIACkI;AAClI;;;;SAUC;AAiID,2DAOC;AACD,4DAOC;AACD,gHAAgH;AAChH,8DAGC;AAmKD,8EAGC;AAgCD,4FAA4F;AAC5F;;;;EAOC;AAYD,oGAOC;AAnRD,iCAAgC,wIAAwI,CAAC;AACzK,wCAAuC,CAAC,CAAC;AAsSzC,0BAAsK"}
1
+ {"version":3,"file":"identity-flows.d.ts","sourceRoot":"","sources":["../../src/forms/identity-flows.js"],"names":[],"mappings":"AAkDA,+GAA+G;AAC/G,oFAOC;AAQD,wFAAwF;AACxF,iDAGC;AACD,0CAYC;AACD,qHAQC;AASD,qHAAqH;AACrH,6FAKC;AACD,4EAYC;AAED;;kGAEkG;AAClG,0FASC;AAED;kIACkI;AAClI;;;;SAUC;AAiID,2DAOC;AACD,4DAOC;AACD,gHAAgH;AAChH,8DAGC;AAyKD,8EAGC;AAgCD,4FAA4F;AAC5F;;;;EAOC;AAYD,oGAOC;AAzRD,iCAAgC,wIAAwI,CAAC;AACzK,wCAAuC,CAAC,CAAC;AA4SzC,0BAAsK"}
@@ -378,17 +378,23 @@ function otpPhoneUnavailable(value) {
378
378
  // offered only where the step offers them (a code sent by text; a caller-ID preselection).
379
379
  const OTP_REPLY_CHOICES = [{ key: 'email', label: 'use the email on the account instead of the phone' }, { key: 'another_account', label: 'use another account' }, { key: 'no_other_account', label: 'says they have no other account, this is their only one' },
380
380
  { key: 'where', label: 'asks where the code was sent' }, { key: 'cannot_find', label: 'looked for the code and cannot find or see it' }, { key: 'another_way', label: 'asks for another way to get the code or to verify' }, { key: 'resend', label: 'says they have not received the code, or asks for it to be sent again' }, { key: 'has_code', label: 'has the code now or is getting it (here it is, one moment, let me look)' }, { key: 'no_phone', label: 'no longer has that phone or number' }, { key: '__agent', label: 'speak with a person (a live agent)' }];
381
- const validateCode = worker('validate-otp-code', 'ValidateOtpCode', 'Validate a challenge response with explicit bounded retries, alternate-contact handling and tenant callbacks.', { loopBound: '3 mismatches, 3 format misses, 2 resends, 3 sends per contact', variables: vars({ otp_phrases: OTP_WORDS, email_too: false, no_code_given: false, wants_other_account: false, other_account_given: false, otp_validation_result: false, whatsapp_invite_sent: false, invite_text: '', otp_cancel: 'contact-support', answer_key: '', answer_value: '', otp_reply_choices: OTP_REPLY_CHOICES, otp_offers: [], otp_reply: {}, otp_where: '', otp_where_es: '' }), contract: { role: 'gate', summary: 'Validate the active one-time challenge', tools: ['validate-otp', 'send-whatsapp-invite'], result: { path: 'cargo.otpVerified', type: 'boolean' } }, steps: [
381
+ const validateCode = worker('validate-otp-code', 'ValidateOtpCode', 'Validate a challenge response with explicit bounded retries, alternate-contact handling and tenant callbacks.', { loopBound: '3 mismatches, 3 format misses, 2 resends, 3 sends per contact', variables: vars({ otp_phrases: OTP_WORDS, email_too: false, no_code_given: false, wants_other_account: false, other_account_given: false, otp_validation_result: false, whatsapp_invite_sent: false, invite_text: '', otp_cancel: 'contact-support', answer_key: '', answer_value: '', otp_reply_choices: OTP_REPLY_CHOICES, otp_offers: [], otp_reply: {}, otp_where: '', otp_where_es: '', otp_last_six: '', otp_last_six_ok: false }), contract: { role: 'gate', summary: 'Validate the active one-time challenge', tools: ['validate-otp', 'send-whatsapp-invite'], result: { path: 'cargo.otpVerified', type: 'boolean' } }, steps: [
382
382
  set('otp_cancel', 'otp_cancel', "cargo.authCancelFlow || 'contact-support'"),
383
383
  set('otp_email_too_ready', 'email_too', "!!(cargo.otp_cell_number && cargo.otpAltSent !== true && cargo.otpAltSent !== 'failed' && validateEmail(String(cargo.otpAltEmail || '')))"),
384
384
  set('otp_reset_no_code', 'no_code_given', 'false'), set('otp_reset_invite', 'whatsapp_invite_sent', 'false'), set('otp_reset_callback', 'answer_key', "''"),
385
- when('otp_tenant_code', 'cargo.authOptions && cargo.authOptions.code_validator && String(user_choice).replace(/\\D/g,\'\').length !== 6 && /[0-9]/.test(user_choice)', call('otp_tenant_code_call', '{{cargo.authOptions.code_validator}}', { answer: '{{user_choice}}' })),
385
+ // Seven or eight digits: the last six are tried as the code before the tenant reads the digits (owner 2026-12-05; prod
386
+ // 12-04 'Código 5 5 3 2 4 2 4' was looked up as an account and a stranger got a code). A match verifies; a miss goes on as before.
387
+ set('otp_last_six', 'otp_last_six', "/^\\d{7,8}$/.test(normalized_otp_code) ? normalized_otp_code.slice(-6) : ''"), set('otp_last_six_reset', 'otp_last_six_ok', 'false'),
388
+ when('otp_last_six_try', '!!otp_last_six', { id: 'otp_last_six_tool', type: 'CALL-TOOL', tool: 'validate-otp', variable: 'otp_last_six_ok', args: { otp: '{{otp_last_six}}', container: '{{cargo}}' }, onFail: set('otp_last_six_failed', 'otp_last_six_ok', 'false') }),
389
+ set('otp_last_six_code', 'normalized_otp_code', "otp_last_six_ok === true ? otp_last_six : normalized_otp_code"),
390
+ when('otp_tenant_code', 'cargo.authOptions && cargo.authOptions.code_validator && String(user_choice).replace(/\\D/g,\'\').length !== 6 && /[0-9]/.test(user_choice) && otp_last_six_ok !== true', call('otp_tenant_code_call', '{{cargo.authOptions.code_validator}}', { answer: '{{user_choice}}' })),
386
391
  set('otp_other_given', 'other_account_given', "answer_key === 'another_account' ? (cargo.authOtherAccount=String(answer_value || ''),true) : false"),
387
392
  set('otp_other_requested', 'wants_other_account', 'other_account_given || !!(cargo.callerPreselected && normalized_otp_code.length !== 6 && ((cargo.authOptions && cargo.authOptions.other_whole_answer ? pickChoice(user_choice,[{key:\'other\',phrases:otp_phrases.other,exact:true}],false) === \'other\' : matchesChoice(user_choice,otp_phrases.other)) || otp_phrases.other_alone.includes(user_choice.replace(/[.,!?¡¿]/g,\'\').trim())))'),
388
393
  when('otp_tenant_answer', 'cargo.authOptions && cargo.authOptions.answer_handler && normalized_otp_code.length !== 6 && !wants_other_account && answer_key !== \'code_notice\'', call('otp_tenant_answer_call', '{{cargo.authOptions.answer_handler}}', { answer: '{{user_choice}}' })),
389
394
  set('otp_where_early', 'otp_where', expression(otpWhere, 'cargo')), set('otp_where_early_es', 'otp_where_es', expression(otpWhere, 'cargo', 'true')),
390
395
  cases('otp_response', {
391
396
  // The tenant's reading of the digits comes first (owner 2026-11-18: a real account number is taken before a code is tried).
397
+ "condition: otp_last_six_ok === true": effect('otp_last_six_verified', 'true'),
392
398
  "condition: normalized_otp_code.length === 6 && answer_key !== 'another_account' && answer_key !== 'code_notice'": { id: 'otp_check_tool', type: 'CALL-TOOL', tool: 'validate-otp', variable: 'otp_validation_result', args: { otp: '{{normalized_otp_code}}', container: '{{cargo}}' }, onFail: call('otp_check_failed', 'get-and-validate-otp-code', undefined, 'replace') },
393
399
  'condition: wants_other_account': toParent(call('otp_change_account', 'authenticate-user', { cell_number: '', email: '', retrying: true, declined_caller: true }, 'replace')),
394
400
  // Email asked for at a code sent by text: authentication is an input step, so the contact question is asked again
@@ -17,13 +17,110 @@ export function streetLocation(result: any, said: any, zip: any): {
17
17
  verified: boolean;
18
18
  city: any;
19
19
  };
20
+ /** A place name as the caller gave it, matched to the listed name it means: accents, case and edge punctuation never
21
+ * distinguish two names ("Los Ángeles" is Los Angeles, "Highland." is Highland). '' when it is none of them. */
22
+ export function listedPlace(value: any, choices: any): string;
23
+ /** The whole address as one line for Google Address Validation: "street[ Apt unit], City, ST zip". */
24
+ export function addressLine(street: any, unit: any, values: any, data: any): string;
25
+ /** validate-address's answer reduced to what the form decides on; null when Google could not be asked or found nothing.
26
+ * The parts are the verdict, never next_action alone (measured: "501 Reading Way" came back "501 Read Street", ROUTE, ACCEPT).
27
+ * ask: 'street' (Google's street differs from the caller's: "Did you mean …?"), 'street_unconfirmed' (the same street, but
28
+ * Google could not place it at a premise), 'place' (Google replaced the city or ZIP code), else ''. */
29
+ export function addressVerdict(result: any, said: any): {
30
+ street: string;
31
+ city: string;
32
+ state: string;
33
+ zip: string;
34
+ formatted: string;
35
+ granularity: string;
36
+ verified: boolean;
37
+ ask: string;
38
+ city_replaced: boolean;
39
+ zip_replaced: boolean;
40
+ units_needed: any;
41
+ unit_confirmed: boolean;
42
+ response_id: string;
43
+ } | null;
44
+ /** The validate-address verdict applied to the street answer (the street validator's last step). Returns the validator's
45
+ * answer: a proposal to confirm Google's version first, or the street accepted. `keys` are the yes/no words for each language. */
46
+ export function streetCheck(state: any, values: any, verdict: any, value: any, reading: any, keys: any): {
47
+ ok: boolean;
48
+ value: string;
49
+ proposal: any;
50
+ } | {
51
+ ok: boolean;
52
+ value: string;
53
+ proposal?: undefined;
54
+ } | {
55
+ ok: boolean;
56
+ value: any;
57
+ proposal: {
58
+ question: string;
59
+ question_es: string;
60
+ on_declined: string;
61
+ };
62
+ };
63
+ /** NO to Google's version. A street is asked again (once: the next answer is kept as given). A city or ZIP code: the
64
+ * caller's street is kept, not verified, and the city or ZIP code is asked again. */
65
+ export function checkDeclined(cargo: any, form: any, accept: any, reset: any): boolean;
66
+ /** After the street is accepted: the city is asked when still missing, unless Google named one (a ZIP code with several
67
+ * place names asks none before the street). The read-back is the first place that city is said. */
68
+ export function streetAccepted(state: any): boolean;
69
+ /** The whole form's check: a card that left the unit blank on a building Google says has units comes back asking it,
70
+ * once (a NONE said to the question is an answer). */
71
+ export function unitsGiven(state: any): {
72
+ ok: boolean;
73
+ invalid: {
74
+ name: string;
75
+ }[];
76
+ } | {
77
+ ok: boolean;
78
+ invalid?: undefined;
79
+ };
80
+ /** The unit question: the building's own wording once Google says it has units, else the form's ordinary one. */
81
+ export function unitQuestion(data: any, building: any): boolean;
82
+ /** A unit answer, before Google is asked: a unit number or letter ("3036 E", "B", "F108", never a sentence or a word), and
83
+ * whether Google should check it (a "none" never reaches a validator). */
84
+ export function unitPrecheck(data: any, value: any): {
85
+ ok: boolean;
86
+ message: string;
87
+ message_es: string;
88
+ value?: undefined;
89
+ check?: undefined;
90
+ unit?: undefined;
91
+ } | {
92
+ ok: boolean;
93
+ value: string;
94
+ check: boolean;
95
+ unit: string;
96
+ message?: undefined;
97
+ message_es?: undefined;
98
+ } | {
99
+ ok: boolean;
100
+ value: string;
101
+ message?: undefined;
102
+ message_es?: undefined;
103
+ check?: undefined;
104
+ unit?: undefined;
105
+ };
106
+ /** Google's answer for the address with its unit: a unit it could not confirm is asked once more, then kept as given. */
107
+ export function unitResult(data: any, pre: any, checked: any): {
108
+ message?: any;
109
+ message_es?: any;
110
+ quiet?: boolean | undefined;
111
+ value?: any;
112
+ ok: any;
113
+ };
20
114
  export function resolvedAddress(values: any, data: any): {
21
115
  street: any;
22
116
  unit: string;
23
117
  city: any;
24
- zip: string;
118
+ zip: any;
25
119
  line: string;
26
120
  verified: boolean;
27
121
  said: any;
122
+ address_verified: boolean;
123
+ unit_verified: boolean;
124
+ formatted: any;
28
125
  };
29
126
  //# sourceMappingURL=address.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../src/helpers/address.js"],"names":[],"mappings":"AAEA;;;;;EAQC;AACD;;;;;SAWC;AACD,gDAEC;AACD;;;;;EASC;AACD;;;;;;;;EAIC"}
1
+ {"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../src/helpers/address.js"],"names":[],"mappings":"AAEA;;;;;EAQC;AACD;;;;;SAWC;AACD,gDAEC;AACD;;;;;EASC;AACD;gHACgH;AAChH,8DAIC;AACD,sGAAsG;AACtG,oFAKC;AACD;;;uGAGuG;AACvG;;;;;;;;;;;;;;SAeC;AACD;kIACkI;AAClI;;;;;;;;;;;;;;;;EAyCC;AACD;qFACqF;AACrF,uFASC;AACD;mGACmG;AACnG,oDAKC;AACD;sDACsD;AACtD;;;;;;;;EAIC;AACD,iHAAiH;AACjH,gEAIC;AACD;0EAC0E;AAC1E;;;;;;;;;;;;;;;;;;;;;EAKC;AACD,yHAAyH;AACzH;;;;;;EAUC;AACD;;;;;;;;;;;EAQC"}
@@ -35,8 +35,195 @@ export function streetLocation(result, said, zip) {
35
35
  const city = exact ? part('locality') || part('postal_town') || part('sublocality') || part('sublocality_level_1') || part('neighborhood') : '';
36
36
  return { street: exact ? part('street_number') + ' ' + part('route') : String(said).trim(), said: String(said).trim(), verified: !!exact, city };
37
37
  }
38
+ /** A place name as the caller gave it, matched to the listed name it means: accents, case and edge punctuation never
39
+ * distinguish two names ("Los Ángeles" is Los Angeles, "Highland." is Highland). '' when it is none of them. */
40
+ export function listedPlace(value, choices) {
41
+ const fold = s => String(s ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
42
+ const said = fold(value), hit = said ? (choices || []).find(c => fold(c.key) === said || fold(c.label) === said) : null;
43
+ return hit ? String(hit.key) : '';
44
+ }
45
+ /** The whole address as one line for Google Address Validation: "street[ Apt unit], City, ST zip". */
46
+ export function addressLine(street, unit, values, data) {
47
+ const u = String(unit ?? '').replace(/^(apt\.?|unit|#)\s*/i, '').trim(), state = data?.location?.state || '';
48
+ // a ZIP code with several place names and no city yet: the state alone, so Google names the city (never one of the list guessed)
49
+ const city = values?.city ? values.city + (state ? ', ' + state : '') : String(values?.city_state || (data?.city_choice ? state : data?.location?.line) || '');
50
+ return [String(street ?? '').trim() + (u ? ' Apt ' + u : ''), city].filter(Boolean).join(', ') + (values?.zip ? ' ' + values.zip : '');
51
+ }
52
+ /** validate-address's answer reduced to what the form decides on; null when Google could not be asked or found nothing.
53
+ * The parts are the verdict, never next_action alone (measured: "501 Reading Way" came back "501 Read Street", ROUTE, ACCEPT).
54
+ * ask: 'street' (Google's street differs from the caller's: "Did you mean …?"), 'street_unconfirmed' (the same street, but
55
+ * Google could not place it at a premise), 'place' (Google replaced the city or ZIP code), else ''. */
56
+ export function addressVerdict(result, said) {
57
+ if (!result || result.status !== 'ok' || !result.parts || typeof result.parts !== 'object')
58
+ return null;
59
+ const p = result.parts, text = k => String(p[k]?.text || ''), g = String(result.granularity || '');
60
+ const number = p.street_number || null, route = p.route || null, street = [text('street_number'), text('route')].filter(Boolean).join(' ');
61
+ const fold = s => String(s ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
62
+ const changed = [number, route].some(x => x && (x.corrected === true || x.replaced === true));
63
+ const coarse = !['PREMISE', 'SUB_PREMISE', 'PREMISE_PROXIMITY'].includes(g) || g === 'PREMISE_PROXIMITY' && number?.level !== 'CONFIRMED';
64
+ const suspicious = [number, route].some(x => x && x.level === 'UNCONFIRMED_AND_SUSPICIOUS');
65
+ const differs = !!street && fold(street) !== fold(said);
66
+ const cityReplaced = p.locality?.replaced === true, zipReplaced = p.postal_code?.replaced === true;
67
+ const ask = !street ? '' : differs && (changed || coarse || suspicious) ? 'street' : coarse || suspicious ? 'street_unconfirmed' : cityReplaced || zipReplaced ? 'place' : '';
68
+ return { street, city: text('locality') || text('postal_town') || text('sublocality') || text('sublocality_level_1') || text('neighborhood'),
69
+ state: text('administrative_area_level_1'), zip: (/\d{5}/.exec(text('postal_code')) || [''])[0], formatted: String(result.formatted || '').replace(/,\s*USA$/, ''),
70
+ granularity: g, verified: !!number && !!route && !coarse && !suspicious, ask, city_replaced: cityReplaced, zip_replaced: zipReplaced,
71
+ units_needed: (result.missing || []).includes('subpremise'), unit_confirmed: p.subpremise?.level === 'CONFIRMED', response_id: String(result.response_id || '') };
72
+ }
73
+ /** The validate-address verdict applied to the street answer (the street validator's last step). Returns the validator's
74
+ * answer: a proposal to confirm Google's version first, or the street accepted. `keys` are the yes/no words for each language. */
75
+ export function streetCheck(state, values, verdict, value, reading, keys) {
76
+ const data = state.data, said = String(value), cur = Object.assign({}, state.values, values);
77
+ const derived = state.accepted?.city?.origin === 'derived', cityInput = data.city_known === true;
78
+ const setCity = v => { if (!v.city)
79
+ return; if (cityInput) {
80
+ state.values.city = v.city;
81
+ cur.city = v.city;
82
+ }
83
+ else {
84
+ state.values.city_state = v.city + (v.state ? ', ' + v.state : '');
85
+ cur.city_state = state.values.city_state;
86
+ } };
87
+ const units = v => { data.units_needed = !!(v && v.units_needed); };
88
+ // the city Google names, when the form has none yet: one of the ZIP code's listed names (accents, case, punctuation folded), or any city when it lists none
89
+ const fold = x => String(x ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
90
+ const cityFrom = v => { if (!v || !v.city || !cityInput || cur.city)
91
+ return ''; const list = data.city_choices || []; if (!list.length)
92
+ return v.city; const hit = list.find(c => fold(c.key) === fold(v.city)); return hit ? String(hit.key) : ''; };
93
+ const take = (v, street) => {
94
+ data.validation = Object.assign({}, v, { input: { street, city: String(cur.city || data.street_city || cur.city_state || ''), zip: String(cur.zip || '') } });
95
+ data.street = { street: v.street, said: data.check ? data.check.said : said, verified: v.verified, city: v.city };
96
+ };
97
+ // the staged version checked again while it waits for the caller (the proposal's refresh): the same question
98
+ if (reading && reading.proposalResume && !reading.proposalApproval && data.check)
99
+ return { ok: true, value: said, proposal: data.check.proposal };
100
+ // YES to Google's version (the proposal's revalidation): its street, city and ZIP code
101
+ if (reading && reading.proposalApproval && data.check) {
102
+ const v = data.check.verdict;
103
+ if (v.city_replaced || derived && v.city && cur.city !== v.city)
104
+ setCity(v);
105
+ if (v.zip_replaced && v.zip) {
106
+ state.values.zip = v.zip;
107
+ cur.zip = v.zip;
108
+ }
109
+ data.street_city = cityFrom(v);
110
+ take(v, said);
111
+ units(v);
112
+ data.check = null;
113
+ return { ok: true, value: said };
114
+ }
115
+ data.check = null;
116
+ data.street_city = cityFrom(verdict);
117
+ data.check_street = verdict && verdict.street ? verdict.street : '';
118
+ data.check_rid = verdict ? verdict.response_id : '';
119
+ // Google could not be asked, found nothing or named no street: the form goes on as before
120
+ if (!verdict || !verdict.street) {
121
+ data.validation = null;
122
+ units(null);
123
+ return { ok: true, value: said };
124
+ }
125
+ // a city the form derived from the ZIP code follows Google's, as it follows an exact street match
126
+ if (derived && verdict.city && cur.city !== verdict.city) {
127
+ state.values.city = verdict.city;
128
+ cur.city = verdict.city;
129
+ }
130
+ const ask = verdict.ask === 'place' && !verdict.zip_replaced && derived ? '' : verdict.ask;
131
+ if (ask && !data.check_declined) {
132
+ const q = ask === 'street' ? ['Did you mean ' + verdict.street + '?', '¿Quiso decir ' + verdict.street + '?']
133
+ : ask === 'street_unconfirmed' ? ['I could not confirm ' + said + '. Is that right?', 'No pude confirmar ' + said + '. ¿Es correcto?']
134
+ : verdict.zip_replaced ? ['The ZIP code for that address is ' + verdict.zip + '. Is that right?', 'El código postal de esa dirección es ' + verdict.zip + '. ¿Es correcto?']
135
+ : ['That ZIP code is in ' + verdict.city + '. Is that right?', 'Ese código postal está en ' + verdict.city + '. ¿Es correcto?'];
136
+ const proposal = { question: q[0] + ' ' + keys.en, question_es: q[1] + ' ' + keys.es, on_declined: 'address-check-declined' };
137
+ data.check = { kind: ask, said, verdict, proposal };
138
+ return { ok: true, value: ask === 'street' ? verdict.street : said, proposal };
139
+ }
140
+ // asked once and declined: the caller's words, not verified
141
+ if (ask) {
142
+ data.validation = null;
143
+ data.street = { street: said, said, verified: false, city: '' };
144
+ units(Object.assign({}, verdict, { verified: false }));
145
+ return { ok: true, value: said };
146
+ }
147
+ take(verdict, said);
148
+ units(verdict);
149
+ return { ok: true, value: said };
150
+ }
151
+ /** NO to Google's version. A street is asked again (once: the next answer is kept as given). A city or ZIP code: the
152
+ * caller's street is kept, not verified, and the city or ZIP code is asked again. */
153
+ export function checkDeclined(cargo, form, accept, reset) {
154
+ const state = cargo.forms[form], data = state.data, c = data.check || {};
155
+ data.check_declined = true;
156
+ data.check = null;
157
+ if (c.kind === 'place') {
158
+ accept(cargo, [{ form, name: 'street', value: c.said, ok: true, origin: 'answer' }]);
159
+ data.street = { street: c.said, said: c.said, verified: false, city: '' };
160
+ data.validation = null;
161
+ data.city_ask = 'yes';
162
+ data.street_city = '';
163
+ reset(cargo, form, [c.verdict && c.verdict.zip_replaced ? 'zip' : data.city_known === true ? 'city' : 'city_state']);
164
+ }
165
+ return true;
166
+ }
167
+ /** After the street is accepted: the city is asked when still missing, unless Google named one (a ZIP code with several
168
+ * place names asks none before the street). The read-back is the first place that city is said. */
169
+ export function streetAccepted(state) {
170
+ const data = state.data;
171
+ data.city_ask = 'yes';
172
+ const v = state.values.city;
173
+ if (data.city_known === true && (v === undefined || v === null || v === '') && data.street_city) {
174
+ state.values.city = data.street_city;
175
+ state.accepted.city = { origin: 'derived', revision: state.revision || 0 };
176
+ }
177
+ return true;
178
+ }
179
+ /** The whole form's check: a card that left the unit blank on a building Google says has units comes back asking it,
180
+ * once (a NONE said to the question is an answer). */
181
+ export function unitsGiven(state) {
182
+ const data = state.data, accepted = state.accepted && state.accepted.unit;
183
+ if (data.units_needed && state.values.unit === null && accepted && accepted.origin === 'form_submission' && !data.units_told) {
184
+ data.units_told = true;
185
+ return { ok: false, invalid: [{ name: 'unit' }] };
186
+ }
187
+ return { ok: true };
188
+ }
189
+ /** The unit question: the building's own wording once Google says it has units, else the form's ordinary one. */
190
+ export function unitQuestion(data, building) {
191
+ if (data.unit_question_plain === undefined) {
192
+ data.unit_question_plain = data.unit_question;
193
+ data.unit_question_plain_es = data.unit_question_es;
194
+ }
195
+ data.unit_question = data.units_needed ? building.en : data.unit_question_plain;
196
+ data.unit_question_es = data.units_needed ? building.es : data.unit_question_plain_es;
197
+ return true;
198
+ }
199
+ /** A unit answer, before Google is asked: a unit number or letter ("3036 E", "B", "F108", never a sentence or a word), and
200
+ * whether Google should check it (a "none" never reaches a validator). */
201
+ export function unitPrecheck(data, value) {
202
+ const u = String(value).replace(/^(apartment|apartamento|departamento|apt\.?|unit|unidad|#)\s*/i, '').replace(/[.,#:]+/g, ' ').replace(/\s+/g, ' ').trim();
203
+ if (!(/^[A-Za-z]$/.test(u) || /\d/.test(u) && /^[A-Za-z0-9-]{1,8}(?:\s[A-Za-z0-9-]{1,4})?$/.test(u)))
204
+ return { ok: false, message: "That doesn't look like an apartment number.", message_es: 'Eso no parece un número de apartamento.' };
205
+ return data.check_street ? { ok: true, value: String(value), check: true, unit: u } : { ok: true, value: String(value) };
206
+ }
207
+ /** Google's answer for the address with its unit: a unit it could not confirm is asked once more, then kept as given. */
208
+ export function unitResult(data, pre, checked) {
209
+ if (!pre.check)
210
+ return { ok: pre.ok, ...(pre.value !== undefined ? { value: pre.value } : {}), ...(pre.quiet ? { quiet: true } : {}), ...(pre.message ? { message: pre.message, message_es: pre.message_es } : {}) };
211
+ const confirmed = !!(checked && checked.status === 'ok' && checked.parts && checked.parts.subpremise && checked.parts.subpremise.level === 'CONFIRMED');
212
+ if (checked && checked.status === 'ok' && !confirmed && !data.unit_retry) {
213
+ data.unit_retry = true;
214
+ return { ok: false, message: 'I could not confirm apartment ' + pre.unit + ' at that address.', message_es: 'No pude confirmar el apartamento ' + pre.unit + ' en esa dirección.' };
215
+ }
216
+ data.unit_retry = false;
217
+ if (data.validation)
218
+ data.validation.unit_confirmed = confirmed;
219
+ return { ok: true, value: pre.value };
220
+ }
38
221
  export function resolvedAddress(values, data) {
39
222
  const unit = String(values.unit ?? '').replace(/^(apt\.?|unit|#)\s*/i, '');
40
- const street = data.street?.street || values.street || '', city = values.city && data.location?.state ? values.city + ', ' + data.location.state : data.location?.line || values.city_state || '';
41
- return { street, unit, city, zip: String(values.zip || ''), line: street + (unit ? ' Apt ' + unit : '') + ', ' + city + ' ' + values.zip, verified: data.street?.verified === true, said: data.street?.said || values.street || '' };
223
+ // Google's address, when it validated the street, city and ZIP code the form holds now (a later correction falls back to the caller's words)
224
+ const v = data.validation, checked = !!(v && v.input && v.input.street === String(values.street || '') && v.input.zip === String(values.zip || '') && v.input.city === String(values.city || values.city_state || ''));
225
+ const street = checked && v.street ? v.street : data.street?.street || values.street || '', city = checked && v.city ? v.city + (v.state ? ', ' + v.state : '') : values.city && data.location?.state ? values.city + ', ' + data.location.state : data.location?.line || values.city_state || '';
226
+ const zip = checked && v.zip ? v.zip : String(values.zip || '');
227
+ return { street, unit, city, zip, line: street + (unit ? ' Apt ' + unit : '') + ', ' + city + ' ' + zip, verified: checked ? v.verified === true : data.street?.verified === true, said: data.street?.said || values.street || '',
228
+ address_verified: checked && v.verified === true, unit_verified: checked && !!unit && v.unit_confirmed === true, formatted: checked ? v.formatted : '' };
42
229
  }
@@ -1 +1 @@
1
- export const JSFE_RUNTIME_FINGERPRINT = "sha256:d4c6ab7e924bce0da918301dfa047d58a3bdc738cddff44a8f766d3f70489754";
1
+ export const JSFE_RUNTIME_FINGERPRINT = "sha256:8d8b251566be0f473808d9214fce948a1df751d57a13d7f41c7c90b4198c4957";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "1.102.1",
3
+ "version": "1.104.0",
4
4
  "description": "TypeScript workflow engine for conversational/automation apps: multi-flow orchestration, interrupt/resume, stack-based control, robust errors, and flexible tool/REST integration.",
5
5
  "license": "MIT",
6
6
  "author": "Ron Pinkas",