jsfe 1.52.0 → 1.53.1

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.
@@ -9,16 +9,16 @@ 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
11
  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.0.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' },
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
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
14
  // 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
15
  // without one, today's wording.
16
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+'? Type the number, or NONE.':'Is there an apartment or unit number? Type the number, or NONE.';d.unit_question_es=labelled?'¿Hay un número de apartamento o unidad en su '+address_label_es+'? Escriba el número, o NINGUNO.':'¿Hay un número de apartamento o unidad? Escriba el número, o NINGUNO.';return true;})(cargo.forms[form_instance].data,typeof address_spec.label==='string'&&!!address_spec.label.trim())")],
17
- 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?' },
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?' },
17
+ 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' } },
19
19
  { 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'] } },
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? Type the number, or NONE.', question_es: '¿Hay un número de apartamento o unidad? Escriba el número, o NINGUNO.' }],
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? Type the number, or NONE.', question_es: '¿Hay un número de apartamento o unidad? Escriba el número, o NINGUNO.', form_client: { autofill: 'address-line2' } }],
22
22
  before_confirm: [S('address_resolved', 'address_result', E(resolvedAddress, 'cargo.forms[form_instance].values', 'cargo.forms[form_instance].data'))],
23
23
  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?', question_es: 'Su {{address_label_es}} es {{address_result.line}}. ¿Es correcta?' },
24
24
  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')] });
@@ -38,7 +38,7 @@ const zipPrompt = C('address-zip-prompt', 'Render the ZIP question from the owne
38
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' } } });
39
39
  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
40
  // NO at the read-back asks which part is wrong and re-asks only that part; ALL starts over.
41
- const PARTS = [{ key: 'zip', phrases: ['1', 'zip', 'zip code', 'postal code', 'código postal', 'codigo postal'] }, { key: 'city', phrases: ['2', 'city', 'ciudad'] }, { key: 'street', phrases: ['3', 'street', 'calle'] }, { key: 'unit', phrases: ['4', 'apartment', 'apt', 'unit', 'apartamento', 'unidad', 'departamento'] }, { key: 'all', phrases: ['5', 'all', 'everything', 'all of it', 'todo', 'toda'] }];
41
+ 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'] }];
42
42
  const declined = C('collect-geocoded-address-declined', 'Ask which part of the declined address is wrong, re-ask only that part, or start a fresh pass.', [
43
43
  S('address_retry_owner', 'parent_form', 'cargo.forms[form_instance].parent'), S('address_retry_input', 'result_input', 'cargo.forms[form_instance].result_input'),
44
44
  F('address_retry_part_ask', 'ask-choice', { question: '{{part_question}}', question_es: '{{part_question_es}}', choices: '{{parts}}' }),
@@ -434,6 +434,7 @@ export namespace FIELD_PRESETS {
434
434
  export { question_es_12 as question_es };
435
435
  }
436
436
  }
437
+ export const FORM_AUTOFILL_TOKENS: string[];
437
438
  export const FLOWS: ({
438
439
  id: string;
439
440
  name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/forms/flows.js"],"names":[],"mappings":"AA4GA;;;;;;;GAOG;AACH;;;;GAIG;AACH,8HAA8H;AAC9H,uFAIC;AAiED;;2EAE2E;AAC3E,qEAEC;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyEC;AACD;;;GAGG;AACH;;;;;;EAGC;AAmlBD,wHAAwH;AACxH,wEAaC;AACD,4FAA4F;AAC5F;;;EAYC;AACD,sGAAsG;AACtG;;;EAOC;AAp2BM,6CAAuG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2jC9G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAOG"}
1
+ {"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/forms/flows.js"],"names":[],"mappings":"AA4GA;;;;;;;GAOG;AACH;;;;GAIG;AACH,8HAA8H;AAC9H,uFAIC;AAiGD;;2EAE2E;AAC3E,qEAEC;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyEC;AACD;;;GAGG;AACH;;;;;;EAGC;AAmlBD,wHAAwH;AACxH,wEAaC;AACD,4FAA4F;AAC5F;;;EAYC;AACD,sGAAsG;AACtG;;;EAOC;AAp4BM,6CAAuG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8H9G,4CAEqI;AA29BrI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAOG"}
@@ -145,17 +145,33 @@ function validateAcceptanceDeclarations(id, inputs) {
145
145
  }
146
146
  }
147
147
  /**
148
- * input.form_client: false (never on a form card) or the control a form card draws for it (docs/form-client.md):
149
- * {control: 'date', range_from?, min?, max?, timezone?}, {control: 'number', min?, max?} or {control: 'place', types,
150
- * regions?}. A date's min and max are whole days from today in `timezone` (required with either); range_from names the
151
- * start of a range, a date input of this form that is not itself an end. A number's min and max bound its value. A
152
- * place suggests what the caller types from the host's place service: types 'cities' or 'address', regions up to 15
153
- * ISO 3166-1 alpha-2 country codes. Checked at definition time; malformed fails.
148
+ * input.form_client: false (never on a form card) or how a form card draws it (docs/form-client.md). Every key is optional
149
+ * except a control's own requirements:
150
+ * - control 'date' {range_from?, min?, max?, timezone?}: a date's min and max are whole days from today in `timezone`
151
+ * (required with either); range_from names the start of a range, a date input of this form that is not itself an end.
152
+ * - control 'number' {min?, max?}: bounds on the value.
153
+ * - control 'place' {types, regions?, fills?}: suggests what the caller types from the host's place service: types
154
+ * 'cities' or 'address', regions up to 15 ISO 3166-1 alpha-2 country codes; fills {input: part} names inputs of this
155
+ * form a pick fills with a part of the picked place (postal_code, locality, admin_area, country).
156
+ * - control 'postal' {regions?, fills}: a postal code the host looks up as it is completed; the card shows the place it
157
+ * names, and fills {input: part} fills inputs of this form with its locality (and, for a combobox, the code's other
158
+ * localities as its options) or admin_area.
159
+ * - control 'combobox': a choice that also takes other text (accept_other), drawn as a text box offering its choices.
160
+ * - autofill: the HTML autocomplete token the browser may fill the box from (a saved address, name, email or phone).
161
+ * Checked at definition time; malformed fails.
154
162
  */
155
- const FORM_CLIENT_KEYS = { date: ['control', 'range_from', 'min', 'max', 'timezone'], number: ['control', 'min', 'max'], place: ['control', 'types', 'regions'] };
163
+ const FORM_CLIENT_KEYS = { date: ['control', 'range_from', 'min', 'max', 'timezone', 'autofill'], number: ['control', 'min', 'max', 'autofill'],
164
+ place: ['control', 'types', 'regions', 'fills', 'autofill'], postal: ['control', 'regions', 'fills', 'autofill'], combobox: ['control', 'autofill'], none: ['autofill'] };
156
165
  const FORM_CLIENT_KINDS = ['pattern', 'text', 'digits', 'amount', 'identifier'];
157
- const FORM_PLACE_KINDS = ['pattern', 'text'];
166
+ const FORM_CONTROL_KINDS = { place: ['pattern', 'text'], postal: ['digits', 'pattern', 'text', 'identifier'], combobox: ['choice'],
167
+ none: ['pattern', 'text', 'digits', 'amount', 'identifier', 'email', 'phone', 'choice'] };
158
168
  const FORM_PLACE_TYPES = ['cities', 'address'];
169
+ const FORM_FILL_PARTS = { place: ['postal_code', 'locality', 'admin_area', 'country'], postal: ['locality', 'admin_area'] };
170
+ // Positive whitelist: what a browser may fill from its own saved data. No payment card or one-time-code token: those are
171
+ // sensitive, and a sensitive input never takes a form_client control.
172
+ export const FORM_AUTOFILL_TOKENS = ['name', 'given-name', 'additional-name', 'family-name', 'honorific-prefix', 'honorific-suffix', 'nickname',
173
+ 'organization', 'organization-title', 'email', 'tel', 'tel-national', 'street-address', 'address-line1', 'address-line2', 'address-line3',
174
+ 'address-level1', 'address-level2', 'address-level3', 'postal-code', 'country', 'country-name', 'bday', 'sex', 'language', 'url'];
159
175
  function validateFormClientControls(id, inputs) {
160
176
  const all = (inputs || []).flatMap((input) => input.any_of || [input]);
161
177
  const fail = (input, message) => { throw new Error(`FORM ${id}: ${input.name} form_client ${message}`); };
@@ -164,24 +180,30 @@ function validateFormClientControls(id, inputs) {
164
180
  if (declared === undefined || declared === false)
165
181
  continue;
166
182
  else if (!declared || typeof declared !== 'object' || Array.isArray(declared))
167
- fail(input, 'must be false or {control, ...}');
168
- else if (!Object.hasOwn(FORM_CLIENT_KEYS, declared.control))
169
- fail(input, 'control must be "date", "number" or "place"');
170
- else { /* a control object, checked below */ }
171
- const extra = Object.keys(declared).filter((key) => !FORM_CLIENT_KEYS[declared.control].includes(key));
183
+ fail(input, 'must be false or {control?, autofill?, ...}');
184
+ else if (declared.control !== undefined && (declared.control === 'none' || !Object.hasOwn(FORM_CLIENT_KEYS, declared.control)))
185
+ fail(input, 'control must be "date", "number", "place", "postal" or "combobox"');
186
+ else { /* a control object, or autofill alone; checked below */ }
187
+ const control = declared.control ?? 'none';
188
+ const extra = Object.keys(declared).filter((key) => !FORM_CLIENT_KEYS[control].includes(key));
172
189
  if (extra.length)
173
- fail(input, `${declared.control} cannot declare ${extra.join(', ')}`);
174
- const kinds = declared.control === 'place' ? FORM_PLACE_KINDS : FORM_CLIENT_KINDS;
175
- if (!kinds.includes(input.profile?.kind))
176
- fail(input, `${declared.control} control needs a profile of kind ${kinds.join(', ')}`);
190
+ fail(input, control === 'none' ? `without a control declares only autofill, not ${extra.join(', ')}` : `${control} cannot declare ${extra.join(', ')}`);
191
+ const kinds = FORM_CONTROL_KINDS[control] || FORM_CLIENT_KINDS;
192
+ const kind = (input.profile || FIELD_PRESETS[input.field]?.profile)?.kind;
193
+ if (!kinds.includes(kind))
194
+ fail(input, `${control === 'none' ? 'autofill' : control + ' control'} needs a profile of kind ${kinds.join(', ')}`);
177
195
  if (input.pii === true)
178
196
  fail(input, 'control cannot draw a sensitive input');
197
+ if (declared.autofill !== undefined && !FORM_AUTOFILL_TOKENS.includes(declared.autofill))
198
+ fail(input, `autofill ${JSON.stringify(declared.autofill)} is not one of ${FORM_AUTOFILL_TOKENS.join(', ')}`);
199
+ if (control === 'combobox' && (input.profile || {}).accept_other !== true)
200
+ fail(input, 'combobox needs a choice that accepts other text (accept_other)');
179
201
  for (const key of ['min', 'max'])
180
202
  if (declared[key] !== undefined && !Number.isInteger(declared[key]))
181
203
  fail(input, `${key} must be a whole number`);
182
204
  if (Number.isInteger(declared.min) && Number.isInteger(declared.max) && declared.min > declared.max)
183
205
  fail(input, 'min is above max');
184
- if (declared.control === 'date') {
206
+ if (control === 'date') {
185
207
  if ((declared.min !== undefined || declared.max !== undefined) && declared.timezone === undefined)
186
208
  fail(input, 'min and max are days from today: declare the timezone they count in');
187
209
  if (declared.timezone !== undefined) {
@@ -203,15 +225,33 @@ function validateFormClientControls(id, inputs) {
203
225
  }
204
226
  else { /* a single date or a range start */ }
205
227
  }
206
- else if (declared.control === 'place') {
207
- if (!FORM_PLACE_TYPES.includes(declared.types))
228
+ else if (control === 'place' || control === 'postal') {
229
+ if (control === 'place' && !FORM_PLACE_TYPES.includes(declared.types))
208
230
  fail(input, `types must be ${FORM_PLACE_TYPES.map((type) => `"${type}"`).join(' or ')}`);
209
231
  if (declared.regions !== undefined && (!Array.isArray(declared.regions) || !declared.regions.length || declared.regions.length > 15 ||
210
232
  !declared.regions.every((region) => typeof region === 'string' && /^[a-z]{2}$/i.test(region))))
211
233
  fail(input, 'regions must be 1 to 15 two-letter country codes');
212
234
  else { /* any region, or a valid list */ }
235
+ const fills = declared.fills;
236
+ if (fills === undefined && control === 'postal')
237
+ fail(input, 'postal needs fills: the inputs its place fills');
238
+ else if (fills !== undefined) {
239
+ if (!fills || typeof fills !== 'object' || Array.isArray(fills) || !Object.keys(fills).length || Object.keys(fills).length > 8)
240
+ fail(input, 'fills must map 1 to 8 inputs to a part');
241
+ for (const [name, part] of Object.entries(fills)) {
242
+ const target = all.find((other) => other.name === name);
243
+ if (!target || target === input)
244
+ fail(input, `fills ${name} must name another input of this form`);
245
+ else if (target.pii === true || target.form_client === false)
246
+ fail(input, `fills ${name} must be an input a card can draw`);
247
+ else if (!FORM_FILL_PARTS[control].includes(part))
248
+ fail(input, `fills ${name}: part must be ${FORM_FILL_PARTS[control].join(', ')}`);
249
+ else { /* a valid fill */ }
250
+ }
251
+ }
252
+ else { /* a place that fills nothing else */ }
213
253
  }
214
- else { /* a number */ }
254
+ else { /* a number, a combobox or autofill alone */ }
215
255
  }
216
256
  }
217
257
  /** How firm a form's confirmation is: firm ONLY when an action it authorizes is a payment (effect 'charge'); every other
@@ -5,6 +5,24 @@ export function projectForm(session: any, flows: any): {
5
5
  language: any;
6
6
  fields: any;
7
7
  } | null;
8
+ /**
9
+ * The options of the question asked now, when it has a closed, labelled set, for a client that draws them as buttons or a list:
10
+ * {version: 1, language, options: [{key, label, say}]}, else null. Only a question asked by ask-choice qualifies (a
11
+ * confirmation, a menu, a choice asked in chat), and only when every option it offers has a label in the session's
12
+ * language (yes and no have standard ones). An option keyed 'event:' is an interrupt word, never offered. A tap sends `say`
13
+ * as the caller's own message: the label when the option reads it, else the option's first word or key that is not a
14
+ * number, else its first key; so the answer is read by the question's own reader. A host offers this only when no form
15
+ * card is drawn (projectForm is null).
16
+ */
17
+ export function projectChoices(session: any): {
18
+ version: number;
19
+ language: string;
20
+ options: {
21
+ key: string;
22
+ label: string;
23
+ say: string;
24
+ }[];
25
+ } | null;
8
26
  /** Host preflight: call before updateActivity. Unknown paths and malformed envelopes never enter execution. */
9
27
  /** The place a view's field suggests, or null: the host's suggestion endpoint answers only for a place field of the
10
28
  * form that is open now (`form` is the view's instance, `path` the field's), so it is never a general place service. */
@@ -1 +1 @@
1
- {"version":3,"file":"form-client.d.ts","sourceRoot":"","sources":["../../src/forms/form-client.js"],"names":[],"mappings":"AAiCA,iGAAiG;AACjG;;;;;SA+FC;AAED,+GAA+G;AAC/G;wHACwH;AACxH,qEAWC;AAED;;;;SA4CC;AAED;;GAEG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6BC;AA5ND,qCAAsC,eAAe,CAAC"}
1
+ {"version":3,"file":"form-client.d.ts","sourceRoot":"","sources":["../../src/forms/form-client.js"],"names":[],"mappings":"AAiCA,iGAAiG;AACjG;;;;;SAwGC;AAMD;;;;;;;;GAQG;AACH;;;;;;;;SAoBC;AAED,+GAA+G;AAC/G;wHACwH;AACxH,qEAWC;AAED;;;;SA4CC;AAED;;GAEG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BC;AA1QD,qCAAsC,eAAe,CAAC"}
@@ -105,7 +105,9 @@ export function projectForm(session, flows) {
105
105
  choices.some(choice => choice.current_only && String(choice.key) === acceptedKey))
106
106
  continue;
107
107
  field.choices = [...allowedChoices.values()];
108
- if (!field.choices.length || profile.accept_other)
108
+ // A choice that also takes other text is drawn only as a combobox (a text box offering its choices, which may
109
+ // be none yet); a select could not hold the other text.
110
+ if (profile.accept_other ? input.form_client?.control !== 'combobox' : !field.choices.length)
109
111
  continue;
110
112
  }
111
113
  field.constraints = Object.fromEntries(['min', 'max'].filter(key => typeof profile[key] === 'number').map(key => [key, profile[key]]));
@@ -119,12 +121,21 @@ export function projectForm(session, flows) {
119
121
  if (control === 'date' && input.form_client.range_from)
120
122
  field.range_from = prefix + input.form_client.range_from;
121
123
  }
122
- else if (control === 'place') {
123
- // Suggestions come from the host's place service; the profile's bounds still apply to the typed text.
124
+ else if (control === 'place' || control === 'postal') {
125
+ // Suggestions and lookups come from the host's place service; the profile's bounds still apply to the typed text.
126
+ // fills names the card's fields (by path) that a pick or a looked-up code fills, with the part each takes.
127
+ const { types, regions, fills } = input.form_client;
128
+ field.control = control;
129
+ field[control] = { ...(types ? { types } : {}), ...(regions ? { regions: regions.map(region => region.toLowerCase()) } : {}),
130
+ ...(fills ? { fills: Object.fromEntries(Object.entries(fills).map(([name, part]) => [prefix + name, part])) } : {}) };
131
+ }
132
+ else if (control === 'combobox') {
124
133
  field.control = control;
125
- field.place = { types: input.form_client.types, ...(input.form_client.regions ? { regions: input.form_client.regions.map(region => region.toLowerCase()) } : {}) };
126
134
  }
127
135
  else { /* the profile's own box */ }
136
+ // The browser may fill the box from its saved data (an address, a name).
137
+ if (input.form_client?.autofill && !field.sensitive)
138
+ field.autofill = input.form_client.autofill;
128
139
  // A declinable field may be left blank: the submission names it in `declined` (answered, no value).
129
140
  if (input.declinable === true) {
130
141
  field.declinable = true;
@@ -156,6 +167,44 @@ export function projectForm(session, flows) {
156
167
  return null;
157
168
  return projected.length ? { version: 1, form: root.id, language, fields: projected } : null;
158
169
  }
170
+ const STANDARD_LABELS = { yes: { en: 'Yes', es: 'Sí' }, no: { en: 'No', es: 'No' } };
171
+ const MAX_CHOICE_OPTIONS = 12;
172
+ const said = text => String(text ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
173
+ /**
174
+ * The options of the question asked now, when it has a closed, labelled set, for a client that draws them as buttons or a list:
175
+ * {version: 1, language, options: [{key, label, say}]}, else null. Only a question asked by ask-choice qualifies (a
176
+ * confirmation, a menu, a choice asked in chat), and only when every option it offers has a label in the session's
177
+ * language (yes and no have standard ones). An option keyed 'event:' is an interrupt word, never offered. A tap sends `say`
178
+ * as the caller's own message: the label when the option reads it, else the option's first word or key that is not a
179
+ * number, else its first key; so the answer is read by the question's own reader. A host offers this only when no form
180
+ * card is drawn (projectForm is null).
181
+ */
182
+ export function projectChoices(session) {
183
+ if (!session || session.continuationSafetyHold)
184
+ return null;
185
+ const frame = (session.flowStacks || []).flat().at(-1);
186
+ if (!frame?.pendingVariable || frame.flowId !== 'ask-choice')
187
+ return null;
188
+ const language = session.language === 'es' ? 'es' : 'en';
189
+ const choices = Array.isArray(frame.variables?.choices) ? frame.variables.choices.filter(choice => !String(choice?.key ?? '').startsWith('event:')) : [];
190
+ if (choices.length < 2 || choices.length > MAX_CHOICE_OPTIONS)
191
+ return null;
192
+ const options = [], seen = new Set();
193
+ for (const choice of choices) {
194
+ const key = String(choice.key ?? '');
195
+ const label = String((language === 'es' ? choice.label_es || choice.label : choice.label) || STANDARD_LABELS[key]?.[language] || '').trim();
196
+ if (!key || !label || seen.has(key))
197
+ return null;
198
+ seen.add(key);
199
+ const words = [].concat(choice.phrases ?? choice.words ?? []).map(String);
200
+ const reads = words.some(word => said(word) === said(label)) || (STANDARD_LABELS[key] && label === STANDARD_LABELS[key][language]);
201
+ const say = reads ? label : words.find(word => !/^\d+$/.test(word.trim())) || words[0] || '';
202
+ if (!say)
203
+ return null;
204
+ options.push({ key, label, say });
205
+ }
206
+ return { version: 1, language, options };
207
+ }
159
208
  /** Host preflight: call before updateActivity. Unknown paths and malformed envelopes never enter execution. */
160
209
  /** The place a view's field suggests, or null: the host's suggestion endpoint answers only for a place field of the
161
210
  * form that is open now (`form` is the view's instance, `path` the field's), so it is never a general place service. */
@@ -262,7 +311,9 @@ export function formSubmissionReaders(submission, getSession) {
262
311
  const profile = candidates.find(candidate => candidate.form === hit.form && candidate.name === hit.name)?.profile || hit.profile;
263
312
  const raw = hit.raw;
264
313
  const read = profile.kind === 'choice'
265
- ? (profile.choices || []).some(choice => String(choice.key) === raw && (!choice.current_only || hit.form === current.form && (hit.name === current.name || current.names?.includes(hit.name)))) ? { value: raw } : null
314
+ ? (profile.choices || []).some(choice => String(choice.key) === raw && (!choice.current_only || hit.form === current.form && (hit.name === current.name || current.names?.includes(hit.name)))) ? { value: raw }
315
+ // A combobox's own text: a choice that takes other text keeps it (with a letter when the profile asks for one).
316
+ : profile.accept_other === true && raw.trim() && (!profile.other_needs_letter || /\p{L}/u.test(raw)) ? { value: raw.trim() } : null
266
317
  : readInputProfile({ ...profile, marked: false }, raw, true);
267
318
  const valid = read && Object.hasOwn(read, 'value') && read.value !== '' && read.refused !== true && !read.incompleteMoney;
268
319
  return { ...hit, value: valid ? read.value : raw, invalid: !valid, origin: 'form_submission', current: false, utterance: '' };
@@ -11,5 +11,5 @@ export { addressDraft, zipLocation, streetLocation, resolvedAddress } from "../h
11
11
  export { Form, Provider, Performer, Worker, compileExpression } from "./authoring.js";
12
12
  export { compileFlowDeclarations, serializeFlowDeclaration, captureOriginalDeclaration } from "./declarations.js";
13
13
  export { findFlowTraps, formatFlowTrap } from "./flow-traps.js";
14
- export { projectForm, parseFormSubmission, formSubmissionReaders, formPlaceField, FORM_SUBMISSION_PREFIX } from "./form-client.js";
14
+ export { projectForm, projectChoices, parseFormSubmission, formSubmissionReaders, formPlaceField, FORM_SUBMISSION_PREFIX } from "./form-client.js";
15
15
  //# sourceMappingURL=index.d.ts.map
@@ -16,4 +16,4 @@ export { compileFlowDeclarations, serializeFlowDeclaration, captureOriginalDecla
16
16
  export { continuationBreaks } from './continuation-compat.js';
17
17
  export { inheritFlowDeclaration } from './declaration-capture.js';
18
18
  export { findFlowTraps, formatFlowTrap } from './flow-traps.js';
19
- export { projectForm, parseFormSubmission, formSubmissionReaders, formPlaceField, FORM_SUBMISSION_PREFIX } from './form-client.js';
19
+ export { projectForm, projectChoices, parseFormSubmission, formSubmissionReaders, formPlaceField, FORM_SUBMISSION_PREFIX } from './form-client.js';
@@ -1 +1 @@
1
- {"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../src/helpers/address.js"],"names":[],"mappings":"AAEA;;;;;EAQC;AACD;;;;;SASC;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;;;;;;;;EAIC"}
@@ -13,7 +13,9 @@ export function addressDraft(raw) {
13
13
  export function zipLocation(result) {
14
14
  const components = result?.components || result?.results?.[0]?.address_components || [];
15
15
  const part = (kind, short = false) => { const row = components.find(c => (c.types || []).includes(kind)); return row ? String(short ? row.short_name || row.long_name : row.long_name || row.short_name) : ''; };
16
- const city = part('locality') || part('postal_town') || part('sublocality'), state = part('administrative_area_level_1', true);
16
+ // The place name its mail carries: the locality, else (inside a city Google splits into named areas, such as Los Angeles's
17
+ // Canoga Park and West Hills, where it returns no locality) the sublocality or neighborhood.
18
+ const city = part('locality') || part('postal_town') || part('sublocality') || part('sublocality_level_1') || part('neighborhood'), state = part('administrative_area_level_1', true);
17
19
  // A ZIP code can belong to several places (90023: Commerce, East Los Angeles, Los Angeles, Vernon); each is a name its
18
20
  // mail may carry, so the caller picks one. Google lists them as postcode_localities; at most 7 (8 is a reserved key).
19
21
  const listed = [].concat(result?.localities || result?.results?.[0]?.postcode_localities || []).map(String).filter(Boolean);
@@ -30,7 +32,7 @@ export function streetLocation(result, said, zip) {
30
32
  const exact = result?.status === 'OK' && row.partial_match !== true && types.includes('street_address') && locationType === 'ROOFTOP' && part('street_number') && part('route') && (!part('postal_code') || part('postal_code') === zip);
31
33
  // An exact street match names the place its mail carries; it corrects a city read from the ZIP code alone (90805 is
32
34
  // Lakewood to the ZIP lookup, while its streets are Long Beach and Lakewood)
33
- const city = exact ? part('locality') || part('postal_town') || part('sublocality') : '';
35
+ const city = exact ? part('locality') || part('postal_town') || part('sublocality') || part('sublocality_level_1') || part('neighborhood') : '';
34
36
  return { street: exact ? part('street_number') + ' ' + part('route') : String(said).trim(), said: String(said).trim(), verified: !!exact, city };
35
37
  }
36
38
  export function resolvedAddress(values, data) {
@@ -1 +1 @@
1
- export const JSFE_RUNTIME_FINGERPRINT = "sha256:76ce5ae5d3bb7215c635ed6e0a92a8a91ab1701e451c37ecdf8d1a1a73c21a7e";
1
+ export const JSFE_RUNTIME_FINGERPRINT = "sha256:8c20b9455024dec07f49227a0774f24c296eeef219a95007dcf4801340d0f140";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "1.52.0",
3
+ "version": "1.53.1",
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",