@ai-matrx/alchemy 0.8.21 → 0.8.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/core.cjs +9 -5
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +14 -0
- package/dist/core.d.ts +14 -0
- package/dist/core.js +9 -5
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +9 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +9 -5
- package/dist/index.js.map +1 -1
- package/dist/menu.cjs +1 -1
- package/dist/menu.cjs.map +1 -1
- package/dist/menu.d.cts +10 -1
- package/dist/menu.d.ts +10 -1
- package/dist/menu.js +1 -1
- package/dist/menu.js.map +1 -1
- package/dist/operate.cjs +9 -5
- package/dist/operate.cjs.map +1 -1
- package/dist/operate.d.cts +14 -0
- package/dist/operate.d.ts +14 -0
- package/dist/operate.js +9 -5
- package/dist/operate.js.map +1 -1
- package/dist/react-bar.cjs +1 -1
- package/dist/react-bar.cjs.map +1 -1
- package/dist/react-bar.d.cts +2 -0
- package/dist/react-bar.d.ts +2 -0
- package/dist/react-bar.js +1 -1
- package/dist/react-bar.js.map +1 -1
- package/dist/react-host.d.cts +2 -0
- package/dist/react-host.d.ts +2 -0
- package/dist/react-menu.cjs +2 -2
- package/dist/react-menu.cjs.map +1 -1
- package/dist/react-menu.d.cts +2 -0
- package/dist/react-menu.d.ts +2 -0
- package/dist/react-menu.js +2 -2
- package/dist/react-menu.js.map +1 -1
- package/dist/react-overflow.cjs +1 -1
- package/dist/react-overflow.cjs.map +1 -1
- package/dist/react-overflow.d.cts +7 -1
- package/dist/react-overflow.d.ts +7 -1
- package/dist/react-overflow.js +1 -1
- package/dist/react-overflow.js.map +1 -1
- package/dist/react-palette.cjs +1 -1
- package/dist/react-palette.cjs.map +1 -1
- package/dist/react-palette.d.cts +2 -0
- package/dist/react-palette.d.ts +2 -0
- package/dist/react-palette.js +1 -1
- package/dist/react-palette.js.map +1 -1
- package/dist/react-selection.cjs +1 -1
- package/dist/react-selection.cjs.map +1 -1
- package/dist/react-selection.d.cts +2 -0
- package/dist/react-selection.d.ts +2 -0
- package/dist/react-selection.js +1 -1
- package/dist/react-selection.js.map +1 -1
- package/dist/react-sheet.cjs +1 -1
- package/dist/react-sheet.cjs.map +1 -1
- package/dist/react-sheet.d.cts +2 -0
- package/dist/react-sheet.d.ts +2 -0
- package/dist/react-sheet.js +1 -1
- package/dist/react-sheet.js.map +1 -1
- package/package.json +1 -1
package/dist/operate.d.cts
CHANGED
|
@@ -272,6 +272,20 @@ interface AgentPayloadInput {
|
|
|
272
272
|
summary?: string;
|
|
273
273
|
attributes?: Record<string, string | number | boolean | null | undefined>;
|
|
274
274
|
context?: Record<string, string | number | boolean | null | undefined>;
|
|
275
|
+
/**
|
|
276
|
+
* How `data` travels (PP-09). `"json"` (the default): `data` is any JSON value, written as a
|
|
277
|
+
* fenced JSON body with `<`, `>` and `&` escaped. Any other name (`"text"`, `"markdown"`,
|
|
278
|
+
* `"csv"`, …): `data` is TEXT, written verbatim — real line breaks, no quoting, no escapes —
|
|
279
|
+
* inside a Markdown fence longer than any backtick run in it, under `<data format="<name>">`.
|
|
280
|
+
* A text source is never wrapped as one escaped JSON string.
|
|
281
|
+
*/
|
|
282
|
+
dataFormat?: string;
|
|
283
|
+
/**
|
|
284
|
+
* A person's instructions for the model (PP-10). Sealed with the envelope as its first block,
|
|
285
|
+
* `<instructions>…</instructions>`, so the preview, the clipboard and the token total all
|
|
286
|
+
* include it. Empty or whitespace-only = no block.
|
|
287
|
+
*/
|
|
288
|
+
instructions?: string;
|
|
275
289
|
}
|
|
276
290
|
interface AgentPayloadEnvironment {
|
|
277
291
|
url?: string;
|
package/dist/operate.d.ts
CHANGED
|
@@ -272,6 +272,20 @@ interface AgentPayloadInput {
|
|
|
272
272
|
summary?: string;
|
|
273
273
|
attributes?: Record<string, string | number | boolean | null | undefined>;
|
|
274
274
|
context?: Record<string, string | number | boolean | null | undefined>;
|
|
275
|
+
/**
|
|
276
|
+
* How `data` travels (PP-09). `"json"` (the default): `data` is any JSON value, written as a
|
|
277
|
+
* fenced JSON body with `<`, `>` and `&` escaped. Any other name (`"text"`, `"markdown"`,
|
|
278
|
+
* `"csv"`, …): `data` is TEXT, written verbatim — real line breaks, no quoting, no escapes —
|
|
279
|
+
* inside a Markdown fence longer than any backtick run in it, under `<data format="<name>">`.
|
|
280
|
+
* A text source is never wrapped as one escaped JSON string.
|
|
281
|
+
*/
|
|
282
|
+
dataFormat?: string;
|
|
283
|
+
/**
|
|
284
|
+
* A person's instructions for the model (PP-10). Sealed with the envelope as its first block,
|
|
285
|
+
* `<instructions>…</instructions>`, so the preview, the clipboard and the token total all
|
|
286
|
+
* include it. Empty or whitespace-only = no block.
|
|
287
|
+
*/
|
|
288
|
+
instructions?: string;
|
|
275
289
|
}
|
|
276
290
|
interface AgentPayloadEnvironment {
|
|
277
291
|
url?: string;
|
package/dist/operate.js
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res,err)=>function(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})};var init_types=__esm({"src/operate/types.ts"(){"use strict"}});function fencedCodeBlock(text,language){let runs=text.match(/`+/g)??[],fence="`".repeat(Math.max(3,...runs.map(run=>run.length+1)));return`${fence}${language}
|
|
2
2
|
${text}${text.endsWith(`
|
|
3
3
|
`)?"":`
|
|
4
|
-
`}${fence}`}var init_fenced_code=__esm({"src/operate/fenced-code.ts"(){"use strict"}});function fenceJsonBlock(json){return fencedCodeBlock(json.trimEnd(),"json")}function buildAgentPayload(input,environment={}){return assembleAgentPayload(input,environment).text}function assembleAgentPayload(input,environment={}){let kind=xmlName(input.kind),url=environment.url??(typeof window>"u"?"":window.location.href),route=environment.route??(typeof window>"u"?"":window.location.pathname),attrs=presentEntries(input.attributes).map(([key,value])=>` ${xmlName(key)}="${escapeXml(String(value))}"`).join(""),entries=[["location",input.location],...url?[["url",url]]:[],...route?[["route",route]]:[],["copied",input.description],["copied-at",environment.capturedAt??new Date().toISOString()],...presentEntries(input.context).map(([key,value])=>[xmlName(key),String(value)])],
|
|
4
|
+
`}${fence}`}var init_fenced_code=__esm({"src/operate/fenced-code.ts"(){"use strict"}});function fenceJsonBlock(json){return fencedCodeBlock(json.trimEnd(),"json")}function buildAgentPayload(input,environment={}){return assembleAgentPayload(input,environment).text}function assembleAgentPayload(input,environment={}){let kind=xmlName(input.kind),url=environment.url??(typeof window>"u"?"":window.location.href),route=environment.route??(typeof window>"u"?"":window.location.pathname),attrs=presentEntries(input.attributes).map(([key,value])=>` ${xmlName(key)}="${escapeXml(String(value))}"`).join(""),entries=[["location",input.location],...url?[["url",url]]:[],...route?[["route",route]]:[],["copied",input.description],["copied-at",environment.capturedAt??new Date().toISOString()],...presentEntries(input.context).map(([key,value])=>[xmlName(key),String(value)])],dataFormat=input.dataFormat??"json";if(dataFormat!=="json"&&!/^[a-z][a-z0-9-]*$/.test(dataFormat))throw new Error(`Invalid AI envelope data format: ${dataFormat}`);let context=entries.map(([key,value])=>`<${key}>${escapeXml(value)}</${key}>`).join(`
|
|
5
5
|
`),summary=input.summary?`<summary>
|
|
6
6
|
${escapeXml(input.summary)}
|
|
7
7
|
</summary>
|
|
8
|
-
`:"",head
|
|
8
|
+
`:"",head=`${input.instructions?.trim()?`<instructions>
|
|
9
|
+
${input.instructions.trim().replace(/<\/instructions>/gi,"<\\/instructions>")}
|
|
10
|
+
</instructions>
|
|
11
|
+
|
|
12
|
+
`:""}<${kind}${attrs}>
|
|
9
13
|
<context>
|
|
10
14
|
${context}
|
|
11
15
|
</context>
|
|
12
|
-
${summary}<data format="
|
|
13
|
-
`,fenced=fenceJsonBlock(safeJson),body=safeJson.trimEnd();return{text:`${head}${fenced}
|
|
16
|
+
${summary}<data format="${dataFormat}">
|
|
17
|
+
`,fenced,body;if(dataFormat==="json"){let json=JSON.stringify(input.data,null,2);if(json===void 0)throw new Error("AI envelope data must be JSON serializable.");let safeJson=json.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026");fenced=fenceJsonBlock(safeJson),body=safeJson.trimEnd()}else{if(typeof input.data!="string")throw new Error(`AI envelope ${dataFormat} data must be text.`);fenced=fencedCodeBlock(input.data,dataFormat==="text"?"text":dataFormat),body=input.data}return{text:`${head}${fenced}
|
|
14
18
|
</data>
|
|
15
19
|
</${kind}>`,body,bodyOffset:head.length+fenced.indexOf(`
|
|
16
20
|
`)+1}}var escapeXml,xmlName,presentEntries,init_agent_payload=__esm({"src/operate/agent-payload.ts"(){"use strict";init_fenced_code();escapeXml=value=>value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),xmlName=name=>{if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name))throw new Error(`Invalid AI envelope name: ${name}`);return name},presentEntries=values=>Object.entries(values??{}).filter(([,value])=>value!=null&&value!=="")}});import{stringifyJson}from"@ai-matrx/kit/json-format";import{escapeHtml}from"@ai-matrx/kit/html-escape";function clone(v,path="",seen=new WeakSet,policy={}){if(v===null||typeof v=="string"||typeof v=="boolean")return v;if(typeof v=="number"){if(!Number.isFinite(v))throw new ContentTransferError("unsupported-value","Only finite numbers are transferable",path);return v}if(typeof v!="object")throw new ContentTransferError("unsupported-value","Unsupported value",path);if(seen.has(v))throw new ContentTransferError("circular-value","Circular values cannot be transferred",path);if(!Array.isArray(v)&&Object.getPrototypeOf(v)!==Object.prototype&&Object.getPrototypeOf(v)!==null)throw new ContentTransferError("unsupported-value","Only plain JSON objects are transferable",path);if(seen.add(v),Array.isArray(v)){for(let index=0;index<v.length;index+=1)if(!Object.hasOwn(v,index))throw new ContentTransferError("unsupported-value","Sparse arrays cannot be transferred",`${path}/${index}`)}let out=Array.isArray(v)?v.map((x,i)=>clone(x,`${path}/${i}`,seen,policy)):Object.fromEntries(Object.entries(v).filter(([,x])=>!policy.omitUndefinedObjectProperties||x!==void 0).map(([k,x])=>[k,clone(x,`${path}/${enc(k)}`,seen,policy)]));return seen.delete(v),out}function displaySurfacePointer(path){if(!path)return"/";let pointer=`/${path.split("/").slice(1).map(segment=>{let controlSafe=segment.replace(/[\u0000-\u001F\u007F-\u009F]/g,character=>`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`);return truncateSurfacePointer(controlSafe,maxSurfacePointerSegmentLength)}).join("/")}`;return truncateSurfacePointer(pointer,maxSurfacePointerLength)}function cloneSurfaceValue(value,path){try{return normalizeTransferJsonAtPath(value,path,{omitUndefinedObjectProperties:!0})}catch(error){throw error instanceof ContentTransferError?new ContentTransferError(error.code,`Surface capture rejected value at ${displaySurfacePointer(error.path)}: ${error.message}`,error.path):error}}function normalizeTransferJsonAtPath(value,path,options={}){return clone(value,path,new WeakSet,options)}function normalizeTransferJson(value,options={}){return normalizeTransferJsonAtPath(value,"",options)}function deepFreeze(v){if(ArrayBuffer.isView(v))return v;if(v&&typeof v=="object"&&!Object.isFrozen(v)){Object.freeze(v);for(let x of Object.values(v))deepFreeze(x)}return v}function at(v,path){if(validatePointer(path),path==="")return v;if(!path.startsWith("/"))throw new ContentTransferError("invalid-path","Expected RFC 6901 pointer",path);let cur=v;for(let part of path.slice(1).split("/").map(dec))if(Array.isArray(cur))cur=cur[Number(part)];else if(cur&&typeof cur=="object")cur=Object.hasOwn(cur,part)?cur[part]:void 0;else return;return cur}function validatePointer(path){if(path!==""&&!path.startsWith("/")||/~(?![01])/u.test(path))throw new ContentTransferError("invalid-path","Expected an RFC 6901 JSON pointer",path)}function readTransferCell(row,column){return at(row,column.path)}function without(v,paths,omit,path=""){if(paths.includes(path)){omit.push({path,reason:"excluded"});return}if(Array.isArray(v))return v.map((x,i)=>without(x,paths,omit,`${path}/${i}`)).filter(x=>x!==void 0);if(v&&typeof v=="object"){let out=Object.create(null);for(let[k,x]of Object.entries(v)){let y=without(x,paths,omit,`${path}/${enc(k)}`);y!==void 0&&(out[k]=y)}return out}return v}function projectValue(v,rules,target,omit){return rules.forEach(rule=>validatePointer(rule.path)),without(clone(v),rules.filter(r=>r.target===target&&(!r.exportable||r.classification!=="ordinary")).map(r=>r.path),omit)??null}function excludedColumn(column){return column.exportable===!1||column.classification==="secret"||column.classification==="credential"}function rowProjectionExcludesColumnSchema(column,rules){return rules.some(rule=>rule.target==="row"&&(!rule.exportable||rule.classification!=="ordinary")&&(rule.path===column.path||column.path.startsWith(`${rule.path}/`)))}function projectColumnSchema(column,rules,omit){if(column.schema===void 0)return;let root=`/columns/${enc(column.id)}/schema`,schemaRules=rules.filter(rule=>rule.target==="payload"&&(rule.path===root||rule.path.startsWith(`${root}/`))).map(rule=>({...rule,path:rule.path.slice(root.length)})),projected=projectValue(column.schema,schemaRules,"payload",omit);if(!schemaRules.some(rule=>rule.path===""&&(!rule.exportable||rule.classification!=="ordinary")))return projected}function normalize(p,projection,omit){if(p.kind==="text"||p.kind==="markdown"){if(typeof p.text!="string")throw new ContentTransferError("unsupported-value","Text payload must contain a string","/text");let value=projectValue(p.text,projection.rules,"payload",omit),text=typeof value=="string"?value:"";return p.kind==="text"&&typeof p.language=="string"&&p.language.trim()?{kind:"text",text,language:p.language.trim()}:{kind:p.kind,text}}if(p.kind==="json")return{kind:"json",value:projectValue(p.value,projection.rules,"payload",omit)};if(p.kind==="registered")return{kind:"registered",format:p.format,value:projectValue(p.value,projection.rules,"payload",omit)};let rowsPayload=p;if(p.kind!=="rows")throw new ContentTransferError("invalid-payload","Unsupported payload kind");let sourceColumns=rowsPayload.columns.map(column=>({...column})),columns=sourceColumns.filter(column=>!excludedColumn(column)).map(column=>{let{schema:_sourceSchema,...withoutSchema}=column,schema=rowProjectionExcludesColumnSchema(column,projection.rules)?void 0:projectColumnSchema(column,projection.rules,omit);return{...withoutSchema,...schema===void 0?{}:{schema}}});resolveTransferRegistry(columns),columns.forEach(column=>validatePointer(column.path));let rules=[...projection.rules,...sourceColumns.filter(excludedColumn).map(c=>({target:"row",path:c.path,exportable:c.exportable??!0,classification:c.classification??"ordinary"}))];return{kind:"rows",columns,rows:rowsPayload.rows.map((row,index)=>{if(!row||typeof row!="object"||Array.isArray(row))throw new ContentTransferError("invalid-row","A table row must be a JSON object",`/rows/${index}`);let projected=projectValue(row,rules,"row",omit);return projected===null?{}:projected})}}function projectSnapshot(raw,projection){let omissions=raw.omissions.map(o=>({...o})),normalized=normalize(raw.payload,projection,omissions),payload=raw.limits?limitPayload(normalized,raw.limits,omissions):normalized,included=payload.kind==="rows"?payload.rows.length:raw.coverage.included;return deepFreeze({...raw,payload,coverage:{...raw.coverage,included,...included<raw.coverage.included?{status:"partial",reason:"Source export limit applied"}:{}},omissions,sections:raw.sections.filter(section=>!projection.rules.some(rule=>rule.target==="payload"&&(!rule.exportable||rule.classification!=="ordinary")&&(section.path===rule.path||section.path.startsWith(`${rule.path}/`)))).map(x=>({...x})),...raw.limits?{limits:{...raw.limits}}:{}})}function directSource(payload,options={}){let id=options.id??uid();return{projection:options.projection??{rules:[]},snapshot:{id,sourceId:options.sourceId??id,revision:options.revision??uid(),capturedAt:new Date().toISOString(),label:options.label??"Content",payload,coverage:options.coverage??{status:"complete",included:payload.kind==="rows"?payload.rows.length:1,total:payload.kind==="rows"?payload.rows.length:1},unsavedChanges:options.unsavedChanges??!1,omissions:[],sections:options.sections??[],...options.limits?{limits:{...options.limits}}:{}}}}async function capture(source,signal,scope="target"){stop(signal);let captured="kind"in source?directSource(source):await source.capture({scope,signal});stop(signal);let all=captured.allMatching;if(all&&(all.query.sourceId!==captured.snapshot.sourceId||all.query.revision!==captured.snapshot.revision||all.query.order.length===0))throw new ContentTransferError("query-mismatch","All-matching query must be captured with stable ordering");let snapshot=projectSnapshot(captured.snapshot,captured.projection);return all?{snapshot,allMatching:deepFreeze({[bound]:!0,source:{...all,query:{...all.query,query:clone(all.query.query),order:all.query.order.map(x=>({...x}))}},projection:{rules:captured.projection.rules.map(x=>({...x}))},columns:captured.snapshot.payload.kind==="rows"?captured.snapshot.payload.columns.map(column=>({...column})):[],...snapshot.limits?{limits:{...snapshot.limits}}:{}})}:{snapshot}}function createDraft(s){return deepFreeze({snapshotId:s.id,sourceId:s.sourceId,sourceRevision:s.revision,revision:0,payload:normalize(s.payload,{rules:[]},[]),omissions:[...s.omissions],manuallyEdited:!1,provenance:[{kind:"original",description:"Captured source snapshot"}]})}function revise(d,p,o,description,manual=d.manuallyEdited,kind="deterministic",baseOmissions=d.omissions){let{history:_history,...previous}=d;return deepFreeze({...d,revision:d.revision+1,payload:normalize(p,{rules:[]},[]),omissions:[...baseOmissions,...o],manuallyEdited:manual,provenance:[...d.provenance,{kind,description}],history:[...d.history??[],previous]})}function undoDraft(d){let previous=d.history?.at(-1);return previous?deepFreeze({...previous,revision:d.revision+1,history:d.history.slice(0,-1)}):d}function refreshDraft(draft,snapshot,choice){return choice==="keep"?draft:createDraft(snapshot)}function applySectionSelection(d,s,ids){if(d.snapshotId!==s.id||d.sourceId!==s.sourceId||d.sourceRevision!==s.revision)throw new ContentTransferError("snapshot-mismatch","Section selection requires the draft's captured source snapshot");let selected=new Set(ids),omit=[],paths=s.sections.filter(x=>!selected.has(x.id)).map(x=>(omit.push({path:x.path,reason:"excluded"}),x.path)),baseOmissions=s.omissions;if(s.payload.kind==="json")return revise(d,{kind:"json",value:without(s.payload.value,paths,[])??null},omit,"Selected sections",d.manuallyEdited,"deterministic",baseOmissions);if(s.payload.kind==="registered")return revise(d,{kind:"registered",format:s.payload.format,value:without(s.payload.value,paths,[])??null},omit,"Selected sections",d.manuallyEdited,"deterministic",baseOmissions);if(s.payload.kind==="markdown"||s.payload.kind==="text"){let text=s.payload.text,ranges=paths.map(path=>{let m=/^\/text\/(\d+)-(\d+)$/.exec(path),start=m?Number(m[1]):NaN,end=m?Number(m[2]):NaN;if(!m||start>end||end>text.length)throw new ContentTransferError("invalid-section",`Section "${path}" is not a range of this text. Declare a prose section as /text/<start>-<end> within the text.`);return[start,end]}).sort((a,b)=>b[0]-a[0]),kept=text;for(let[start,end]of ranges)kept=kept.slice(0,start)+kept.slice(end);return revise(d,{...s.payload,text:kept},omit,"Selected sections",d.manuallyEdited,"deterministic",baseOmissions)}return revise(d,s.payload,omit,"Selected sections",d.manuallyEdited,"deterministic",baseOmissions)}function transformRows(d,o){if(d.payload.kind!=="rows")return d;o.top!=null&&assertLimit(o.top,"maxRows");let cols=o.visibleColumns?o.visibleColumns.map(id=>d.payload.kind==="rows"?d.payload.columns.find(c=>c.id===id):void 0).filter(c=>!!c):d.payload.columns.filter(c=>c.visible),get=readTransferCell,rows=[...d.payload.rows],omit=[],before=rows.length;if(o.selectedIndices!==void 0){let selected=new Set;for(let index of o.selectedIndices){if(!Number.isSafeInteger(index)||index<0||index>=d.payload.rows.length)throw new ContentTransferError("invalid-selection-index","Selected row indexes must be non-negative positions in the input draft rows");selected.add(index)}rows=d.payload.rows.filter((_,index)=>selected.has(index))}if(o.selectedIds&&o.idColumn){let set=new Set(o.selectedIds),idColumn=d.payload.columns.find(c=>c.id===o.idColumn);rows=rows.filter(r=>set.has(String(idColumn?get(r,idColumn):r[o.idColumn])))}if(o.search){let q=o.search.toLowerCase();rows=rows.filter(r=>cols.some(c=>String(get(r,c)??"").toLowerCase().includes(q)))}for(let[id,q]of Object.entries(o.filters??{})){let c=cols.find(x=>x.id===id);c&&(rows=rows.filter(r=>String(get(r,c)??"").toLowerCase().includes(q.toLowerCase())))}if(rows.length!==before&&omit.push({path:"/rows",reason:"filtered",count:before-rows.length}),o.sort){let c=cols.find(x=>x.id===o.sort.column);c&&rows.sort((a,b)=>{let left=get(a,c),right=get(b,c);return(typeof left=="number"&&typeof right=="number"?left-right:String(left??"").localeCompare(String(right??"")))*(o.sort.direction==="asc"?1:-1)})}if(o.top!=null&&rows.length>o.top&&(omit.push({path:"/rows",reason:"truncated",count:rows.length-o.top}),rows=rows.slice(0,o.top)),o.structuredProjection==="visible"){rows=rows.map(r=>Object.fromEntries(cols.map(c=>[c.id,get(r,c)??null])));let excludedColumns=d.payload.columns.length-cols.length;excludedColumns>0&&omit.push({path:"/columns",reason:"excluded",count:excludedColumns})}return revise(d,{kind:"rows",rows,columns:cols.map(c=>({...c,visible:!0,...o.structuredProjection==="visible"?{path:`/${enc(c.id)}`}:{}}))},omit,"Prepared row subset")}function reduceJson(draft,options){if(draft.payload.kind!=="json"&&draft.payload.kind!=="registered")return draft;let omissions=[];options.exclude?.forEach(validatePointer);let filtered=without(clone(draft.payload.value),options.exclude??[],omissions)??null,payload=limitPayload({...draft.payload,value:filtered},options,omissions);return revise(draft,payload,omissions,"Reduced JSON")}async function collectAllMatching(c,signal){let rows=[],omissions=[],ids=new Set,cursors=new Set,cursor=null,token,last={status:"unknown",included:0,total:null},certifiedTotal,maxRows=c.limits?.maxRows;maxRows!=null&&assertLimit(maxRows,"maxRows");let finishAtLimit=(total,knownOmitted)=>({rows:deepFreeze(rows),omissions:deepFreeze([...omissions,{path:"/rows",reason:"truncated",...knownOmitted===void 0||knownOmitted<=0?{}:{count:knownOmitted}}]),coverage:deepFreeze({status:"partial",included:rows.length,total,reason:"Source export limit applied"})});try{if(maxRows===0)return finishAtLimit(null);do{stop(signal);let page=await c.source.page({query:c.source.query,cursor,consistencyToken:token??null,signal});if(stop(signal),token===void 0)token=page.consistencyToken;else if(page.consistencyToken!==token)throw new ContentTransferError("consistency-token-changed","All-matching export changed during collection");if(page.coverage.included!==page.rows.length)throw new ContentTransferError("invalid-page-coverage","Page count does not match returned rows");if(page.coverage.total!==null&&(!Number.isSafeInteger(page.coverage.total)||page.coverage.total<0))throw new ContentTransferError("invalid-page-coverage","Page total must be a non-negative integer or null");if(certifiedTotal===void 0)certifiedTotal=page.coverage.total;else if(page.coverage.total!==certifiedTotal)throw new ContentTransferError("inconsistent-total","All-matching source changed its reported total during collection");let projected=normalize({kind:"rows",rows:page.rows,columns:[...c.columns]},c.projection,omissions).rows,uniqueBeyondLimit=0;for(let row of projected){let id=c.source.getRowId(row);if(!id)throw new ContentTransferError("invalid-row-id","All-matching source returned empty projected ID");ids.has(id)?omissions.push({path:`/rows/${enc(id)}`,reason:"duplicate"}):(ids.add(id),maxRows==null||rows.length<maxRows?rows.push(limitPayload({kind:"rows",rows:[row],columns:[...c.columns]},{...c.limits,maxRows:null},omissions).rows[0]):uniqueBeyondLimit+=1)}if(page.coverage.total!==null&&page.coverage.total<ids.size)throw new ContentTransferError("invalid-page-coverage","Page total is smaller than the accumulated unique row count");if(last=page.coverage,maxRows!=null&&rows.length>=maxRows&&(uniqueBeyondLimit>0||page.nextCursor!==null))return finishAtLimit(page.coverage.total,page.nextCursor===null?uniqueBeyondLimit:page.coverage.total!=null&&page.coverage.total>rows.length?page.coverage.total-rows.length:void 0);if(cursor=page.nextCursor,cursor!==null&&(!cursor||cursors.has(cursor)))throw new ContentTransferError("non-advancing-cursor","All-matching source repeated a cursor");cursor&&cursors.add(cursor)}while(cursor!==null);let complete=c.source.stableSnapshot===!0&&last.status==="complete"&&last.total===rows.length&&token!==void 0;return{rows:deepFreeze(rows),omissions:deepFreeze(omissions),coverage:deepFreeze(complete?{...last,included:rows.length}:{...last,status:"partial",included:rows.length,reason:last.reason??"Source did not certify a stable complete snapshot"})}}catch(e){let error=e instanceof ContentTransferError?e:new ContentTransferError(signal.aborted?"cancelled":"page-failed",e instanceof Error?e.message:"Page collection failed");return{rows:deepFreeze(rows),omissions:deepFreeze(omissions),coverage:deepFreeze({status:"partial",included:rows.length,total:last.total,reason:error.message}),error}}}function sealTransferArtifact(artifact){if(!artifact.file)return deepFreeze({...artifact,omissions:artifact.omissions.map(o=>({...o}))});let bytes=artifact.file.bytes.slice(),file={filename:artifact.file.filename,mime:artifact.file.mime,get bytes(){return bytes.slice()}};return deepFreeze({...artifact,file,omissions:artifact.omissions.map(o=>({...o}))})}function exportedColumns(columns){return columns.filter(c=>c.visible&&c.exportable!==!1&&c.classification!=="secret"&&c.classification!=="credential")}function serialize(draft,format,options={}){let payload=draft.payload,omissions=draft.omissions.map(o=>({...o})),plainText="",html,mime="text/plain;charset=utf-8",extension="txt",columnCell=(row,column)=>textValue(readTransferCell(row,column));if((format==="csv"||format==="tsv")&&payload.kind!=="rows")throw new ContentTransferError("unsupported-format",`${format.toUpperCase()} requires tabular data`);if(format==="json"||format==="compact-json"){let value=payload.kind==="rows"?payload.rows:payload.kind==="text"||payload.kind==="markdown"?payload.text:payload.value;plainText=stringifyJson(value,{style:format==="json"?"pretty":"compact"}),mime="application/json;charset=utf-8",extension="json"}else if(payload.kind==="rows"){let columns=exportedColumns(payload.columns);if(format==="markdown"){let escapeCell=value=>escapeHtml(value).replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\r\n|\r|\n/g,"<br>");plainText=[`| ${columns.map(c=>escapeCell(c.label)).join(" | ")} |`,`| ${columns.map(()=>"---").join(" | ")} |`,...payload.rows.map(row=>`| ${columns.map(c=>escapeCell(columnCell(row,c))).join(" | ")} |`)].join(`
|
|
@@ -20,5 +24,5 @@ ${summary}<data format="json">
|
|
|
20
24
|
`;)i++;spans.push({path,start,end:i});let last=index===paths.length-1,expected=last?`
|
|
21
25
|
`:delimiter;if(!(last&&i===text.length)){if(text[i]!==expected)throw spanError(`Expected ${last?"a line break":"a delimiter"} at character ${i}.`);last||i++}}),linePath!==null&&(spans[lineSlot].end=i),i<text.length&&i++};readLine(columns.map(c=>`/columns/${pointerSegment(c.id)}`),null);for(let row=0;row<rowCount;row++)readLine(columns.map(c=>`/rows/${row}${c.path}`),`/rows/${row}`);if(i<text.length)throw spanError(`Text continues after the last row at character ${i}.`);return spans}function markdownTableSpans(text,columns,rowCount){let spans=[],lines=[],at2=0;for(let line of text.split(`
|
|
22
26
|
`))lines.push({start:at2,end:at2+line.length}),at2+=line.length+1;if(lines.length!==rowCount+2)throw spanError(`A Markdown table of ${rowCount} rows has ${lines.length} lines.`);let cells=(line,paths)=>{let i=line.start;if(text.slice(i,i+2)!=="| ")throw spanError(`A table line must open with "| " at character ${i}.`);if(i+=2,paths.forEach(path=>{let start=i;for(;i<line.end&&text[i]!=="|";)i+=text[i]==="\\"?2:1;if(text[i]!=="|"||text[i-1]!==" ")throw spanError(`A table cell must close with " |" at character ${i}.`);spans.push({path,start,end:i-1}),i+=2}),i-1!==line.end)throw spanError(`A table line has more cells than columns at character ${i}.`)};cells(lines[0],columns.map(c=>`/columns/${pointerSegment(c.id)}`));for(let row=0;row<rowCount;row++){let line=lines[row+2];spans.push({path:`/rows/${row}`,start:line.start,end:line.end}),cells(line,columns.map(c=>`/rows/${row}${c.path}`))}return spans}function spanMap(draft,artifact){if(artifact.snapshotId!==draft.snapshotId||artifact.draftRevision!==draft.revision)throw spanError("This artifact was built from a different draft, so its spans cannot be read from this one. Seal the current draft again.");let text=artifact.plainText,payload=draft.payload,format=artifact.format;if(format==="json"||format==="compact-json")return jsonTextSpans(text,payload.kind==="rows"?"/rows":"");if(format==="csv"||format==="tsv"){if(payload.kind!=="rows")throw spanError(`${format.toUpperCase()} requires tabular data`);return delimitedSpans(text,format==="csv"?",":" ",exportedColumns(payload.columns),payload.rows.length)}if(format!=="plain"&&format!=="markdown"&&format!=="html")throw spanError(`The ${format} format has no text span map; spans cover plain, Markdown, JSON, CSV and TSV text.`);if(payload.kind==="rows"){let columns=exportedColumns(payload.columns);return format==="markdown"?markdownTableSpans(text,columns,payload.rows.length):delimitedSpans(text," ",columns,payload.rows.length)}if(payload.kind==="json"||payload.kind==="registered")return jsonTextSpans(text);if(payload.kind==="text"&&payload.language&&format==="markdown"){if(fencedCodeBlock(payload.text,payload.language)!==text)throw spanError("The Markdown code block does not hold this draft's text.");let start=text.indexOf(`
|
|
23
|
-
`)+1;return[{path:"",start,end:start+payload.text.length}]}return[{path:"",start:0,end:text.length}]}function offsetSpans(spans,offset){return spans.map(s=>({path:s.path,start:s.start+offset,end:s.end+offset}))}function agentPayloadWithSpans(input,environment={}){let{text,body,bodyOffset}=assembleAgentPayload(input,environment);return{text,spans:jsonTextSpans(body,"",bodyOffset)}}init_core();var TRANSFER_DEFAULT_RECIPE_SETTING="alchemy.transfer.default_recipe",KEY=/^[a-z0-9][a-z0-9._:-]{0,127}$/;function recipeKey(sourceKind){if(!KEY.test(sourceKind))throw new ContentTransferError("invalid-recipe-key",`"${sourceKind}" is not a source-kind id (lowercase letters, digits and . _ : -, up to 128 characters).`);return sourceKind}var isRecord=v=>v!==null&&typeof v=="object"&&!Array.isArray(v);async function resolveDefaultRecipe(ports,sourceKind,organizationId){let key=recipeKey(sourceKind),notices=[],skip=(error,sentence,remedy)=>{notices.push({sentence,remedy}),ports.diagnostics.capture(error,{area:"operate",detail:{recipeKey:key,sentence}})};if(ports.persistence)try{let own=await ports.persistence.readSetting(TRANSFER_DEFAULT_RECIPE_SETTING);if(own!==null){if(!isRecord(own))skip(new Error("person default recipes are not a map"),"Your saved default recipes could not be read (they are not a list of recipes), so they were skipped.","Save your default recipe for this source again.");else if(own[key]!==void 0){let recipe=own[key];if(isRecord(recipe))return{recipe,from:"person",notices};skip(new Error("person default recipe is not an object"),"Your default recipe for this source is not a recipe, so it was skipped.","Save your default recipe for this source again.")}}}catch(error){skip(error,"Your own default recipe could not be read, so the organization's default applies.","Reopen the workspace to try again.")}if(ports.transferKnobs)try{let org=await ports.transferKnobs.defaultRecipe(key,organizationId);if(org!==null){if(isRecord(org))return{recipe:org,from:"organization",notices};skip(new Error("organization default recipe is not an object"),"Your organization's default recipe for this source is not a recipe, so it was skipped.","Ask an organization admin to set the default recipe again.")}}catch(error){skip(error,"Your organization's default recipe could not be read, so the workspace opens on Full.","Reopen the workspace to try again.")}return{recipe:null,from:"built-in",notices}}async function setPersonDefaultRecipe(ports,sourceKind,recipe){let key=recipeKey(sourceKind),persistence=ports.persistence;if(!persistence)throw new ContentTransferError("capability-absent","This app cannot save your own settings, so a personal default recipe is not available here.");let current;try{current=await persistence.readSetting(TRANSFER_DEFAULT_RECIPE_SETTING)}catch(error){let reason=error instanceof Error?error.message:String(error);throw new ContentTransferError("read-failed",`Nothing was saved: your other default recipes could not be read (${reason}), and saving now would have replaced all of them. Try again in a moment.`)}if(current!==null&&!isRecord(current))throw new ContentTransferError("invalid-setting","Nothing was saved: your saved default recipes are not a list of recipes, so one cannot be changed without replacing them all.");let map={...current??{}};if(recipe===null){if(!(key in map))return;delete map[key]}else map[key]=recipe;await persistence.writeSetting(TRANSFER_DEFAULT_RECIPE_SETTING,Object.keys(map).length===0?null:map)}export{ContentTransferError,FORMAT_ADAPTERS,TRANSFER_DEFAULT_RECIPE_SETTING,agentPayloadWithSpans,applySectionSelection,applyTransferLimits,assembleAgentPayload,buildAgentPayload,capture,collectAllMatching,createBrowserTransport,createDelivery,createDraft,createSurfaceTransferHandle,directSource,editDraft,eligibleFormats,exportedColumns,extensionForLanguage,fenceJsonBlock,formatAdapter,isSealed,jsonTextSpans,normalizeTransferJson,offsetSpans,openPreparation,projectSnapshot,readTransferCell,recipeKey,reduceJson,refreshDraft,resetDraft,resolveDefaultRecipe,resolveTransferPreferences,resolveTransferRegistry,sealArtifact,sealDraft,sealTransferArtifact,serialize,setPersonDefaultRecipe,sourceChanged,spanMap,transformRows,undoDraft};
|
|
27
|
+
`)+1;return[{path:"",start,end:start+payload.text.length}]}return[{path:"",start:0,end:text.length}]}function offsetSpans(spans,offset){return spans.map(s=>({path:s.path,start:s.start+offset,end:s.end+offset}))}function agentPayloadWithSpans(input,environment={}){let{text,body,bodyOffset}=assembleAgentPayload(input,environment);return(input.dataFormat??"json")!=="json"?{text,spans:[{path:"",start:bodyOffset,end:bodyOffset+body.length}]}:{text,spans:jsonTextSpans(body,"",bodyOffset)}}init_core();var TRANSFER_DEFAULT_RECIPE_SETTING="alchemy.transfer.default_recipe",KEY=/^[a-z0-9][a-z0-9._:-]{0,127}$/;function recipeKey(sourceKind){if(!KEY.test(sourceKind))throw new ContentTransferError("invalid-recipe-key",`"${sourceKind}" is not a source-kind id (lowercase letters, digits and . _ : -, up to 128 characters).`);return sourceKind}var isRecord=v=>v!==null&&typeof v=="object"&&!Array.isArray(v);async function resolveDefaultRecipe(ports,sourceKind,organizationId){let key=recipeKey(sourceKind),notices=[],skip=(error,sentence,remedy)=>{notices.push({sentence,remedy}),ports.diagnostics.capture(error,{area:"operate",detail:{recipeKey:key,sentence}})};if(ports.persistence)try{let own=await ports.persistence.readSetting(TRANSFER_DEFAULT_RECIPE_SETTING);if(own!==null){if(!isRecord(own))skip(new Error("person default recipes are not a map"),"Your saved default recipes could not be read (they are not a list of recipes), so they were skipped.","Save your default recipe for this source again.");else if(own[key]!==void 0){let recipe=own[key];if(isRecord(recipe))return{recipe,from:"person",notices};skip(new Error("person default recipe is not an object"),"Your default recipe for this source is not a recipe, so it was skipped.","Save your default recipe for this source again.")}}}catch(error){skip(error,"Your own default recipe could not be read, so the organization's default applies.","Reopen the workspace to try again.")}if(ports.transferKnobs)try{let org=await ports.transferKnobs.defaultRecipe(key,organizationId);if(org!==null){if(isRecord(org))return{recipe:org,from:"organization",notices};skip(new Error("organization default recipe is not an object"),"Your organization's default recipe for this source is not a recipe, so it was skipped.","Ask an organization admin to set the default recipe again.")}}catch(error){skip(error,"Your organization's default recipe could not be read, so the workspace opens on Full.","Reopen the workspace to try again.")}return{recipe:null,from:"built-in",notices}}async function setPersonDefaultRecipe(ports,sourceKind,recipe){let key=recipeKey(sourceKind),persistence=ports.persistence;if(!persistence)throw new ContentTransferError("capability-absent","This app cannot save your own settings, so a personal default recipe is not available here.");let current;try{current=await persistence.readSetting(TRANSFER_DEFAULT_RECIPE_SETTING)}catch(error){let reason=error instanceof Error?error.message:String(error);throw new ContentTransferError("read-failed",`Nothing was saved: your other default recipes could not be read (${reason}), and saving now would have replaced all of them. Try again in a moment.`)}if(current!==null&&!isRecord(current))throw new ContentTransferError("invalid-setting","Nothing was saved: your saved default recipes are not a list of recipes, so one cannot be changed without replacing them all.");let map={...current??{}};if(recipe===null){if(!(key in map))return;delete map[key]}else map[key]=recipe;await persistence.writeSetting(TRANSFER_DEFAULT_RECIPE_SETTING,Object.keys(map).length===0?null:map)}export{ContentTransferError,FORMAT_ADAPTERS,TRANSFER_DEFAULT_RECIPE_SETTING,agentPayloadWithSpans,applySectionSelection,applyTransferLimits,assembleAgentPayload,buildAgentPayload,capture,collectAllMatching,createBrowserTransport,createDelivery,createDraft,createSurfaceTransferHandle,directSource,editDraft,eligibleFormats,exportedColumns,extensionForLanguage,fenceJsonBlock,formatAdapter,isSealed,jsonTextSpans,normalizeTransferJson,offsetSpans,openPreparation,projectSnapshot,readTransferCell,recipeKey,reduceJson,refreshDraft,resetDraft,resolveDefaultRecipe,resolveTransferPreferences,resolveTransferRegistry,sealArtifact,sealDraft,sealTransferArtifact,serialize,setPersonDefaultRecipe,sourceChanged,spanMap,transformRows,undoDraft};
|
|
24
28
|
//# sourceMappingURL=operate.js.map
|