fms-odata-js 0.4.0 → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -5,7 +5,28 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [0.4.0] — 2025-01-09
8
+ ## [0.4.1] — 2026-10-27
9
+
10
+ ### Fixed — Script invocation envelope (#9)
11
+
12
+ `db.script()` / `scriptById()` now match the FileMaker Server OData script
13
+ contract, verified live against FileMaker Server 2026.
14
+
15
+ - **Request field:** the optional `parameter` is sent as
16
+ `{ "scriptParameterValue": ... }` (the only field name FMS accepts; the
17
+ previously documented `scriptParameter` is rejected with code `-1053`).
18
+ The `parameter` option now accepts `string | number | object`.
19
+ - **Nested response envelope (FMS v26+):** FMS 2026 replies with
20
+ `{ "scriptResult": { "code": 0, "resultParameter": "...", "message": "..." } }`.
21
+ The parser now reads this shape: a non-zero `code` throws `FMScriptError`
22
+ with `scriptError = code`, `scriptResult = resultParameter`, and the FMS
23
+ `message` included in the error text. Previously the nested object was
24
+ stringified to `"[object Object]"` and failures were reported as success.
25
+ - **Legacy envelope kept:** the flat `{ "scriptResult": "...", "scriptError": "0" }`
26
+ shape from older FMS versions is still accepted.
27
+ - **Docs:** wiki script pages updated to the `scriptParameterValue` field name
28
+ and the nested envelope; outdated `scriptParameter` references removed.
29
+
9
30
 
10
31
  ### Fixed — DDL and webhook API alignment with real FileMaker Server
11
32
 
@@ -41,7 +62,7 @@ rejects; both modules now match the actual server behavior.
41
62
  tables and webhooks are created and cleaned up; production tables are
42
63
  never touched.
43
64
 
44
- ### Changed — Spec alignment with `@fms-odata/spec-ts` 2.0.0
65
+ ### Changed — Spec alignment with `@fms-odata/spec-ts` 2.0
45
66
 
46
67
  Bumped the shared spec dependency from `^1.1.0` to `^2.0.1` and aligned the
47
68
  client with the v2.0.0 spec overhaul (drop FileMaker 19.x, corrected version
package/README.md CHANGED
@@ -4,16 +4,17 @@
4
4
 
5
5
  **A tiny, type-safe OData v4 client built for FileMaker Server.**
6
6
 
7
- Zero runtime dependencies · ~10.6 KB gzipped · ESM + IIFE · Web Viewer / Browser / Node 18+
7
+ Zero runtime dependencies · ~11.1 KB gzipped · ESM + IIFE · Web Viewer / Browser / Node 18+
8
8
 
9
9
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.5-3178c6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
10
10
  [![OData](https://img.shields.io/badge/OData-v4-0078D4?logo=data&logoColor=white)](https://www.odata.org/)
11
- [![FileMaker](https://img.shields.io/badge/FileMaker-19.0--26.0-FF6B00?logo=filemaker&logoColor=white)](https://www.claris.com/filemaker/)
12
- [![Bundle](https://img.shields.io/badge/gzip-~10.6%20KB-brightgreen)](#)
11
+ [![FileMaker](https://img.shields.io/badge/FileMaker-20.0--26.0-FF6B00?logo=filemaker&logoColor=white)](https://www.claris.com/filemaker/)
12
+ [![Bundle](https://img.shields.io/badge/gzip-~11.1%20KB-brightgreen)](#)
13
13
  [![Deps](https://img.shields.io/badge/runtime%20deps-0-blue)](#)
14
14
  [![Node](https://img.shields.io/badge/node-%3E%3D18-339933?logo=node.js&logoColor=white)](#)
15
15
  [![License](https://img.shields.io/badge/license-MIT-black)](./LICENSE)
16
16
  [![Spec](https://img.shields.io/badge/spec-fms--odata--spec-FF6B00?logo=filemaker&logoColor=white)](https://github.com/fsans/fms-odata-spec)
17
+ [![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-6E56CF)](https://deepwiki.com/fsans/fms-odata-js)
17
18
 
18
19
  </div>
19
20
 
@@ -25,20 +26,20 @@ FileMaker Server speaks OData v4, but the spec has sharp corners and FMS has qui
25
26
 
26
27
  > **Battle-tested in production.** I've been using this library heavily to let FileMaker Web Viewer instances talk to the *same* hosted database they live in — and the performance has been genuinely impressive. Queries that used to require round-tripping through scripts and set-field loops now resolve in a single OData call, with noticeably lower latency and a much cleaner code path. If you're building rich Web Viewer UIs backed by FMS, this is the fastest route I've found.
27
28
 
28
- - **Tiny.** ESM and IIFE bundles, zero runtime dependencies, ~10.6 KB gzipped.
29
+ - **Tiny.** ESM and IIFE bundles, zero runtime dependencies, ~11.1 KB gzipped.
29
30
  - **Type-safe.** Fluent, chainable query builder with full TS inference.
30
31
  - **Runs anywhere.** Drop it into a FileMaker Web Viewer, a browser, or Node 18+.
31
32
  - **FMS-aware.** Handles the documented FMS OData deviations for you.
32
- - **Version-aware.** Detects the FileMaker Server major version (19, 21, 22, 26) from `$metadata` and gates features accordingly.
33
+ - **Version-aware.** Detects the FileMaker Server major version (20, 21, 22, 26) from `$metadata` and gates features accordingly.
33
34
  - **Scripts built in.** Invoke FileMaker scripts at database, entity-set, or record scope — by name or by immutable FMSID (v26+).
34
35
  - **Containers built in.** Upload, download, stream, or clear container fields with typed helpers — `Blob`, `ArrayBuffer`, and `Uint8Array` all accepted.
35
36
  - **Aggregations.** `$apply` builder for `aggregate()` and `groupBy()` — server-side sum, average, min, max, count (FMS 2024+).
36
37
  - **Navigation properties.** Full `$ref` CRUD — `getRefs`, `addRef`, `setRef`, `removeRef` for OData relationship links.
37
38
  - **Schema introspection.** `$metadata` parsed into typed `ODataMetadata` with entity types, keys, properties, and actions. Cached by default.
38
39
  - **Schema editing (DDL).** Create/delete tables, add/delete fields, create/delete indexes via the `FileMaker_Tables` and `FileMaker_Indexes` system endpoints. Field types validated against the spec; destructive ops guarded by `confirm: true`.
39
- - **Webhooks.** Create, remove, get, list, and manually invoke webhooks (FMS 2023+ / v21) with typed params and `endpointHeaders` / `queryHeaders` support.
40
+ - **Webhooks.** Create, remove, get, list, and manually invoke webhooks (FMS 2025+ / v22) with typed params and `endpointHeaders` / `queryHeaders` support.
40
41
  - **Batch requests.** `$batch` builder composes multiple reads and atomic changesets (POST / PATCH / DELETE) into a single HTTP round-trip.
41
- - **Multi-auth.** Basic, Bearer, and FMID (FileMaker Cloud / Claris ID) auth with 401 retry, `AbortSignal`, and timeouts built in.
42
+ - **Multi-auth.** Basic and Bearer (OAuth / FileMaker Cloud) auth with 401 retry, `AbortSignal`, and timeouts built in.
42
43
  - **Honest errors.** Every failure becomes a normalized `FMSODataError` (or `FMScriptError` for script failures) with `isFMSODataError` / `isFMScriptError` type guards.
43
44
 
44
45
  ## Status
@@ -73,7 +74,7 @@ Local dev:
73
74
 
74
75
  ```bash
75
76
  npm install
76
- npm test # 227 unit tests, offline
77
+ npm test # 274 unit tests, offline
77
78
  ```
78
79
 
79
80
  ## Quick start
@@ -88,9 +89,9 @@ const db = new FMSOData({
88
89
  timeoutMs: 15_000,
89
90
  })
90
91
 
91
- // For FileMaker Cloud, use FMID auth instead:
92
- // import { fmidAuth } from 'fms-odata-js'
93
- // token: fmidAuth(clarisIdToken)
92
+ // For FileMaker Cloud, use Bearer auth instead:
93
+ // import { bearerAuth } from 'fms-odata-js'
94
+ // token: bearerAuth(oauthToken)
94
95
 
95
96
  // Collection read
96
97
  const { value, count } = await db
@@ -378,7 +379,7 @@ length in parentheses (`VARCHAR(200)`). Destructive operations (`deleteTable`,
378
379
 
379
380
  ## Webhooks
380
381
 
381
- Manage FileMaker Server webhooks — requires FMS 2023+ (v21). Use
382
+ Manage FileMaker Server webhooks — requires FMS 2025+ (v22). Use
382
383
  `hasFeature('webhooks')` to check before calling.
383
384
 
384
385
  ```ts
@@ -1429,17 +1429,19 @@ function parseScriptEnvelope(raw, request) {
1429
1429
  const rawResult = envelope.scriptResult;
1430
1430
  let scriptResult;
1431
1431
  let scriptError;
1432
- if (rawResult !== null && typeof rawResult === "object" && "resultParameter" in rawResult) {
1432
+ let fmsMessage;
1433
+ if (rawResult !== null && typeof rawResult === "object" && ("code" in rawResult || "resultParameter" in rawResult)) {
1433
1434
  const nested = rawResult;
1434
1435
  scriptError = nested.code !== void 0 ? String(nested.code) : "0";
1435
- scriptResult = nested.resultParameter !== void 0 ? String(nested.resultParameter) : void 0;
1436
+ scriptResult = nested.resultParameter !== void 0 ? typeof nested.resultParameter === "string" ? nested.resultParameter : JSON.stringify(nested.resultParameter) : void 0;
1437
+ if (typeof nested.message === "string") fmsMessage = nested.message;
1436
1438
  } else {
1437
1439
  scriptError = envelope.scriptError !== void 0 ? String(envelope.scriptError) : "0";
1438
1440
  scriptResult = rawResult !== void 0 ? typeof rawResult === "string" ? rawResult : JSON.stringify(rawResult) : void 0;
1439
1441
  }
1440
1442
  if (scriptError !== "0") {
1441
1443
  throw new FMScriptError(
1442
- `FileMaker script error ${scriptError}`,
1444
+ fmsMessage ? `FileMaker script error ${scriptError}: ${fmsMessage}` : `FileMaker script error ${scriptError}`,
1443
1445
  {
1444
1446
  status: 200,
1445
1447
  scriptError,
@@ -1,6 +1,6 @@
1
- var y=class extends Error{constructor(e,t){super(e),this.name="FMSODataError",this.status=t.status,t.code!==void 0&&(this.code=t.code),t.odataError!==void 0&&(this.odataError=t.odataError),t.request!==void 0&&(this.request=t.request)}};async function Q(r,e){let t=r.status,n="";try{n=await r.text()}catch{}let i,o=r.statusText||`HTTP ${t}`,s=n,a=(r.headers.get("content-type")??"").toLowerCase(),c=a.includes("json")||n.startsWith("{")&&n.endsWith("}"),d=a.includes("xml")||n.trimStart().startsWith("<?xml")||n.includes("<m:error");if(c)try{let l=JSON.parse(n);s=l;let h=l?.error?.code,g=l?.error?.message,M=typeof g=="string"?g:g?.value;h&&(i=String(h)),M&&(o=M)}catch{}else if(d){let l=n.match(/<m:code>([^<]+)<\/m:code>/),h=n.match(/<m:message(?:\s[^>]*)?>([^<]+)<\/m:message>/);l?.[1]&&(i=l[1]),h?.[1]&&(o=h[1])}return new y(o,{status:t,...i!==void 0?{code:i}:{},odataError:s,request:e})}var _=class extends y{constructor(e,t){super(e,{status:t.status,code:t.scriptError,...t.odataError!==void 0?{odataError:t.odataError}:{},...t.request!==void 0?{request:t.request}:{}}),this.name="FMScriptError",this.scriptError=t.scriptError,t.scriptResult!==void 0&&(this.scriptResult=t.scriptResult)}};function z(r){return r instanceof y}function pe(r){return r instanceof _}var le=/^(basic|bearer|negotiate|digest)\s+\S/i;async function fe(r){let e=typeof r=="function"?await r():r;if(typeof e!="string"||e.length===0)throw new TypeError("fms-odata-js: token resolver produced an empty value");return le.test(e)?e:`Bearer ${e}`}function he(r,e){let t=`${r}:${e}`;return`Basic ${typeof Buffer<"u"?Buffer.from(t,"utf8").toString("base64"):btoa(unescape(encodeURIComponent(t)))}`}function me(r){return`Bearer ${r}`}function ge(r){let e=r.filter(n=>n!==void 0);if(e.length===0)return;if(e.length===1)return e[0];let t=new AbortController;for(let n of e){if(n.aborted)return t.abort(n.reason),t.signal;n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}var ye={json:"application/json",xml:"application/xml",text:"text/plain",binary:"application/octet-stream",none:"*/*"};async function m(r,e,t={}){return Y(r,e,t,!1)}async function Y(r,e,t,n){let i=t.method??"GET",o=new Headers(t.headers);o.set("Authorization",await fe(r.token)),o.has("OData-Version")||o.set("OData-Version","4.0"),o.has("OData-MaxVersion")||o.set("OData-MaxVersion","4.0"),o.has("Accept")||o.set("Accept",ye[t.accept??"json"]);let s=new AbortController,a=r.timeoutMs&&r.timeoutMs>0?setTimeout(()=>s.abort(new Error(`Timeout after ${r.timeoutMs}ms`)),r.timeoutMs):void 0,c=ge([t.signal,r.timeoutMs?s.signal:void 0]),d;try{d=await r.fetch(e,{method:i,headers:o,keepalive:!0,...t.body!==void 0?{body:t.body}:{},...c?{signal:c}:{}})}catch(l){throw a&&clearTimeout(a),l}if(a&&clearTimeout(a),d.status===401&&r.onUnauthorized&&!n)return await r.onUnauthorized(),Y(r,e,t,!0);if(!d.ok)throw await Q(d,{url:e,method:i});return d}async function p(r,e,t={}){let n=await m(r,e,t);if(n.status===204)return;let i=(n.headers.get("content-type")??"").toLowerCase();if(!i.includes("json")){let o=await n.text();if(!o)return;try{return JSON.parse(o)}catch{throw new y(`Expected JSON response, got "${i||"no content-type"}"`,{status:n.status,odataError:o,request:{url:e,method:t.method??"GET"}})}}return await n.json()}function x(r){return r.replace(/'/g,"''")}function be(r){if(!(r instanceof Date)||Number.isNaN(r.getTime()))throw new TypeError("formatDateTime: invalid Date");return r.toISOString().replace(/\.\d{3}Z$/,"Z")}function b(r){if(r==null)return"null";if(typeof r=="string")return`'${x(r)}'`;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`formatLiteral: cannot encode non-finite number: ${r}`);return String(r)}if(typeof r=="boolean")return r?"true":"false";if(r instanceof Date)return be(r);throw new TypeError(`formatLiteral: unsupported OData literal type: ${typeof r}`)}function u(r){return encodeURIComponent(r)}function O(r){return encodeURIComponent(r).replace(/%2C/gi,",").replace(/%24/g,"$").replace(/%3D/g,"=").replace(/%3B/g,";").replace(/%28/g,"(").replace(/%29/g,")")}function Z(r){let e=[];for(let[t,n]of r)n===""||n===void 0||n===null||e.push(`${t}=${O(n)}`);return e.join("&")}function Se(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).byteLength:Buffer.byteLength(r,"utf8")}function X(r){let e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return`${r}_${e}`}function ee(r,e,t){let n=[];t?.$top!==void 0&&n.push(`$top=${O(String(t.$top))}`),t?.$skip!==void 0&&n.push(`$skip=${O(String(t.$skip))}`),t?.$filter&&n.push(`$filter=${O(t.$filter)}`),t?.$select&&n.push(`$select=${O(t.$select)}`);let i=n.join("&"),o=u(e);return i?`${r}/${o}?${i}`:`${r}/${o}`}function K(r,e,t){let n=u(e),i;if(typeof t=="number")i=String(t);else if(typeof t=="string")i=`'${t.replace(/'/g,"''")}'`;else if(typeof t=="boolean")i=t?"true":"false";else throw new TypeError("Batch: unsupported key type");return`${r}/${n}(${i})`}var U=class{constructor(e){this._ops=[];this._handles=[];this._baseUrl=e}get _operations(){return this._ops}get _handleSlots(){return this._handles}create(e,t){let n=ee(this._baseUrl,e),i,o,s=new Promise((c,d)=>{i=c,o=d}),a=this._handles.length;return this._handles.push({resolve:i,reject:o}),this._ops.push({method:"POST",path:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{__brand:"BatchHandle",_promise:s,_index:a}}patch(e,t,n,i){let o=K(this._baseUrl,e,t),s={"Content-Type":"application/json"};i?.ifMatch&&(s["If-Match"]=i.ifMatch);let a,c,d=new Promise((h,g)=>{a=h,c=g}),l=this._handles.length;return this._handles.push({resolve:a,reject:c}),this._ops.push({method:"PATCH",path:o,headers:s,body:JSON.stringify(n)}),{__brand:"BatchHandle",_promise:d,_index:l}}delete(e,t,n){let i=K(this._baseUrl,e,t),o={};n?.ifMatch&&(o["If-Match"]=n.ifMatch);let s,a,c=new Promise((l,h)=>{s=l,a=h}),d=this._handles.length;return this._handles.push({resolve:s,reject:a}),this._ops.push({method:"DELETE",path:i,headers:o}),{__brand:"BatchHandle",_promise:c,_index:d}}},F=class{constructor(e){this._parts=[];this._changesets=[];this._client=e}add(e){let t=ee(this._client.baseUrl,e.entitySet,e.query),n,i,s={__brand:"BatchHandle",_promise:new Promise((a,c)=>{n=a,i=c}),_index:this._parts.length};return this._parts.push({type:"read",content:{method:"GET",path:t},handle:s}),s}changeset(e){let t=new U(this._client.baseUrl);e(t),this._changesets.push(t),this._parts.push({type:"changeset",content:t})}_serialize(){let e=X("batch"),t=[];for(let n of this._parts)if(t.push(`--${e}`),n.type==="read"){let i=n.content;t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${i.method} ${i.path} HTTP/1.1`)}else if(n.type==="changeset"){let i=n.content,o=X("changeset");t.push("Content-Type: multipart/mixed; boundary="+o),t.push("");for(let s of i._operations){if(t.push(`--${o}`),t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${s.method} ${s.path} HTTP/1.1`),s.headers)for(let[a,c]of Object.entries(s.headers))t.push(`${a}: ${c}`);s.body&&(t.push(`Content-Length: ${Se(s.body)}`),t.push(""),t.push(s.body))}t.push(`--${o}--`)}return t.push(`--${e}--`),{boundary:e,body:t.join(`\r
1
+ var y=class extends Error{constructor(e,t){super(e),this.name="FMSODataError",this.status=t.status,t.code!==void 0&&(this.code=t.code),t.odataError!==void 0&&(this.odataError=t.odataError),t.request!==void 0&&(this.request=t.request)}};async function Q(r,e){let t=r.status,n="";try{n=await r.text()}catch{}let i,o=r.statusText||`HTTP ${t}`,s=n,a=(r.headers.get("content-type")??"").toLowerCase(),c=a.includes("json")||n.startsWith("{")&&n.endsWith("}"),d=a.includes("xml")||n.trimStart().startsWith("<?xml")||n.includes("<m:error");if(c)try{let l=JSON.parse(n);s=l;let h=l?.error?.code,g=l?.error?.message,M=typeof g=="string"?g:g?.value;h&&(i=String(h)),M&&(o=M)}catch{}else if(d){let l=n.match(/<m:code>([^<]+)<\/m:code>/),h=n.match(/<m:message(?:\s[^>]*)?>([^<]+)<\/m:message>/);l?.[1]&&(i=l[1]),h?.[1]&&(o=h[1])}return new y(o,{status:t,...i!==void 0?{code:i}:{},odataError:s,request:e})}var O=class extends y{constructor(e,t){super(e,{status:t.status,code:t.scriptError,...t.odataError!==void 0?{odataError:t.odataError}:{},...t.request!==void 0?{request:t.request}:{}}),this.name="FMScriptError",this.scriptError=t.scriptError,t.scriptResult!==void 0&&(this.scriptResult=t.scriptResult)}};function z(r){return r instanceof y}function pe(r){return r instanceof O}var le=/^(basic|bearer|negotiate|digest)\s+\S/i;async function fe(r){let e=typeof r=="function"?await r():r;if(typeof e!="string"||e.length===0)throw new TypeError("fms-odata-js: token resolver produced an empty value");return le.test(e)?e:`Bearer ${e}`}function he(r,e){let t=`${r}:${e}`;return`Basic ${typeof Buffer<"u"?Buffer.from(t,"utf8").toString("base64"):btoa(unescape(encodeURIComponent(t)))}`}function me(r){return`Bearer ${r}`}function ge(r){let e=r.filter(n=>n!==void 0);if(e.length===0)return;if(e.length===1)return e[0];let t=new AbortController;for(let n of e){if(n.aborted)return t.abort(n.reason),t.signal;n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}var ye={json:"application/json",xml:"application/xml",text:"text/plain",binary:"application/octet-stream",none:"*/*"};async function m(r,e,t={}){return Y(r,e,t,!1)}async function Y(r,e,t,n){let i=t.method??"GET",o=new Headers(t.headers);o.set("Authorization",await fe(r.token)),o.has("OData-Version")||o.set("OData-Version","4.0"),o.has("OData-MaxVersion")||o.set("OData-MaxVersion","4.0"),o.has("Accept")||o.set("Accept",ye[t.accept??"json"]);let s=new AbortController,a=r.timeoutMs&&r.timeoutMs>0?setTimeout(()=>s.abort(new Error(`Timeout after ${r.timeoutMs}ms`)),r.timeoutMs):void 0,c=ge([t.signal,r.timeoutMs?s.signal:void 0]),d;try{d=await r.fetch(e,{method:i,headers:o,keepalive:!0,...t.body!==void 0?{body:t.body}:{},...c?{signal:c}:{}})}catch(l){throw a&&clearTimeout(a),l}if(a&&clearTimeout(a),d.status===401&&r.onUnauthorized&&!n)return await r.onUnauthorized(),Y(r,e,t,!0);if(!d.ok)throw await Q(d,{url:e,method:i});return d}async function p(r,e,t={}){let n=await m(r,e,t);if(n.status===204)return;let i=(n.headers.get("content-type")??"").toLowerCase();if(!i.includes("json")){let o=await n.text();if(!o)return;try{return JSON.parse(o)}catch{throw new y(`Expected JSON response, got "${i||"no content-type"}"`,{status:n.status,odataError:o,request:{url:e,method:t.method??"GET"}})}}return await n.json()}function x(r){return r.replace(/'/g,"''")}function be(r){if(!(r instanceof Date)||Number.isNaN(r.getTime()))throw new TypeError("formatDateTime: invalid Date");return r.toISOString().replace(/\.\d{3}Z$/,"Z")}function b(r){if(r==null)return"null";if(typeof r=="string")return`'${x(r)}'`;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`formatLiteral: cannot encode non-finite number: ${r}`);return String(r)}if(typeof r=="boolean")return r?"true":"false";if(r instanceof Date)return be(r);throw new TypeError(`formatLiteral: unsupported OData literal type: ${typeof r}`)}function u(r){return encodeURIComponent(r)}function _(r){return encodeURIComponent(r).replace(/%2C/gi,",").replace(/%24/g,"$").replace(/%3D/g,"=").replace(/%3B/g,";").replace(/%28/g,"(").replace(/%29/g,")")}function Z(r){let e=[];for(let[t,n]of r)n===""||n===void 0||n===null||e.push(`${t}=${_(n)}`);return e.join("&")}function Se(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).byteLength:Buffer.byteLength(r,"utf8")}function X(r){let e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return`${r}_${e}`}function ee(r,e,t){let n=[];t?.$top!==void 0&&n.push(`$top=${_(String(t.$top))}`),t?.$skip!==void 0&&n.push(`$skip=${_(String(t.$skip))}`),t?.$filter&&n.push(`$filter=${_(t.$filter)}`),t?.$select&&n.push(`$select=${_(t.$select)}`);let i=n.join("&"),o=u(e);return i?`${r}/${o}?${i}`:`${r}/${o}`}function K(r,e,t){let n=u(e),i;if(typeof t=="number")i=String(t);else if(typeof t=="string")i=`'${t.replace(/'/g,"''")}'`;else if(typeof t=="boolean")i=t?"true":"false";else throw new TypeError("Batch: unsupported key type");return`${r}/${n}(${i})`}var U=class{constructor(e){this._ops=[];this._handles=[];this._baseUrl=e}get _operations(){return this._ops}get _handleSlots(){return this._handles}create(e,t){let n=ee(this._baseUrl,e),i,o,s=new Promise((c,d)=>{i=c,o=d}),a=this._handles.length;return this._handles.push({resolve:i,reject:o}),this._ops.push({method:"POST",path:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{__brand:"BatchHandle",_promise:s,_index:a}}patch(e,t,n,i){let o=K(this._baseUrl,e,t),s={"Content-Type":"application/json"};i?.ifMatch&&(s["If-Match"]=i.ifMatch);let a,c,d=new Promise((h,g)=>{a=h,c=g}),l=this._handles.length;return this._handles.push({resolve:a,reject:c}),this._ops.push({method:"PATCH",path:o,headers:s,body:JSON.stringify(n)}),{__brand:"BatchHandle",_promise:d,_index:l}}delete(e,t,n){let i=K(this._baseUrl,e,t),o={};n?.ifMatch&&(o["If-Match"]=n.ifMatch);let s,a,c=new Promise((l,h)=>{s=l,a=h}),d=this._handles.length;return this._handles.push({resolve:s,reject:a}),this._ops.push({method:"DELETE",path:i,headers:o}),{__brand:"BatchHandle",_promise:c,_index:d}}},F=class{constructor(e){this._parts=[];this._changesets=[];this._client=e}add(e){let t=ee(this._client.baseUrl,e.entitySet,e.query),n,i,s={__brand:"BatchHandle",_promise:new Promise((a,c)=>{n=a,i=c}),_index:this._parts.length};return this._parts.push({type:"read",content:{method:"GET",path:t},handle:s}),s}changeset(e){let t=new U(this._client.baseUrl);e(t),this._changesets.push(t),this._parts.push({type:"changeset",content:t})}_serialize(){let e=X("batch"),t=[];for(let n of this._parts)if(t.push(`--${e}`),n.type==="read"){let i=n.content;t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${i.method} ${i.path} HTTP/1.1`)}else if(n.type==="changeset"){let i=n.content,o=X("changeset");t.push("Content-Type: multipart/mixed; boundary="+o),t.push("");for(let s of i._operations){if(t.push(`--${o}`),t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${s.method} ${s.path} HTTP/1.1`),s.headers)for(let[a,c]of Object.entries(s.headers))t.push(`${a}: ${c}`);s.body&&(t.push(`Content-Length: ${Se(s.body)}`),t.push(""),t.push(s.body))}t.push(`--${o}--`)}return t.push(`--${e}--`),{boundary:e,body:t.join(`\r
2
2
  `)}}async send(e={}){let{boundary:t,body:n}=this._serialize(),i=await m(this._client._ctx,`${this._client.baseUrl}/$batch`,{method:"POST",headers:{"Content-Type":`multipart/mixed; boundary=${t}`},body:n,accept:"none",...e.signal?{signal:e.signal}:{}}),o=await i.text();return this._parseResponse(o,i.headers.get("content-type")??"")}_parseResponse(e,t){let i=t.match(/boundary=([^;\s]+)/)?.[1];if(!i)throw new Error("Batch response missing boundary in Content-Type");let o=e.split(`--${i}`),s=[],a=0;for(let c=1;c<o.length-1;c++){let d=o[c].trim();if(!d||d==="--")continue;let l=this._parts[a];if(l){if(l.type==="read"){let h=this._parseHttpPart(d);s.push(h),l.handle&&this._resolveHandle(l.handle,h),a++}else if(l.type==="changeset"){let h=l.content,g=this._parseChangesetResponse(d,h);s.push(...g);let M=g.find(T=>!T.ok);for(let T=0;T<h._handleSlots.length;T++){let q=h._handleSlots[T],G=g[T];M?q.reject(new Error(`Changeset failed: ${M.status}`)):G?q.resolve(G.body):q.resolve(void 0)}a++}}}return{responses:s,ok:s.every(c=>c.ok)}}_parseHttpPart(e){let t=e.indexOf(`\r
3
3
  \r
4
4
  `),n=t>=0?e.slice(t+4):e,i=n.indexOf(`\r
5
5
  \r
6
- `),o=i>=0?n.slice(0,i):n,s=i>=0?n.slice(i+4).trim():"",a=o.match(/^HTTP\/1\.\d (\d+)/),c=a?parseInt(a[1],10):0,d;if(s&&o.toLowerCase().includes("application/json"))try{d=JSON.parse(s)}catch{d=s}else s&&(d=s);return{status:c,body:d,headers:new Headers,ok:c>=200&&c<300}}_parseChangesetResponse(e,t){let i=e.match(/boundary=([^\s]+)/)?.[1];if(!i)return[this._parseHttpPart(e)];let o=e.split(`--${i}`),s=[];for(let a=1;a<o.length-1;a++){let c=o[a].trim();!c||c==="--"||s.push(this._parseHttpPart(c))}return s}_resolveHandle(e,t){}};var xe={20:"Claris FileMaker 2023",21:"Claris FileMaker 2024",22:"Claris FileMaker 2025",26:"Claris FileMaker 2026",future:"Future / next"},we="4.01";var w={20:{major:"20",name:"Claris FileMaker 2023",releaseYear:2023,internalVersion:"20.x",status:"supported",odataProtocolVersion:"4.0",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!1,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!1,parameterizedFilters:!1,simplifiedQuerySyntax:!1,nestedQueries:!1,batchPreferenceInheritance:!1,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!1,aiAnnotation:!1,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!1},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},21:{major:"21",name:"Claris FileMaker 2024",releaseYear:2024,internalVersion:"21.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},22:{major:"22",name:"Claris FileMaker 2025",releaseYear:2025,internalVersion:"22.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},26:{major:"26",name:"Claris FileMaker 2026",releaseYear:2026,internalVersion:"26.x",status:"current",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},future:{major:"future",name:"Future / next",releaseYear:null,internalVersion:"unknown",status:"future",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}}};function H(r,e){return w[r]?.features[e]??!1}function Ee(r,e){return w[r]?.queryOptions[e]??!1}function Te(r){let e=["20","21","22","26"];for(let t of e)if(w[t].features[r])return t;return null}function R(r){let e=r.trim().match(/(\d+)\.(\d+)\.(\d+)/);return e?{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10),raw:r.trim()}:null}function W(r){if(!r||typeof r!="string")return null;let e=r.match(/Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["'][^>]*String\s*=\s*["']([^"']+)["']/);if(e){let s=R(e[1]);if(s)return s}let t=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["']/);if(t){let s=R(t[1]);if(s)return s}let n=r.match(/Term\s*=\s*["']ServerVersion["'][^>]*String\s*=\s*["']([^"']+)["']/i);if(n){let s=R(n[1]);if(s&&s.major>=17)return s}let i=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']ServerVersion["']/i);if(i){let s=R(i[1]);if(s&&s.major>=17)return s}let o=r.match(/Term\s*=\s*["'][^"']*Version[^"']*["'][^>]*String\s*=\s*["'][^"']*?(\d{2,}\.\d+\.\d+(?:\.\d+)?)[^"']*?["']/i);if(o){let s=R(o[1]);if(s&&s.major>=17)return s}return null}var V=["NUMERIC","DECIMAL","INT","DATE","TIME","TIMESTAMP","VARCHAR","CHARACTER VARYING","BLOB","VARBINARY","LONGVARBINARY","BINARY VARYING"],_e=["USER","USERNAME","CURRENT_USER","CURRENT_DATE","CURDATE","CURRENT_TIME","CURTIME","CURRENT_TIMESTAMP","CURTIMESTAMP"];function J(r){let e=r.match(/\((\d+)\)/),t=r.match(/\[(\d+)\]/);return{baseType:r.replace(/\(.*?\)/,"").replace(/\[.*?\]/,"").trim(),length:e?parseInt(e[1],10):void 0,repetitions:t?parseInt(t[1],10):void 0}}function Oe(r,e){return r===void 0?e:r==="true"}function B(r,e){let t=new RegExp(`${e}="([^"]*)"`,"i");return r.match(t)?.[1]}function P(r){let e={},t=/(\w+)="([^"]*)"/g,n;for(;(n=t.exec(r))!==null;)e[n[1]]=n[2];return e}function S(r,e){let t=[],n=new RegExp(`<([\\w]+:)?${e}\\b[^>]*>`,"gi"),i;for(;(i=n.exec(r))!==null;){let o=i[0];if(/\/>\s*$/.test(o)){t.push(o);continue}let s=i.index,a=new RegExp(`</([\\w]+:)?${e}>`,"gi");a.lastIndex=n.lastIndex;let c=a.exec(r);c&&t.push(r.slice(s,c.index+c[0].length))}return t}function D(r,e){let n=new RegExp(`<(?:[\\w]+:)?${e}\\b[^>]*>`,"i").exec(r);if(!n)return;let i=n.index+n[0].length,o=new RegExp(`</(?:[\\w]+:)?${e}>`,"i");o.lastIndex=i;let s=o.exec(r);if(s)return r.slice(i,s.index)}function Re(r){let e=P(r),t=Oe(e.Nullable,!0),n={name:e.Name??"",type:e.Type??"",nullable:t};if(e.MaxLength!==void 0){let i=parseInt(e.MaxLength,10);Number.isNaN(i)||(n.maxLength=i)}return n}function $e(r){let e=P(r),t=e.Type??"",n=t.startsWith("Collection("),i=n?t.slice(11,-1):t;return{name:e.Name??"",target:i,collection:n}}function ke(r){let e=[],t=S(r,"PropertyRef");for(let n of t){let i=B(n,"Name");i&&e.push(i)}return e}function Me(r){let e=B(r,"Name")??"",t=[],n=[],i=[],o=D(r,"EntityType")??r,s=S(o,"Key")[0];s&&t.push(...ke(s));for(let a of S(o,"Property"))n.push(Re(a));for(let a of S(o,"NavigationProperty"))i.push($e(a));return{name:e,keys:t,properties:n,navigationProperties:i}}function Fe(r){let e=P(r);return{name:e.Name??"",entityType:e.EntityType??""}}function De(r){return W(r)??void 0}function Pe(r){let e=B(r,"Name")??"",t=P(r),n=t.IsBound==="true"?t.EntityType:void 0,i=[],o=D(r,"Action")??r;for(let s of S(o,"Parameter")){let a=P(s);i.push({name:a.Name??"",type:a.Type??""})}return n!==void 0?{name:e,boundTo:n,parameters:i}:{name:e,parameters:i}}function Ce(r){try{let e=D(r,"DataServices");if(!e)throw new Error("Missing <edmx:DataServices> in metadata");let t=S(e,"Schema")[0];if(!t)throw new Error("Missing <Schema> in metadata");let n=B(t,"Namespace")??"",i=D(t,"Schema")??t,o=[];for(let h of S(i,"EntityType"))o.push(Me(h));let s=[],a=S(i,"EntityContainer")[0];if(a){let h=D(a,"EntityContainer")??a;for(let g of S(h,"EntitySet"))s.push(Fe(g))}let c=[];for(let h of S(i,"Action"))c.push(Pe(h));let d=De(r),l={namespace:n,entityTypes:o,entitySets:s,actions:c,raw:r};return d&&(l.serverVersion=d,l.productVersion=d.raw),l}catch(e){let t=e instanceof Error?e.message:String(e);throw new y(`Failed to parse $metadata: ${t}`,{status:0,odataError:r.slice(0,500)})}}async function ve(r,e,t={}){return(await m(r,`${e}/$metadata`,{method:"GET",accept:"xml",...t.signal?{signal:t.signal}:{}})).text()}var $=class{constructor(e,t){this._ctx=e;this._baseUrl=t}async fetchXml(e={}){return ve(this._ctx,this._baseUrl,e)}async fetch(e={}){if(!e.refresh&&this._cache)return this._cache;let t=this.fetchXml(e).then(Ce);return this._cache=t,t}};var L=["image/png","image/jpeg","image/gif","image/tiff","application/pdf"];function Ae(r){return(r.split(";")[0]??"").trim().toLowerCase()}function Ie(r){let e=Ae(r);return L.includes(e)}function te(r){if(r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71&&r[4]===13&&r[5]===10&&r[6]===26&&r[7]===10)return"image/png";if(r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(r.length>=4&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56)return"image/gif";if(r.length>=4&&(r[0]===73&&r[1]===73&&r[2]===42&&r[3]===0||r[0]===77&&r[1]===77&&r[2]===0&&r[3]===42))return"image/tiff";if(r.length>=4&&r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70)return"application/pdf"}var C=class{constructor(e,t){if(!t)throw new TypeError("ContainerRef: fieldName is required");this._entity=e,this.fieldName=t}url(){return`${this._entity.toURL()}/${u(this.fieldName)}`}_valueUrl(){return`${this.url()}/$value`}async get(e={}){let t=await m(this._entity._client._ctx,this._valueUrl(),{method:"GET",accept:"none",...e.signal?{signal:e.signal}:{}}),n=t.headers.get("content-type")??"",i=t.headers.get("content-disposition"),o=i?je(i):void 0,s=await t.blob(),a={blob:s,contentType:n,size:s.size};return o!==void 0&&(a.filename=o),a}async getStream(e={}){let t=await m(this._entity._client._ctx,this._valueUrl(),{method:"GET",accept:"none",...e.signal?{signal:e.signal}:{}});if(!t.body)throw new TypeError("ContainerRef.getStream: response has no body");return t.body}async upload(e,t={}){let n=e.encoding??"binary",i=await Ve(e.data),o=e.contentType;if(!o){let a=te(i);if(!a)throw new TypeError(`ContainerRef.upload: contentType is required and could not be sniffed from the payload. Pass a contentType explicitly (one of ${L.join(", ")}).`);o=a}if(n==="binary"){if(!Ie(o))throw new TypeError(`ContainerRef.upload (binary): contentType "${o}" is not a FileMaker-supported container type. Use one of ${L.join(", ")}, or switch to { encoding: 'base64' }.`);let a={"Content-Type":o};e.filename&&(a["Content-Disposition"]=Ue(e.filename));let c=new ArrayBuffer(i.byteLength);new Uint8Array(c).set(i),await m(this._entity._client._ctx,this.url(),{method:"PATCH",headers:a,body:c,accept:"none",...t.signal?{signal:t.signal}:{}});return}let s=k({[this.fieldName]:{data:re(i),contentType:o,...e.filename?{filename:e.filename}:{}}});await m(this._entity._client._ctx,this._entity.toURL(),{method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(s),accept:"none",...t.signal?{signal:t.signal}:{}})}async delete(e={}){let t={[this.fieldName]:null};await m(this._entity._client._ctx,this._entity.toURL(),{method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(t),accept:"none",...e.signal?{signal:e.signal}:{}})}};function k(r,e={}){let t={...e};for(let[n,i]of Object.entries(r)){if(!i.contentType)throw new TypeError(`buildContainerJsonBody: "${n}".contentType is required`);t[n]=i.data,t[`${n}@com.filemaker.odata.ContentType`]=i.contentType,i.filename&&(t[`${n}@com.filemaker.odata.Filename`]=i.filename)}return t}function je(r){let e=r.match(/filename\*\s*=\s*([^']+)'[^']*'([^;]+)/i);if(e){let n=e[1].trim().toLowerCase(),i=e[2].trim();try{let o=decodeURIComponent(i);return o}catch{}}let t=r.match(/filename\s*=\s*("([^"\\]*(?:\\.[^"\\]*)*)"|([^;]+))/i);if(t){let n=t[2];if(n!==void 0)return n.replace(/\\(.)/g,"$1").trim();let i=t[3];if(i!==void 0)return i.trim()}}function Ue(r){let e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,t=/[^\x00-\x7F]/.test(r),n;return e.test(r)?n=`inline; filename=${r}`:n=`inline; filename="${r.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,'\\"')}"`,t?`${n}; filename*=UTF-8''${encodeURIComponent(r)}`:n}async function Ve(r){if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);let e=await r.arrayBuffer();return new Uint8Array(e)}function re(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="",t=32768;for(let n=0;n<r.length;n+=t)e+=String.fromCharCode.apply(null,Array.from(r.subarray(n,n+t)));return btoa(e)}function Be(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("ScriptInvoker: key must be a finite number");return String(r)}if(typeof r=="string")return`'${x(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("ScriptInvoker: unsupported key type")}var E=class{constructor(e,t={}){this._client=e,t.entitySet!==void 0&&(this.entitySet=t.entitySet),t.key!==void 0&&(this.key=t.key)}url(e){if(!e)throw new TypeError("ScriptInvoker: script name is required");return this._urlForSegment(`Script.${u(e)}`)}urlById(e){if(!Number.isFinite(e))throw new TypeError("ScriptInvoker: fmsid must be a finite number");return this._urlForSegment(`Script.FMSID:${e}`)}_urlForSegment(e){let t=this._client.baseUrl;if(this.entitySet===void 0)return`${t}/${e}`;let n=u(this.entitySet);return this.key===void 0?`${t}/${n}/${e}`:`${t}/${n}(${Be(this.key)})/${e}`}async run(e,t={}){return this._runAtUrl(this.url(e),t)}async runById(e,t={}){return this._runAtUrl(this.urlById(e),t)}async _runAtUrl(e,t){let n={},i;t.parameter!==void 0&&(n["Content-Type"]="application/json",i=JSON.stringify({scriptParameterValue:t.parameter}));let o="POST",s=await p(this._client._ctx,e,{method:o,headers:n,...i!==void 0?{body:i}:{},accept:"json",...t.signal?{signal:t.signal}:{}});return Le(s,{url:e,method:o})}};function Le(r,e){let t=Ne(r),n=t.scriptResult,i,o;if(n!==null&&typeof n=="object"&&"resultParameter"in n){let a=n;o=a.code!==void 0?String(a.code):"0",i=a.resultParameter!==void 0?String(a.resultParameter):void 0}else o=t.scriptError!==void 0?String(t.scriptError):"0",i=n!==void 0?typeof n=="string"?n:JSON.stringify(n):void 0;if(o!=="0")throw new _(`FileMaker script error ${o}`,{status:200,scriptError:o,...i!==void 0?{scriptResult:i}:{},odataError:r,request:e});let s={scriptError:o,raw:r};return i!==void 0&&(s.scriptResult=i),s}function Ne(r){if(r===null||typeof r!="object")return{};let e=r;if("scriptError"in e||"scriptResult"in e)return e;for(let t of Object.values(e))if(t&&typeof t=="object"){let n=t;if("scriptError"in n||"scriptResult"in n)return n}return{}}function ne(r,e,t){return new E(r).run(e,t)}function ie(r,e,t){return new E(r).runById(e,t)}function oe(r,e,t,n){return new E(r,{entitySet:e}).run(t,n)}function se(r,e,t,n,i){return new E(r,{entitySet:e,key:t}).run(n,i)}function qe(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("EntityRef: key must be a finite number");return String(r)}if(typeof r=="string")return`'${x(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("EntityRef: unsupported key type")}var v=class{constructor(e,t,n){this._client=e,this.entitySet=t,this.key=n}toURL(){return`${this._client.baseUrl}/${u(this.entitySet)}(${qe(this.key)})`}async get(e={}){return await p(this._client._ctx,this.toURL(),{method:"GET",accept:"json",...e.signal?{signal:e.signal}:{}})}async fieldValue(e,t={}){let n=`${this.toURL()}/${u(e)}`;return(await p(this._client._ctx,n,{method:"GET",accept:"json",...t.signal?{signal:t.signal}:{}})).value}async patch(e,t={}){let n={"Content-Type":"application/json",Prefer:t.returnRepresentation?"return=representation":"return=minimal"};return t.ifMatch&&(n["If-Match"]=t.ifMatch),await p(this._client._ctx,this.toURL(),{method:"PATCH",headers:n,body:JSON.stringify(e),accept:"json",...t.signal?{signal:t.signal}:{}})}async delete(e={}){let t={};e.ifMatch&&(t["If-Match"]=e.ifMatch),await m(this._client._ctx,this.toURL(),{method:"DELETE",headers:t,accept:"none",...e.signal?{signal:e.signal}:{}})}async script(e,t={}){return se(this._client,this.entitySet,this.key,e,t)}container(e){return new C(this,e)}async patchContainers(e,t={},n={}){let i={"Content-Type":"application/json",Prefer:n.returnRepresentation?"return=representation":"return=minimal"};n.ifMatch&&(i["If-Match"]=n.ifMatch);let o=k(e,t);await m(this._client._ctx,this.toURL(),{method:"PATCH",headers:i,body:JSON.stringify(o),accept:"none",...n.signal?{signal:n.signal}:{}})}async getRefs(e,t={}){let n=`${this.toURL()}/${u(e)}/$ref`,i=await p(this._client._ctx,n,{method:"GET",accept:"json",...t.signal?{signal:t.signal}:{}});return i?.value?i.value:i?.["@odata.id"]?[i]:[]}async addRef(e,t,n={}){let i=`${this.toURL()}/${u(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await m(this._client._ctx,i,{method:"POST",headers:o,body:s,accept:"none",...n.signal?{signal:n.signal}:{}})}async setRef(e,t,n={}){let i=`${this.toURL()}/${u(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await m(this._client._ctx,i,{method:"PATCH",headers:o,body:s,accept:"none",...n.signal?{signal:n.signal}:{}})}async removeRef(e,t,n={}){let i=`${this.toURL()}/${u(e)}/$ref`,o={};n.ifMatch&&(o["If-Match"]=n.ifMatch),t!==void 0&&(i+=`('${x(this._refId(e,t))}')`),await m(this._client._ctx,i,{method:"DELETE",headers:o,accept:"none",...n.signal?{signal:n.signal}:{}})}_refId(e,t){let n=e;return typeof t=="number"?`${n}(${t})`:`${n}('${x(t)}')`}};var f=class r{constructor(e){this.expr=e}toString(){return this.expr}and(e){return new r(`(${this.expr}) and (${r.coerce(e)})`)}or(e){return new r(`(${this.expr}) or (${r.coerce(e)})`)}not(){return new r(`not (${this.expr})`)}static coerce(e){return e instanceof r?e.expr:e}},ce={eq:(r,e)=>new f(`${r} eq ${b(e)}`),ne:(r,e)=>new f(`${r} ne ${b(e)}`),gt:(r,e)=>new f(`${r} gt ${b(e)}`),ge:(r,e)=>new f(`${r} ge ${b(e)}`),lt:(r,e)=>new f(`${r} lt ${b(e)}`),le:(r,e)=>new f(`${r} le ${b(e)}`),startswith:(r,e)=>new f(`startswith(${r},${b(e)})`),endswith:(r,e)=>new f(`endswith(${r},${b(e)})`),contains:(r,e)=>new f(`contains(${r},${b(e)})`),and:(r,e)=>new f(`(${f.coerce(r)}) and (${f.coerce(e)})`),or:(r,e)=>new f(`(${f.coerce(r)}) or (${f.coerce(e)})`),not:r=>new f(`not (${f.coerce(r)})`),raw:r=>new f(r)};function ae(r){return typeof r=="function"?f.coerce(r(ce)):f.coerce(r)}var A=class r{constructor(e,t,n){this._state={};this._baseUrl=e,this._entitySet=t,n&&(this._client=n)}select(...e){return this._state.select=[...this._state.select??[],...e],this}filter(e){let t=ae(e);return this._state.filter=this._state.filter?`(${this._state.filter}) and (${t})`:t,this}or(e){let t=ae(e);return this._state.filter=this._state.filter?`(${this._state.filter}) or (${t})`:t,this}expand(e,t){let n={name:e};if(t){let i=new r("",e);t(i),n.options=i._state}return this._state.expand=[...this._state.expand??[],n],this}orderby(e,t="asc"){return this._state.orderby=[...this._state.orderby??[],{field:e,dir:t}],this}top(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#top: expected non-negative integer, got ${e}`);return this._state.top=e,this}skip(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#skip: expected non-negative integer, got ${e}`);return this._state.skip=e,this}count(e=!0){return this._state.count=e,this}search(e){return this._state.search=e,this}apply(e){return this._state.apply=e,this}aggregate(e){let t=e.map(n=>`${n.field} with ${n.function} as ${n.alias}`);return this._state.apply=`aggregate(${t.join(",")})`,this}groupBy(e,t){let n=e.join(",");if(t&&t.length>0){let i=t.map(o=>`${o.field} with ${o.function} as ${o.alias}`);this._state.apply=`groupby((${n}),aggregate(${i.join(",")}))`}else this._state.apply=`groupby((${n}))`;return this}toURL(){let e=ue(this._state,{topLevel:!0}),t=`${this._baseUrl}/${u(this._entitySet)}`;return e?`${t}?${e}`:t}byKey(e){if(!this._client)throw new Error("Query#byKey: no client attached (use FMSOData#from)");return new v(this._client,this._entitySet,e)}async create(e,t={}){if(!this._client)throw new Error("Query#create: no client attached (use FMSOData#from)");let n=`${this._baseUrl}/${u(this._entitySet)}`;return await p(this._client._ctx,n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json",...t.signal?{signal:t.signal}:{}})}async createWithContainers(e,t,n={}){if(!this._client)throw new Error("Query#createWithContainers: no client attached (use FMSOData#from)");let i=`${this._baseUrl}/${u(this._entitySet)}`,o=k(t,e);return await p(this._client._ctx,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),accept:"json",...n.signal?{signal:n.signal}:{}})}async get(e={}){if(!this._client)throw new Error("Query#get: no client attached (use FMSOData#from)");let t=await p(this._client._ctx,this.toURL(),{method:"GET",accept:"json",...e.signal?{signal:e.signal}:{}}),n={value:t?.value??[]};return t&&typeof t["@odata.count"]=="number"&&(n.count=t["@odata.count"]),t&&typeof t["@odata.nextLink"]=="string"&&(n.nextLink=t["@odata.nextLink"]),n}async script(e,t={}){if(!this._client)throw new Error("Query#script: no client attached (use FMSOData#from)");return oe(this._client,this._entitySet,e,t)}};function ue(r,e){let t=[];if(r.select&&r.select.length>0&&t.push(["$select",r.select.join(",")]),r.filter&&t.push(["$filter",r.filter]),r.expand&&r.expand.length>0){let n=r.expand.map(i=>{if(!i.options)return i.name;let o=ue(i.options,{topLevel:!1});return o?`${i.name}(${o})`:i.name});t.push(["$expand",n.join(",")])}return r.orderby&&r.orderby.length>0&&t.push(["$orderby",r.orderby.map(n=>`${n.field} ${n.dir}`).join(",")]),r.top!==void 0&&t.push(["$top",String(r.top)]),r.skip!==void 0&&t.push(["$skip",String(r.skip)]),r.count&&t.push(["$count","true"]),r.search&&t.push(["$search",r.search]),r.apply&&t.push(["$apply",r.apply]),e.topLevel?Z(t):t.map(([n,i])=>`${n}=${i}`).join(";")}function de(r){for(let e of r){if(!e.name)throw new TypeError("SchemaEditor: field `name` is required");if(!e.type)throw new TypeError("SchemaEditor: field `type` is required");let{baseType:t}=J(e.type),n=t.toUpperCase();if(!V.includes(n))throw new TypeError(`SchemaEditor: unsupported field type "${e.type}" (base: "${t}"). Supported: ${V.join(", ")}`)}}var I=class{constructor(e){this._client=e}async createTable(e,t={}){if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!e.fields?.length)throw new TypeError("SchemaEditor: `fields` must be a non-empty array");de(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables`;return p(this._client._ctx,n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json",...t.signal?{signal:t.signal}:{}})}async addFields(e,t={}){if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!e.fields?.length)throw new TypeError("SchemaEditor: `fields` must be a non-empty array");de(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables/${u(e.tableName)}`;return p(this._client._ctx,n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({fields:e.fields}),accept:"json",...t.signal?{signal:t.signal}:{}})}async deleteTable(e,t){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(t.confirm!==!0)throw new TypeError(`SchemaEditor: deleteTable("${e}") requires { confirm: true } \u2014 this operation permanently destroys the table and all its records.`);let n=`${this._client.baseUrl}/FileMaker_Tables/${u(e)}`;await p(this._client._ctx,n,{method:"DELETE",accept:"json",...t.signal?{signal:t.signal}:{}})}async deleteField(e,t,n){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");if(n.confirm!==!0)throw new TypeError(`SchemaEditor: deleteField("${e}", "${t}") requires { confirm: true } \u2014 this operation permanently destroys the field and all its data.`);let i=`${this._client.baseUrl}/FileMaker_Tables/${u(e)}/${u(t)}`;await p(this._client._ctx,i,{method:"DELETE",accept:"json",...n.signal?{signal:n.signal}:{}})}async createIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${u(e)}`;return p(this._client._ctx,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({indexName:t}),accept:"json",...n.signal?{signal:n.signal}:{}})}async deleteIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${u(e)}/${u(t)}`;await p(this._client._ctx,i,{method:"DELETE",accept:"json",...n.signal?{signal:n.signal}:{}})}};function He(r){let e={webhook:r.webhook,tableName:r.tableName};return r.endpointHeaders&&(e.endpointHeaders=r.endpointHeaders),r.headers&&!r.endpointHeaders&&(e.endpointHeaders=r.headers),r.queryHeaders&&(e.queryHeaders=r.queryHeaders),r.notifySchemaChanges!==void 0&&(e.notifySchemaChanges=r.notifySchemaChanges),r.select&&(e.select=r.select),r.filter&&(e.filter=r.filter),r.maxFailedAttempts!==void 0&&(e.maxFailedAttempts=r.maxFailedAttempts),e}function We(r){if(!r||typeof r!="object")return;let e=r,n=e.webhookResult?.webhookID??e.webhookID??e.id;return n!==void 0?String(n):void 0}var j=class{constructor(e){this._client=e}_url(e,t){let n=`${this._client.baseUrl}/Webhook.${e}`;return t!==void 0?`${n}(${u(String(t))})`:n}async create(e,t={}){if(!e.webhook)throw new TypeError("WebhookManager: `webhook` URL is required");if(!e.tableName)throw new TypeError("WebhookManager: `tableName` is required");let n=JSON.stringify(He(e)),i=await p(this._client._ctx,this._url("Add"),{method:"POST",headers:{"Content-Type":"application/json"},body:n,accept:"json",...t.signal?{signal:t.signal}:{}}),o=We(i);if(o===void 0)throw new Error("WebhookManager: Webhook.Add did not return a webhook id");return{id:o}}async remove(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return p(this._client._ctx,this._url("Delete",e),{method:"POST",accept:"json",...t.signal?{signal:t.signal}:{}})}async delete(e,t={}){return this.remove(e,t)}async get(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return p(this._client._ctx,this._url("Get",e),{method:"GET",accept:"json",...t.signal?{signal:t.signal}:{}})}async getAll(e={}){return p(this._client._ctx,this._url("GetAll"),{method:"GET",accept:"json",...e.signal?{signal:e.signal}:{}})}async invoke(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");let{rowIDs:n,signal:i,...o}=t,s=JSON.stringify({rowIDs:n?[...n]:[]});return p(this._client._ctx,this._url("Invoke",e),{method:"POST",headers:{"Content-Type":"application/json"},body:s,accept:"json",...i?{signal:i}:{},...o})}};var N=class{constructor(e){if(!e.host)throw new TypeError("FMSOData: `host` is required");if(!e.database)throw new TypeError("FMSOData: `database` is required");if(e.token===void 0||e.token===null)throw new TypeError("FMSOData: `token` is required");this.host=e.host.replace(/\/+$/,""),this.database=e.database,this.baseUrl=`${this.host}/fmi/odata/v4/${encodeURIComponent(this.database)}`,this.timeoutMs=e.timeoutMs,this._ctx={token:e.token,fetch:e.fetch??globalThis.fetch.bind(globalThis),timeoutMs:e.timeoutMs,...e.onUnauthorized?{onUnauthorized:e.onUnauthorized}:{}}}from(e){if(!e)throw new TypeError("FMSOData#from: entitySet is required");return new A(this.baseUrl,e,this)}async request(e,t={}){return p(this._ctx,this._resolveUrl(e),t)}async rawRequest(e,t={}){return m(this._ctx,this._resolveUrl(e),t)}async script(e,t={}){return ne(this,e,t)}async scriptById(e,t={}){return ie(this,e,t)}async metadata(e={}){return this._metadataFetcher||(this._metadataFetcher=new $(this._ctx,this.baseUrl)),this._metadataFetcher.fetch(e)}async metadataXml(e={}){return this._metadataFetcher||(this._metadataFetcher=new $(this._ctx,this.baseUrl)),this._metadataFetcher.fetchXml(e)}async version(){if(this._detectedVersion!==void 0)return this._detectedVersion;try{let e=await this.serverVersion();if(!e)return this._detectedVersion=null,null;let t=String(e.major);return this._detectedVersion=t in w?t:"future",this._detectedVersion}catch{return this._detectedVersion=null,null}}async serverVersion(){if(this._detectedServerVersion!==void 0)return this._detectedServerVersion;try{let e=await this.metadata();return this._detectedServerVersion=e.serverVersion??null,this._detectedServerVersion}catch{return this._detectedServerVersion=null,null}}async versionInfo(){let e=await this.version();return e?w[e]:null}async hasFeature(e){let t=await this.version();return t?H(t,e):!1}schema(){return this._schemaEditor||(this._schemaEditor=new I(this)),this._schemaEditor}async createTable(e,t={}){return this.schema().createTable(e,t)}async addFields(e,t={}){return this.schema().addFields(e,t)}async deleteTable(e,t){return this.schema().deleteTable(e,t)}async deleteField(e,t,n){return this.schema().deleteField(e,t,n)}async createIndex(e,t,n={}){return this.schema().createIndex(e,t,n)}async deleteIndex(e,t,n={}){return this.schema().deleteIndex(e,t,n)}webhooks(){return this._webhookManager||(this._webhookManager=new j(this)),this._webhookManager}async createWebhook(e,t={}){return this.webhooks().create(e,t)}async removeWebhook(e,t={}){return this.webhooks().remove(e,t)}async getWebhook(e,t={}){return this.webhooks().get(e,t)}async getAllWebhooks(e={}){return this.webhooks().getAll(e)}async invokeWebhook(e,t={}){return this.webhooks().invoke(e,t)}batch(){return new F(this)}_resolveUrl(e){return/^https?:\/\//i.test(e)?e:e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}};export{F as Batch,U as Changeset,C as ContainerRef,v as EntityRef,_e as FIELD_DEFAULTS,V as FIELD_TYPES,N as FMOData,y as FMODataError,N as FMSOData,y as FMSODataError,_ as FMScriptError,L as FM_CONTAINER_SUPPORTED_MIME_TYPES,w as FM_VERSION_MATRIX,xe as FM_VERSION_NAMES,f as Filter,$ as MetadataFetcher,we as ODATA_PROTOCOL_VERSION,A as Query,I as SchemaEditor,E as ScriptInvoker,j as WebhookManager,he as basicAuth,me as bearerAuth,k as buildContainerJsonBody,ce as filterFactory,H as hasFeature,Ee as hasQueryOption,z as isFMODataError,z as isFMSODataError,pe as isFMScriptError,Te as minVersionForFeature,J as parseFieldType,W as parseServerVersion,R as parseVersionString,te as sniffContainerMime,re as toBase64};
6
+ `),o=i>=0?n.slice(0,i):n,s=i>=0?n.slice(i+4).trim():"",a=o.match(/^HTTP\/1\.\d (\d+)/),c=a?parseInt(a[1],10):0,d;if(s&&o.toLowerCase().includes("application/json"))try{d=JSON.parse(s)}catch{d=s}else s&&(d=s);return{status:c,body:d,headers:new Headers,ok:c>=200&&c<300}}_parseChangesetResponse(e,t){let i=e.match(/boundary=([^\s]+)/)?.[1];if(!i)return[this._parseHttpPart(e)];let o=e.split(`--${i}`),s=[];for(let a=1;a<o.length-1;a++){let c=o[a].trim();!c||c==="--"||s.push(this._parseHttpPart(c))}return s}_resolveHandle(e,t){}};var xe={20:"Claris FileMaker 2023",21:"Claris FileMaker 2024",22:"Claris FileMaker 2025",26:"Claris FileMaker 2026",future:"Future / next"},we="4.01";var w={20:{major:"20",name:"Claris FileMaker 2023",releaseYear:2023,internalVersion:"20.x",status:"supported",odataProtocolVersion:"4.0",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!1,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!1,parameterizedFilters:!1,simplifiedQuerySyntax:!1,nestedQueries:!1,batchPreferenceInheritance:!1,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!1,aiAnnotation:!1,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!1},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},21:{major:"21",name:"Claris FileMaker 2024",releaseYear:2024,internalVersion:"21.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},22:{major:"22",name:"Claris FileMaker 2025",releaseYear:2025,internalVersion:"22.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},26:{major:"26",name:"Claris FileMaker 2026",releaseYear:2026,internalVersion:"26.x",status:"current",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},future:{major:"future",name:"Future / next",releaseYear:null,internalVersion:"unknown",status:"future",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}}};function H(r,e){return w[r]?.features[e]??!1}function Ee(r,e){return w[r]?.queryOptions[e]??!1}function Te(r){let e=["20","21","22","26"];for(let t of e)if(w[t].features[r])return t;return null}function R(r){let e=r.trim().match(/(\d+)\.(\d+)\.(\d+)/);return e?{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10),raw:r.trim()}:null}function W(r){if(!r||typeof r!="string")return null;let e=r.match(/Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["'][^>]*String\s*=\s*["']([^"']+)["']/);if(e){let s=R(e[1]);if(s)return s}let t=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["']/);if(t){let s=R(t[1]);if(s)return s}let n=r.match(/Term\s*=\s*["']ServerVersion["'][^>]*String\s*=\s*["']([^"']+)["']/i);if(n){let s=R(n[1]);if(s&&s.major>=17)return s}let i=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']ServerVersion["']/i);if(i){let s=R(i[1]);if(s&&s.major>=17)return s}let o=r.match(/Term\s*=\s*["'][^"']*Version[^"']*["'][^>]*String\s*=\s*["'][^"']*?(\d{2,}\.\d+\.\d+(?:\.\d+)?)[^"']*?["']/i);if(o){let s=R(o[1]);if(s&&s.major>=17)return s}return null}var V=["NUMERIC","DECIMAL","INT","DATE","TIME","TIMESTAMP","VARCHAR","CHARACTER VARYING","BLOB","VARBINARY","LONGVARBINARY","BINARY VARYING"],Oe=["USER","USERNAME","CURRENT_USER","CURRENT_DATE","CURDATE","CURRENT_TIME","CURTIME","CURRENT_TIMESTAMP","CURTIMESTAMP"];function J(r){let e=r.match(/\((\d+)\)/),t=r.match(/\[(\d+)\]/);return{baseType:r.replace(/\(.*?\)/,"").replace(/\[.*?\]/,"").trim(),length:e?parseInt(e[1],10):void 0,repetitions:t?parseInt(t[1],10):void 0}}function _e(r,e){return r===void 0?e:r==="true"}function B(r,e){let t=new RegExp(`${e}="([^"]*)"`,"i");return r.match(t)?.[1]}function P(r){let e={},t=/(\w+)="([^"]*)"/g,n;for(;(n=t.exec(r))!==null;)e[n[1]]=n[2];return e}function S(r,e){let t=[],n=new RegExp(`<([\\w]+:)?${e}\\b[^>]*>`,"gi"),i;for(;(i=n.exec(r))!==null;){let o=i[0];if(/\/>\s*$/.test(o)){t.push(o);continue}let s=i.index,a=new RegExp(`</([\\w]+:)?${e}>`,"gi");a.lastIndex=n.lastIndex;let c=a.exec(r);c&&t.push(r.slice(s,c.index+c[0].length))}return t}function D(r,e){let n=new RegExp(`<(?:[\\w]+:)?${e}\\b[^>]*>`,"i").exec(r);if(!n)return;let i=n.index+n[0].length,o=new RegExp(`</(?:[\\w]+:)?${e}>`,"i");o.lastIndex=i;let s=o.exec(r);if(s)return r.slice(i,s.index)}function Re(r){let e=P(r),t=_e(e.Nullable,!0),n={name:e.Name??"",type:e.Type??"",nullable:t};if(e.MaxLength!==void 0){let i=parseInt(e.MaxLength,10);Number.isNaN(i)||(n.maxLength=i)}return n}function $e(r){let e=P(r),t=e.Type??"",n=t.startsWith("Collection("),i=n?t.slice(11,-1):t;return{name:e.Name??"",target:i,collection:n}}function ke(r){let e=[],t=S(r,"PropertyRef");for(let n of t){let i=B(n,"Name");i&&e.push(i)}return e}function Me(r){let e=B(r,"Name")??"",t=[],n=[],i=[],o=D(r,"EntityType")??r,s=S(o,"Key")[0];s&&t.push(...ke(s));for(let a of S(o,"Property"))n.push(Re(a));for(let a of S(o,"NavigationProperty"))i.push($e(a));return{name:e,keys:t,properties:n,navigationProperties:i}}function Fe(r){let e=P(r);return{name:e.Name??"",entityType:e.EntityType??""}}function De(r){return W(r)??void 0}function Pe(r){let e=B(r,"Name")??"",t=P(r),n=t.IsBound==="true"?t.EntityType:void 0,i=[],o=D(r,"Action")??r;for(let s of S(o,"Parameter")){let a=P(s);i.push({name:a.Name??"",type:a.Type??""})}return n!==void 0?{name:e,boundTo:n,parameters:i}:{name:e,parameters:i}}function Ce(r){try{let e=D(r,"DataServices");if(!e)throw new Error("Missing <edmx:DataServices> in metadata");let t=S(e,"Schema")[0];if(!t)throw new Error("Missing <Schema> in metadata");let n=B(t,"Namespace")??"",i=D(t,"Schema")??t,o=[];for(let h of S(i,"EntityType"))o.push(Me(h));let s=[],a=S(i,"EntityContainer")[0];if(a){let h=D(a,"EntityContainer")??a;for(let g of S(h,"EntitySet"))s.push(Fe(g))}let c=[];for(let h of S(i,"Action"))c.push(Pe(h));let d=De(r),l={namespace:n,entityTypes:o,entitySets:s,actions:c,raw:r};return d&&(l.serverVersion=d,l.productVersion=d.raw),l}catch(e){let t=e instanceof Error?e.message:String(e);throw new y(`Failed to parse $metadata: ${t}`,{status:0,odataError:r.slice(0,500)})}}async function ve(r,e,t={}){return(await m(r,`${e}/$metadata`,{method:"GET",accept:"xml",...t.signal?{signal:t.signal}:{}})).text()}var $=class{constructor(e,t){this._ctx=e;this._baseUrl=t}async fetchXml(e={}){return ve(this._ctx,this._baseUrl,e)}async fetch(e={}){if(!e.refresh&&this._cache)return this._cache;let t=this.fetchXml(e).then(Ce);return this._cache=t,t}};var L=["image/png","image/jpeg","image/gif","image/tiff","application/pdf"];function Ae(r){return(r.split(";")[0]??"").trim().toLowerCase()}function Ie(r){let e=Ae(r);return L.includes(e)}function te(r){if(r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71&&r[4]===13&&r[5]===10&&r[6]===26&&r[7]===10)return"image/png";if(r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(r.length>=4&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56)return"image/gif";if(r.length>=4&&(r[0]===73&&r[1]===73&&r[2]===42&&r[3]===0||r[0]===77&&r[1]===77&&r[2]===0&&r[3]===42))return"image/tiff";if(r.length>=4&&r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70)return"application/pdf"}var C=class{constructor(e,t){if(!t)throw new TypeError("ContainerRef: fieldName is required");this._entity=e,this.fieldName=t}url(){return`${this._entity.toURL()}/${u(this.fieldName)}`}_valueUrl(){return`${this.url()}/$value`}async get(e={}){let t=await m(this._entity._client._ctx,this._valueUrl(),{method:"GET",accept:"none",...e.signal?{signal:e.signal}:{}}),n=t.headers.get("content-type")??"",i=t.headers.get("content-disposition"),o=i?je(i):void 0,s=await t.blob(),a={blob:s,contentType:n,size:s.size};return o!==void 0&&(a.filename=o),a}async getStream(e={}){let t=await m(this._entity._client._ctx,this._valueUrl(),{method:"GET",accept:"none",...e.signal?{signal:e.signal}:{}});if(!t.body)throw new TypeError("ContainerRef.getStream: response has no body");return t.body}async upload(e,t={}){let n=e.encoding??"binary",i=await Ve(e.data),o=e.contentType;if(!o){let a=te(i);if(!a)throw new TypeError(`ContainerRef.upload: contentType is required and could not be sniffed from the payload. Pass a contentType explicitly (one of ${L.join(", ")}).`);o=a}if(n==="binary"){if(!Ie(o))throw new TypeError(`ContainerRef.upload (binary): contentType "${o}" is not a FileMaker-supported container type. Use one of ${L.join(", ")}, or switch to { encoding: 'base64' }.`);let a={"Content-Type":o};e.filename&&(a["Content-Disposition"]=Ue(e.filename));let c=new ArrayBuffer(i.byteLength);new Uint8Array(c).set(i),await m(this._entity._client._ctx,this.url(),{method:"PATCH",headers:a,body:c,accept:"none",...t.signal?{signal:t.signal}:{}});return}let s=k({[this.fieldName]:{data:re(i),contentType:o,...e.filename?{filename:e.filename}:{}}});await m(this._entity._client._ctx,this._entity.toURL(),{method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(s),accept:"none",...t.signal?{signal:t.signal}:{}})}async delete(e={}){let t={[this.fieldName]:null};await m(this._entity._client._ctx,this._entity.toURL(),{method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(t),accept:"none",...e.signal?{signal:e.signal}:{}})}};function k(r,e={}){let t={...e};for(let[n,i]of Object.entries(r)){if(!i.contentType)throw new TypeError(`buildContainerJsonBody: "${n}".contentType is required`);t[n]=i.data,t[`${n}@com.filemaker.odata.ContentType`]=i.contentType,i.filename&&(t[`${n}@com.filemaker.odata.Filename`]=i.filename)}return t}function je(r){let e=r.match(/filename\*\s*=\s*([^']+)'[^']*'([^;]+)/i);if(e){let n=e[1].trim().toLowerCase(),i=e[2].trim();try{let o=decodeURIComponent(i);return o}catch{}}let t=r.match(/filename\s*=\s*("([^"\\]*(?:\\.[^"\\]*)*)"|([^;]+))/i);if(t){let n=t[2];if(n!==void 0)return n.replace(/\\(.)/g,"$1").trim();let i=t[3];if(i!==void 0)return i.trim()}}function Ue(r){let e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,t=/[^\x00-\x7F]/.test(r),n;return e.test(r)?n=`inline; filename=${r}`:n=`inline; filename="${r.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,'\\"')}"`,t?`${n}; filename*=UTF-8''${encodeURIComponent(r)}`:n}async function Ve(r){if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);let e=await r.arrayBuffer();return new Uint8Array(e)}function re(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="",t=32768;for(let n=0;n<r.length;n+=t)e+=String.fromCharCode.apply(null,Array.from(r.subarray(n,n+t)));return btoa(e)}function Be(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("ScriptInvoker: key must be a finite number");return String(r)}if(typeof r=="string")return`'${x(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("ScriptInvoker: unsupported key type")}var E=class{constructor(e,t={}){this._client=e,t.entitySet!==void 0&&(this.entitySet=t.entitySet),t.key!==void 0&&(this.key=t.key)}url(e){if(!e)throw new TypeError("ScriptInvoker: script name is required");return this._urlForSegment(`Script.${u(e)}`)}urlById(e){if(!Number.isFinite(e))throw new TypeError("ScriptInvoker: fmsid must be a finite number");return this._urlForSegment(`Script.FMSID:${e}`)}_urlForSegment(e){let t=this._client.baseUrl;if(this.entitySet===void 0)return`${t}/${e}`;let n=u(this.entitySet);return this.key===void 0?`${t}/${n}/${e}`:`${t}/${n}(${Be(this.key)})/${e}`}async run(e,t={}){return this._runAtUrl(this.url(e),t)}async runById(e,t={}){return this._runAtUrl(this.urlById(e),t)}async _runAtUrl(e,t){let n={},i;t.parameter!==void 0&&(n["Content-Type"]="application/json",i=JSON.stringify({scriptParameterValue:t.parameter}));let o="POST",s=await p(this._client._ctx,e,{method:o,headers:n,...i!==void 0?{body:i}:{},accept:"json",...t.signal?{signal:t.signal}:{}});return Le(s,{url:e,method:o})}};function Le(r,e){let t=Ne(r),n=t.scriptResult,i,o,s;if(n!==null&&typeof n=="object"&&("code"in n||"resultParameter"in n)){let c=n;o=c.code!==void 0?String(c.code):"0",i=c.resultParameter!==void 0?typeof c.resultParameter=="string"?c.resultParameter:JSON.stringify(c.resultParameter):void 0,typeof c.message=="string"&&(s=c.message)}else o=t.scriptError!==void 0?String(t.scriptError):"0",i=n!==void 0?typeof n=="string"?n:JSON.stringify(n):void 0;if(o!=="0")throw new O(s?`FileMaker script error ${o}: ${s}`:`FileMaker script error ${o}`,{status:200,scriptError:o,...i!==void 0?{scriptResult:i}:{},odataError:r,request:e});let a={scriptError:o,raw:r};return i!==void 0&&(a.scriptResult=i),a}function Ne(r){if(r===null||typeof r!="object")return{};let e=r;if("scriptError"in e||"scriptResult"in e)return e;for(let t of Object.values(e))if(t&&typeof t=="object"){let n=t;if("scriptError"in n||"scriptResult"in n)return n}return{}}function ne(r,e,t){return new E(r).run(e,t)}function ie(r,e,t){return new E(r).runById(e,t)}function oe(r,e,t,n){return new E(r,{entitySet:e}).run(t,n)}function se(r,e,t,n,i){return new E(r,{entitySet:e,key:t}).run(n,i)}function qe(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("EntityRef: key must be a finite number");return String(r)}if(typeof r=="string")return`'${x(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("EntityRef: unsupported key type")}var v=class{constructor(e,t,n){this._client=e,this.entitySet=t,this.key=n}toURL(){return`${this._client.baseUrl}/${u(this.entitySet)}(${qe(this.key)})`}async get(e={}){return await p(this._client._ctx,this.toURL(),{method:"GET",accept:"json",...e.signal?{signal:e.signal}:{}})}async fieldValue(e,t={}){let n=`${this.toURL()}/${u(e)}`;return(await p(this._client._ctx,n,{method:"GET",accept:"json",...t.signal?{signal:t.signal}:{}})).value}async patch(e,t={}){let n={"Content-Type":"application/json",Prefer:t.returnRepresentation?"return=representation":"return=minimal"};return t.ifMatch&&(n["If-Match"]=t.ifMatch),await p(this._client._ctx,this.toURL(),{method:"PATCH",headers:n,body:JSON.stringify(e),accept:"json",...t.signal?{signal:t.signal}:{}})}async delete(e={}){let t={};e.ifMatch&&(t["If-Match"]=e.ifMatch),await m(this._client._ctx,this.toURL(),{method:"DELETE",headers:t,accept:"none",...e.signal?{signal:e.signal}:{}})}async script(e,t={}){return se(this._client,this.entitySet,this.key,e,t)}container(e){return new C(this,e)}async patchContainers(e,t={},n={}){let i={"Content-Type":"application/json",Prefer:n.returnRepresentation?"return=representation":"return=minimal"};n.ifMatch&&(i["If-Match"]=n.ifMatch);let o=k(e,t);await m(this._client._ctx,this.toURL(),{method:"PATCH",headers:i,body:JSON.stringify(o),accept:"none",...n.signal?{signal:n.signal}:{}})}async getRefs(e,t={}){let n=`${this.toURL()}/${u(e)}/$ref`,i=await p(this._client._ctx,n,{method:"GET",accept:"json",...t.signal?{signal:t.signal}:{}});return i?.value?i.value:i?.["@odata.id"]?[i]:[]}async addRef(e,t,n={}){let i=`${this.toURL()}/${u(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await m(this._client._ctx,i,{method:"POST",headers:o,body:s,accept:"none",...n.signal?{signal:n.signal}:{}})}async setRef(e,t,n={}){let i=`${this.toURL()}/${u(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await m(this._client._ctx,i,{method:"PATCH",headers:o,body:s,accept:"none",...n.signal?{signal:n.signal}:{}})}async removeRef(e,t,n={}){let i=`${this.toURL()}/${u(e)}/$ref`,o={};n.ifMatch&&(o["If-Match"]=n.ifMatch),t!==void 0&&(i+=`('${x(this._refId(e,t))}')`),await m(this._client._ctx,i,{method:"DELETE",headers:o,accept:"none",...n.signal?{signal:n.signal}:{}})}_refId(e,t){let n=e;return typeof t=="number"?`${n}(${t})`:`${n}('${x(t)}')`}};var f=class r{constructor(e){this.expr=e}toString(){return this.expr}and(e){return new r(`(${this.expr}) and (${r.coerce(e)})`)}or(e){return new r(`(${this.expr}) or (${r.coerce(e)})`)}not(){return new r(`not (${this.expr})`)}static coerce(e){return e instanceof r?e.expr:e}},ce={eq:(r,e)=>new f(`${r} eq ${b(e)}`),ne:(r,e)=>new f(`${r} ne ${b(e)}`),gt:(r,e)=>new f(`${r} gt ${b(e)}`),ge:(r,e)=>new f(`${r} ge ${b(e)}`),lt:(r,e)=>new f(`${r} lt ${b(e)}`),le:(r,e)=>new f(`${r} le ${b(e)}`),startswith:(r,e)=>new f(`startswith(${r},${b(e)})`),endswith:(r,e)=>new f(`endswith(${r},${b(e)})`),contains:(r,e)=>new f(`contains(${r},${b(e)})`),and:(r,e)=>new f(`(${f.coerce(r)}) and (${f.coerce(e)})`),or:(r,e)=>new f(`(${f.coerce(r)}) or (${f.coerce(e)})`),not:r=>new f(`not (${f.coerce(r)})`),raw:r=>new f(r)};function ae(r){return typeof r=="function"?f.coerce(r(ce)):f.coerce(r)}var A=class r{constructor(e,t,n){this._state={};this._baseUrl=e,this._entitySet=t,n&&(this._client=n)}select(...e){return this._state.select=[...this._state.select??[],...e],this}filter(e){let t=ae(e);return this._state.filter=this._state.filter?`(${this._state.filter}) and (${t})`:t,this}or(e){let t=ae(e);return this._state.filter=this._state.filter?`(${this._state.filter}) or (${t})`:t,this}expand(e,t){let n={name:e};if(t){let i=new r("",e);t(i),n.options=i._state}return this._state.expand=[...this._state.expand??[],n],this}orderby(e,t="asc"){return this._state.orderby=[...this._state.orderby??[],{field:e,dir:t}],this}top(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#top: expected non-negative integer, got ${e}`);return this._state.top=e,this}skip(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#skip: expected non-negative integer, got ${e}`);return this._state.skip=e,this}count(e=!0){return this._state.count=e,this}search(e){return this._state.search=e,this}apply(e){return this._state.apply=e,this}aggregate(e){let t=e.map(n=>`${n.field} with ${n.function} as ${n.alias}`);return this._state.apply=`aggregate(${t.join(",")})`,this}groupBy(e,t){let n=e.join(",");if(t&&t.length>0){let i=t.map(o=>`${o.field} with ${o.function} as ${o.alias}`);this._state.apply=`groupby((${n}),aggregate(${i.join(",")}))`}else this._state.apply=`groupby((${n}))`;return this}toURL(){let e=ue(this._state,{topLevel:!0}),t=`${this._baseUrl}/${u(this._entitySet)}`;return e?`${t}?${e}`:t}byKey(e){if(!this._client)throw new Error("Query#byKey: no client attached (use FMSOData#from)");return new v(this._client,this._entitySet,e)}async create(e,t={}){if(!this._client)throw new Error("Query#create: no client attached (use FMSOData#from)");let n=`${this._baseUrl}/${u(this._entitySet)}`;return await p(this._client._ctx,n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json",...t.signal?{signal:t.signal}:{}})}async createWithContainers(e,t,n={}){if(!this._client)throw new Error("Query#createWithContainers: no client attached (use FMSOData#from)");let i=`${this._baseUrl}/${u(this._entitySet)}`,o=k(t,e);return await p(this._client._ctx,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),accept:"json",...n.signal?{signal:n.signal}:{}})}async get(e={}){if(!this._client)throw new Error("Query#get: no client attached (use FMSOData#from)");let t=await p(this._client._ctx,this.toURL(),{method:"GET",accept:"json",...e.signal?{signal:e.signal}:{}}),n={value:t?.value??[]};return t&&typeof t["@odata.count"]=="number"&&(n.count=t["@odata.count"]),t&&typeof t["@odata.nextLink"]=="string"&&(n.nextLink=t["@odata.nextLink"]),n}async script(e,t={}){if(!this._client)throw new Error("Query#script: no client attached (use FMSOData#from)");return oe(this._client,this._entitySet,e,t)}};function ue(r,e){let t=[];if(r.select&&r.select.length>0&&t.push(["$select",r.select.join(",")]),r.filter&&t.push(["$filter",r.filter]),r.expand&&r.expand.length>0){let n=r.expand.map(i=>{if(!i.options)return i.name;let o=ue(i.options,{topLevel:!1});return o?`${i.name}(${o})`:i.name});t.push(["$expand",n.join(",")])}return r.orderby&&r.orderby.length>0&&t.push(["$orderby",r.orderby.map(n=>`${n.field} ${n.dir}`).join(",")]),r.top!==void 0&&t.push(["$top",String(r.top)]),r.skip!==void 0&&t.push(["$skip",String(r.skip)]),r.count&&t.push(["$count","true"]),r.search&&t.push(["$search",r.search]),r.apply&&t.push(["$apply",r.apply]),e.topLevel?Z(t):t.map(([n,i])=>`${n}=${i}`).join(";")}function de(r){for(let e of r){if(!e.name)throw new TypeError("SchemaEditor: field `name` is required");if(!e.type)throw new TypeError("SchemaEditor: field `type` is required");let{baseType:t}=J(e.type),n=t.toUpperCase();if(!V.includes(n))throw new TypeError(`SchemaEditor: unsupported field type "${e.type}" (base: "${t}"). Supported: ${V.join(", ")}`)}}var I=class{constructor(e){this._client=e}async createTable(e,t={}){if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!e.fields?.length)throw new TypeError("SchemaEditor: `fields` must be a non-empty array");de(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables`;return p(this._client._ctx,n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json",...t.signal?{signal:t.signal}:{}})}async addFields(e,t={}){if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!e.fields?.length)throw new TypeError("SchemaEditor: `fields` must be a non-empty array");de(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables/${u(e.tableName)}`;return p(this._client._ctx,n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({fields:e.fields}),accept:"json",...t.signal?{signal:t.signal}:{}})}async deleteTable(e,t){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(t.confirm!==!0)throw new TypeError(`SchemaEditor: deleteTable("${e}") requires { confirm: true } \u2014 this operation permanently destroys the table and all its records.`);let n=`${this._client.baseUrl}/FileMaker_Tables/${u(e)}`;await p(this._client._ctx,n,{method:"DELETE",accept:"json",...t.signal?{signal:t.signal}:{}})}async deleteField(e,t,n){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");if(n.confirm!==!0)throw new TypeError(`SchemaEditor: deleteField("${e}", "${t}") requires { confirm: true } \u2014 this operation permanently destroys the field and all its data.`);let i=`${this._client.baseUrl}/FileMaker_Tables/${u(e)}/${u(t)}`;await p(this._client._ctx,i,{method:"DELETE",accept:"json",...n.signal?{signal:n.signal}:{}})}async createIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${u(e)}`;return p(this._client._ctx,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({indexName:t}),accept:"json",...n.signal?{signal:n.signal}:{}})}async deleteIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${u(e)}/${u(t)}`;await p(this._client._ctx,i,{method:"DELETE",accept:"json",...n.signal?{signal:n.signal}:{}})}};function He(r){let e={webhook:r.webhook,tableName:r.tableName};return r.endpointHeaders&&(e.endpointHeaders=r.endpointHeaders),r.headers&&!r.endpointHeaders&&(e.endpointHeaders=r.headers),r.queryHeaders&&(e.queryHeaders=r.queryHeaders),r.notifySchemaChanges!==void 0&&(e.notifySchemaChanges=r.notifySchemaChanges),r.select&&(e.select=r.select),r.filter&&(e.filter=r.filter),r.maxFailedAttempts!==void 0&&(e.maxFailedAttempts=r.maxFailedAttempts),e}function We(r){if(!r||typeof r!="object")return;let e=r,n=e.webhookResult?.webhookID??e.webhookID??e.id;return n!==void 0?String(n):void 0}var j=class{constructor(e){this._client=e}_url(e,t){let n=`${this._client.baseUrl}/Webhook.${e}`;return t!==void 0?`${n}(${u(String(t))})`:n}async create(e,t={}){if(!e.webhook)throw new TypeError("WebhookManager: `webhook` URL is required");if(!e.tableName)throw new TypeError("WebhookManager: `tableName` is required");let n=JSON.stringify(He(e)),i=await p(this._client._ctx,this._url("Add"),{method:"POST",headers:{"Content-Type":"application/json"},body:n,accept:"json",...t.signal?{signal:t.signal}:{}}),o=We(i);if(o===void 0)throw new Error("WebhookManager: Webhook.Add did not return a webhook id");return{id:o}}async remove(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return p(this._client._ctx,this._url("Delete",e),{method:"POST",accept:"json",...t.signal?{signal:t.signal}:{}})}async delete(e,t={}){return this.remove(e,t)}async get(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return p(this._client._ctx,this._url("Get",e),{method:"GET",accept:"json",...t.signal?{signal:t.signal}:{}})}async getAll(e={}){return p(this._client._ctx,this._url("GetAll"),{method:"GET",accept:"json",...e.signal?{signal:e.signal}:{}})}async invoke(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");let{rowIDs:n,signal:i,...o}=t,s=JSON.stringify({rowIDs:n?[...n]:[]});return p(this._client._ctx,this._url("Invoke",e),{method:"POST",headers:{"Content-Type":"application/json"},body:s,accept:"json",...i?{signal:i}:{},...o})}};var N=class{constructor(e){if(!e.host)throw new TypeError("FMSOData: `host` is required");if(!e.database)throw new TypeError("FMSOData: `database` is required");if(e.token===void 0||e.token===null)throw new TypeError("FMSOData: `token` is required");this.host=e.host.replace(/\/+$/,""),this.database=e.database,this.baseUrl=`${this.host}/fmi/odata/v4/${encodeURIComponent(this.database)}`,this.timeoutMs=e.timeoutMs,this._ctx={token:e.token,fetch:e.fetch??globalThis.fetch.bind(globalThis),timeoutMs:e.timeoutMs,...e.onUnauthorized?{onUnauthorized:e.onUnauthorized}:{}}}from(e){if(!e)throw new TypeError("FMSOData#from: entitySet is required");return new A(this.baseUrl,e,this)}async request(e,t={}){return p(this._ctx,this._resolveUrl(e),t)}async rawRequest(e,t={}){return m(this._ctx,this._resolveUrl(e),t)}async script(e,t={}){return ne(this,e,t)}async scriptById(e,t={}){return ie(this,e,t)}async metadata(e={}){return this._metadataFetcher||(this._metadataFetcher=new $(this._ctx,this.baseUrl)),this._metadataFetcher.fetch(e)}async metadataXml(e={}){return this._metadataFetcher||(this._metadataFetcher=new $(this._ctx,this.baseUrl)),this._metadataFetcher.fetchXml(e)}async version(){if(this._detectedVersion!==void 0)return this._detectedVersion;try{let e=await this.serverVersion();if(!e)return this._detectedVersion=null,null;let t=String(e.major);return this._detectedVersion=t in w?t:"future",this._detectedVersion}catch{return this._detectedVersion=null,null}}async serverVersion(){if(this._detectedServerVersion!==void 0)return this._detectedServerVersion;try{let e=await this.metadata();return this._detectedServerVersion=e.serverVersion??null,this._detectedServerVersion}catch{return this._detectedServerVersion=null,null}}async versionInfo(){let e=await this.version();return e?w[e]:null}async hasFeature(e){let t=await this.version();return t?H(t,e):!1}schema(){return this._schemaEditor||(this._schemaEditor=new I(this)),this._schemaEditor}async createTable(e,t={}){return this.schema().createTable(e,t)}async addFields(e,t={}){return this.schema().addFields(e,t)}async deleteTable(e,t){return this.schema().deleteTable(e,t)}async deleteField(e,t,n){return this.schema().deleteField(e,t,n)}async createIndex(e,t,n={}){return this.schema().createIndex(e,t,n)}async deleteIndex(e,t,n={}){return this.schema().deleteIndex(e,t,n)}webhooks(){return this._webhookManager||(this._webhookManager=new j(this)),this._webhookManager}async createWebhook(e,t={}){return this.webhooks().create(e,t)}async removeWebhook(e,t={}){return this.webhooks().remove(e,t)}async getWebhook(e,t={}){return this.webhooks().get(e,t)}async getAllWebhooks(e={}){return this.webhooks().getAll(e)}async invokeWebhook(e,t={}){return this.webhooks().invoke(e,t)}batch(){return new F(this)}_resolveUrl(e){return/^https?:\/\//i.test(e)?e:e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}};export{F as Batch,U as Changeset,C as ContainerRef,v as EntityRef,Oe as FIELD_DEFAULTS,V as FIELD_TYPES,N as FMOData,y as FMODataError,N as FMSOData,y as FMSODataError,O as FMScriptError,L as FM_CONTAINER_SUPPORTED_MIME_TYPES,w as FM_VERSION_MATRIX,xe as FM_VERSION_NAMES,f as Filter,$ as MetadataFetcher,we as ODATA_PROTOCOL_VERSION,A as Query,I as SchemaEditor,E as ScriptInvoker,j as WebhookManager,he as basicAuth,me as bearerAuth,k as buildContainerJsonBody,ce as filterFactory,H as hasFeature,Ee as hasQueryOption,z as isFMODataError,z as isFMSODataError,pe as isFMScriptError,Te as minVersionForFeature,J as parseFieldType,W as parseServerVersion,R as parseVersionString,te as sniffContainerMime,re as toBase64};
@@ -1,6 +1,6 @@
1
- "use strict";var FMSODataLib=(()=>{var G=Object.defineProperty,$e=Object.defineProperties,ke=Object.getOwnPropertyDescriptor,Me=Object.getOwnPropertyDescriptors,Fe=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols;var X=Object.prototype.hasOwnProperty,ie=Object.prototype.propertyIsEnumerable;var ne=(r,e,t)=>e in r?G(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,c=(r,e)=>{for(var t in e||(e={}))X.call(e,t)&&ne(r,t,e[t]);if(J)for(var t of J(e))ie.call(e,t)&&ne(r,t,e[t]);return r},V=(r,e)=>$e(r,Me(e));var oe=(r,e)=>{var t={};for(var n in r)X.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&J)for(var n of J(r))e.indexOf(n)<0&&ie.call(r,n)&&(t[n]=r[n]);return t};var De=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},Pe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fe(e))!X.call(r,i)&&i!==t&&G(r,i,{get:()=>e[i],enumerable:!(n=ke(e,i))||n.enumerable});return r};var Ce=r=>Pe(G({},"__esModule",{value:!0}),r);var at={};De(at,{Batch:()=>P,Changeset:()=>B,ContainerRef:()=>C,EntityRef:()=>v,FIELD_DEFAULTS:()=>Se,FIELD_TYPES:()=>L,FMOData:()=>W,FMODataError:()=>x,FMSOData:()=>W,FMSODataError:()=>x,FMScriptError:()=>R,FM_CONTAINER_SUPPORTED_MIME_TYPES:()=>H,FM_VERSION_MATRIX:()=>_,FM_VERSION_NAMES:()=>me,Filter:()=>f,MetadataFetcher:()=>M,ODATA_PROTOCOL_VERSION:()=>ge,Query:()=>A,SchemaEditor:()=>I,ScriptInvoker:()=>O,WebhookManager:()=>j,basicAuth:()=>ce,bearerAuth:()=>ue,buildContainerJsonBody:()=>F,filterFactory:()=>re,hasFeature:()=>Q,hasQueryOption:()=>ye,isFMODataError:()=>K,isFMSODataError:()=>K,isFMScriptError:()=>ae,minVersionForFeature:()=>be,parseFieldType:()=>Y,parseServerVersion:()=>z,parseVersionString:()=>k,sniffContainerMime:()=>ee,toBase64:()=>te});var x=class extends Error{constructor(e,t){super(e),this.name="FMSODataError",this.status=t.status,t.code!==void 0&&(this.code=t.code),t.odataError!==void 0&&(this.odataError=t.odataError),t.request!==void 0&&(this.request=t.request)}};async function se(r,e){var h,m,S;let t=r.status,n="";try{n=await r.text()}catch(g){}let i,o=r.statusText||`HTTP ${t}`,s=n,a=((h=r.headers.get("content-type"))!=null?h:"").toLowerCase(),u=a.includes("json")||n.startsWith("{")&&n.endsWith("}"),d=a.includes("xml")||n.trimStart().startsWith("<?xml")||n.includes("<m:error");if(u)try{let g=JSON.parse(n);s=g;let y=(m=g==null?void 0:g.error)==null?void 0:m.code,w=(S=g==null?void 0:g.error)==null?void 0:S.message,U=typeof w=="string"?w:w==null?void 0:w.value;y&&(i=String(y)),U&&(o=U)}catch(g){}else if(d){let g=n.match(/<m:code>([^<]+)<\/m:code>/),y=n.match(/<m:message(?:\s[^>]*)?>([^<]+)<\/m:message>/);g!=null&&g[1]&&(i=g[1]),y!=null&&y[1]&&(o=y[1])}return new x(o,V(c({status:t},i!==void 0?{code:i}:{}),{odataError:s,request:e}))}var R=class extends x{constructor(e,t){super(e,c(c({status:t.status,code:t.scriptError},t.odataError!==void 0?{odataError:t.odataError}:{}),t.request!==void 0?{request:t.request}:{})),this.name="FMScriptError",this.scriptError=t.scriptError,t.scriptResult!==void 0&&(this.scriptResult=t.scriptResult)}};function K(r){return r instanceof x}function ae(r){return r instanceof R}var ve=/^(basic|bearer|negotiate|digest)\s+\S/i;async function Ae(r){let e=typeof r=="function"?await r():r;if(typeof e!="string"||e.length===0)throw new TypeError("fms-odata-js: token resolver produced an empty value");return ve.test(e)?e:`Bearer ${e}`}function ce(r,e){let t=`${r}:${e}`;return`Basic ${typeof Buffer!="undefined"?Buffer.from(t,"utf8").toString("base64"):btoa(unescape(encodeURIComponent(t)))}`}function ue(r){return`Bearer ${r}`}function Ie(r){let e=r.filter(n=>n!==void 0);if(e.length===0)return;if(e.length===1)return e[0];let t=new AbortController;for(let n of e){if(n.aborted)return t.abort(n.reason),t.signal;n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}var je={json:"application/json",xml:"application/xml",text:"text/plain",binary:"application/octet-stream",none:"*/*"};async function b(r,e,t={}){return de(r,e,t,!1)}async function de(r,e,t,n){var h,m;let i=(h=t.method)!=null?h:"GET",o=new Headers(t.headers);o.set("Authorization",await Ae(r.token)),o.has("OData-Version")||o.set("OData-Version","4.0"),o.has("OData-MaxVersion")||o.set("OData-MaxVersion","4.0"),o.has("Accept")||o.set("Accept",je[(m=t.accept)!=null?m:"json"]);let s=new AbortController,a=r.timeoutMs&&r.timeoutMs>0?setTimeout(()=>s.abort(new Error(`Timeout after ${r.timeoutMs}ms`)),r.timeoutMs):void 0,u=Ie([t.signal,r.timeoutMs?s.signal:void 0]),d;try{d=await r.fetch(e,c(c({method:i,headers:o,keepalive:!0},t.body!==void 0?{body:t.body}:{}),u?{signal:u}:{}))}catch(S){throw a&&clearTimeout(a),S}if(a&&clearTimeout(a),d.status===401&&r.onUnauthorized&&!n)return await r.onUnauthorized(),de(r,e,t,!0);if(!d.ok)throw await se(d,{url:e,method:i});return d}async function l(r,e,t={}){var o,s;let n=await b(r,e,t);if(n.status===204)return;let i=((o=n.headers.get("content-type"))!=null?o:"").toLowerCase();if(!i.includes("json")){let a=await n.text();if(!a)return;try{return JSON.parse(a)}catch(u){throw new x(`Expected JSON response, got "${i||"no content-type"}"`,{status:n.status,odataError:a,request:{url:e,method:(s=t.method)!=null?s:"GET"}})}}return await n.json()}function $(r){return r.replace(/'/g,"''")}function Ue(r){if(!(r instanceof Date)||Number.isNaN(r.getTime()))throw new TypeError("formatDateTime: invalid Date");return r.toISOString().replace(/\.\d{3}Z$/,"Z")}function E(r){if(r==null)return"null";if(typeof r=="string")return`'${$(r)}'`;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`formatLiteral: cannot encode non-finite number: ${r}`);return String(r)}if(typeof r=="boolean")return r?"true":"false";if(r instanceof Date)return Ue(r);throw new TypeError(`formatLiteral: unsupported OData literal type: ${typeof r}`)}function p(r){return encodeURIComponent(r)}function D(r){return encodeURIComponent(r).replace(/%2C/gi,",").replace(/%24/g,"$").replace(/%3D/g,"=").replace(/%3B/g,";").replace(/%28/g,"(").replace(/%29/g,")")}function pe(r){let e=[];for(let[t,n]of r)n===""||n===void 0||n===null||e.push(`${t}=${D(n)}`);return e.join("&")}function Ve(r){return typeof TextEncoder!="undefined"?new TextEncoder().encode(r).byteLength:Buffer.byteLength(r,"utf8")}function le(r){let e=typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return`${r}_${e}`}function he(r,e,t){let n=[];(t==null?void 0:t.$top)!==void 0&&n.push(`$top=${D(String(t.$top))}`),(t==null?void 0:t.$skip)!==void 0&&n.push(`$skip=${D(String(t.$skip))}`),t!=null&&t.$filter&&n.push(`$filter=${D(t.$filter)}`),t!=null&&t.$select&&n.push(`$select=${D(t.$select)}`);let i=n.join("&"),o=p(e);return i?`${r}/${o}?${i}`:`${r}/${o}`}function fe(r,e,t){let n=p(e),i;if(typeof t=="number")i=String(t);else if(typeof t=="string")i=`'${t.replace(/'/g,"''")}'`;else if(typeof t=="boolean")i=t?"true":"false";else throw new TypeError("Batch: unsupported key type");return`${r}/${n}(${i})`}var B=class{constructor(e){this._ops=[];this._handles=[];this._baseUrl=e}get _operations(){return this._ops}get _handleSlots(){return this._handles}create(e,t){let n=he(this._baseUrl,e),i,o,s=new Promise((u,d)=>{i=u,o=d}),a=this._handles.length;return this._handles.push({resolve:i,reject:o}),this._ops.push({method:"POST",path:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{__brand:"BatchHandle",_promise:s,_index:a}}patch(e,t,n,i){let o=fe(this._baseUrl,e,t),s={"Content-Type":"application/json"};i!=null&&i.ifMatch&&(s["If-Match"]=i.ifMatch);let a,u,d=new Promise((m,S)=>{a=m,u=S}),h=this._handles.length;return this._handles.push({resolve:a,reject:u}),this._ops.push({method:"PATCH",path:o,headers:s,body:JSON.stringify(n)}),{__brand:"BatchHandle",_promise:d,_index:h}}delete(e,t,n){let i=fe(this._baseUrl,e,t),o={};n!=null&&n.ifMatch&&(o["If-Match"]=n.ifMatch);let s,a,u=new Promise((h,m)=>{s=h,a=m}),d=this._handles.length;return this._handles.push({resolve:s,reject:a}),this._ops.push({method:"DELETE",path:i,headers:o}),{__brand:"BatchHandle",_promise:u,_index:d}}},P=class{constructor(e){this._parts=[];this._changesets=[];this._client=e}add(e){let t=he(this._client.baseUrl,e.entitySet,e.query),n,i,s={__brand:"BatchHandle",_promise:new Promise((a,u)=>{n=a,i=u}),_index:this._parts.length};return this._parts.push({type:"read",content:{method:"GET",path:t},handle:s}),s}changeset(e){let t=new B(this._client.baseUrl);e(t),this._changesets.push(t),this._parts.push({type:"changeset",content:t})}_serialize(){let e=le("batch"),t=[];for(let n of this._parts)if(t.push(`--${e}`),n.type==="read"){let i=n.content;t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${i.method} ${i.path} HTTP/1.1`)}else if(n.type==="changeset"){let i=n.content,o=le("changeset");t.push("Content-Type: multipart/mixed; boundary="+o),t.push("");for(let s of i._operations){if(t.push(`--${o}`),t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${s.method} ${s.path} HTTP/1.1`),s.headers)for(let[a,u]of Object.entries(s.headers))t.push(`${a}: ${u}`);s.body&&(t.push(`Content-Length: ${Ve(s.body)}`),t.push(""),t.push(s.body))}t.push(`--${o}--`)}return t.push(`--${e}--`),{boundary:e,body:t.join(`\r
2
- `)}}async send(e={}){var s;let{boundary:t,body:n}=this._serialize(),i=await b(this._client._ctx,`${this._client.baseUrl}/$batch`,c({method:"POST",headers:{"Content-Type":`multipart/mixed; boundary=${t}`},body:n,accept:"none"},e.signal?{signal:e.signal}:{})),o=await i.text();return this._parseResponse(o,(s=i.headers.get("content-type"))!=null?s:"")}_parseResponse(e,t){let n=t.match(/boundary=([^;\s]+)/),i=n==null?void 0:n[1];if(!i)throw new Error("Batch response missing boundary in Content-Type");let o=e.split(`--${i}`),s=[],a=0;for(let u=1;u<o.length-1;u++){let d=o[u].trim();if(!d||d==="--")continue;let h=this._parts[a];if(h){if(h.type==="read"){let m=this._parseHttpPart(d);s.push(m),h.handle&&this._resolveHandle(h.handle,m),a++}else if(h.type==="changeset"){let m=h.content,S=this._parseChangesetResponse(d,m);s.push(...S);let g=S.find(y=>!y.ok);for(let y=0;y<m._handleSlots.length;y++){let w=m._handleSlots[y],U=S[y];g?w.reject(new Error(`Changeset failed: ${g.status}`)):U?w.resolve(U.body):w.resolve(void 0)}a++}}}return{responses:s,ok:s.every(u=>u.ok)}}_parseHttpPart(e){let t=e.indexOf(`\r
1
+ "use strict";var FMSODataLib=(()=>{var G=Object.defineProperty,Re=Object.defineProperties,ke=Object.getOwnPropertyDescriptor,Me=Object.getOwnPropertyDescriptors,Fe=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols;var X=Object.prototype.hasOwnProperty,ie=Object.prototype.propertyIsEnumerable;var ne=(r,e,t)=>e in r?G(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e)=>{for(var t in e||(e={}))X.call(e,t)&&ne(r,t,e[t]);if(J)for(var t of J(e))ie.call(e,t)&&ne(r,t,e[t]);return r},V=(r,e)=>Re(r,Me(e));var oe=(r,e)=>{var t={};for(var n in r)X.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&J)for(var n of J(r))e.indexOf(n)<0&&ie.call(r,n)&&(t[n]=r[n]);return t};var De=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},Pe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fe(e))!X.call(r,i)&&i!==t&&G(r,i,{get:()=>e[i],enumerable:!(n=ke(e,i))||n.enumerable});return r};var Ce=r=>Pe(G({},"__esModule",{value:!0}),r);var at={};De(at,{Batch:()=>P,Changeset:()=>B,ContainerRef:()=>C,EntityRef:()=>v,FIELD_DEFAULTS:()=>Se,FIELD_TYPES:()=>L,FMOData:()=>W,FMODataError:()=>x,FMSOData:()=>W,FMSODataError:()=>x,FMScriptError:()=>$,FM_CONTAINER_SUPPORTED_MIME_TYPES:()=>H,FM_VERSION_MATRIX:()=>O,FM_VERSION_NAMES:()=>me,Filter:()=>f,MetadataFetcher:()=>M,ODATA_PROTOCOL_VERSION:()=>ge,Query:()=>A,SchemaEditor:()=>I,ScriptInvoker:()=>_,WebhookManager:()=>j,basicAuth:()=>ce,bearerAuth:()=>ue,buildContainerJsonBody:()=>F,filterFactory:()=>re,hasFeature:()=>Q,hasQueryOption:()=>ye,isFMODataError:()=>K,isFMSODataError:()=>K,isFMScriptError:()=>ae,minVersionForFeature:()=>be,parseFieldType:()=>Y,parseServerVersion:()=>z,parseVersionString:()=>k,sniffContainerMime:()=>ee,toBase64:()=>te});var x=class extends Error{constructor(e,t){super(e),this.name="FMSODataError",this.status=t.status,t.code!==void 0&&(this.code=t.code),t.odataError!==void 0&&(this.odataError=t.odataError),t.request!==void 0&&(this.request=t.request)}};async function se(r,e){var h,m,S;let t=r.status,n="";try{n=await r.text()}catch(g){}let i,o=r.statusText||`HTTP ${t}`,s=n,c=((h=r.headers.get("content-type"))!=null?h:"").toLowerCase(),a=c.includes("json")||n.startsWith("{")&&n.endsWith("}"),d=c.includes("xml")||n.trimStart().startsWith("<?xml")||n.includes("<m:error");if(a)try{let g=JSON.parse(n);s=g;let y=(m=g==null?void 0:g.error)==null?void 0:m.code,w=(S=g==null?void 0:g.error)==null?void 0:S.message,U=typeof w=="string"?w:w==null?void 0:w.value;y&&(i=String(y)),U&&(o=U)}catch(g){}else if(d){let g=n.match(/<m:code>([^<]+)<\/m:code>/),y=n.match(/<m:message(?:\s[^>]*)?>([^<]+)<\/m:message>/);g!=null&&g[1]&&(i=g[1]),y!=null&&y[1]&&(o=y[1])}return new x(o,V(u({status:t},i!==void 0?{code:i}:{}),{odataError:s,request:e}))}var $=class extends x{constructor(e,t){super(e,u(u({status:t.status,code:t.scriptError},t.odataError!==void 0?{odataError:t.odataError}:{}),t.request!==void 0?{request:t.request}:{})),this.name="FMScriptError",this.scriptError=t.scriptError,t.scriptResult!==void 0&&(this.scriptResult=t.scriptResult)}};function K(r){return r instanceof x}function ae(r){return r instanceof $}var ve=/^(basic|bearer|negotiate|digest)\s+\S/i;async function Ae(r){let e=typeof r=="function"?await r():r;if(typeof e!="string"||e.length===0)throw new TypeError("fms-odata-js: token resolver produced an empty value");return ve.test(e)?e:`Bearer ${e}`}function ce(r,e){let t=`${r}:${e}`;return`Basic ${typeof Buffer!="undefined"?Buffer.from(t,"utf8").toString("base64"):btoa(unescape(encodeURIComponent(t)))}`}function ue(r){return`Bearer ${r}`}function Ie(r){let e=r.filter(n=>n!==void 0);if(e.length===0)return;if(e.length===1)return e[0];let t=new AbortController;for(let n of e){if(n.aborted)return t.abort(n.reason),t.signal;n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}var je={json:"application/json",xml:"application/xml",text:"text/plain",binary:"application/octet-stream",none:"*/*"};async function b(r,e,t={}){return de(r,e,t,!1)}async function de(r,e,t,n){var h,m;let i=(h=t.method)!=null?h:"GET",o=new Headers(t.headers);o.set("Authorization",await Ae(r.token)),o.has("OData-Version")||o.set("OData-Version","4.0"),o.has("OData-MaxVersion")||o.set("OData-MaxVersion","4.0"),o.has("Accept")||o.set("Accept",je[(m=t.accept)!=null?m:"json"]);let s=new AbortController,c=r.timeoutMs&&r.timeoutMs>0?setTimeout(()=>s.abort(new Error(`Timeout after ${r.timeoutMs}ms`)),r.timeoutMs):void 0,a=Ie([t.signal,r.timeoutMs?s.signal:void 0]),d;try{d=await r.fetch(e,u(u({method:i,headers:o,keepalive:!0},t.body!==void 0?{body:t.body}:{}),a?{signal:a}:{}))}catch(S){throw c&&clearTimeout(c),S}if(c&&clearTimeout(c),d.status===401&&r.onUnauthorized&&!n)return await r.onUnauthorized(),de(r,e,t,!0);if(!d.ok)throw await se(d,{url:e,method:i});return d}async function l(r,e,t={}){var o,s;let n=await b(r,e,t);if(n.status===204)return;let i=((o=n.headers.get("content-type"))!=null?o:"").toLowerCase();if(!i.includes("json")){let c=await n.text();if(!c)return;try{return JSON.parse(c)}catch(a){throw new x(`Expected JSON response, got "${i||"no content-type"}"`,{status:n.status,odataError:c,request:{url:e,method:(s=t.method)!=null?s:"GET"}})}}return await n.json()}function R(r){return r.replace(/'/g,"''")}function Ue(r){if(!(r instanceof Date)||Number.isNaN(r.getTime()))throw new TypeError("formatDateTime: invalid Date");return r.toISOString().replace(/\.\d{3}Z$/,"Z")}function E(r){if(r==null)return"null";if(typeof r=="string")return`'${R(r)}'`;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`formatLiteral: cannot encode non-finite number: ${r}`);return String(r)}if(typeof r=="boolean")return r?"true":"false";if(r instanceof Date)return Ue(r);throw new TypeError(`formatLiteral: unsupported OData literal type: ${typeof r}`)}function p(r){return encodeURIComponent(r)}function D(r){return encodeURIComponent(r).replace(/%2C/gi,",").replace(/%24/g,"$").replace(/%3D/g,"=").replace(/%3B/g,";").replace(/%28/g,"(").replace(/%29/g,")")}function pe(r){let e=[];for(let[t,n]of r)n===""||n===void 0||n===null||e.push(`${t}=${D(n)}`);return e.join("&")}function Ve(r){return typeof TextEncoder!="undefined"?new TextEncoder().encode(r).byteLength:Buffer.byteLength(r,"utf8")}function le(r){let e=typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return`${r}_${e}`}function he(r,e,t){let n=[];(t==null?void 0:t.$top)!==void 0&&n.push(`$top=${D(String(t.$top))}`),(t==null?void 0:t.$skip)!==void 0&&n.push(`$skip=${D(String(t.$skip))}`),t!=null&&t.$filter&&n.push(`$filter=${D(t.$filter)}`),t!=null&&t.$select&&n.push(`$select=${D(t.$select)}`);let i=n.join("&"),o=p(e);return i?`${r}/${o}?${i}`:`${r}/${o}`}function fe(r,e,t){let n=p(e),i;if(typeof t=="number")i=String(t);else if(typeof t=="string")i=`'${t.replace(/'/g,"''")}'`;else if(typeof t=="boolean")i=t?"true":"false";else throw new TypeError("Batch: unsupported key type");return`${r}/${n}(${i})`}var B=class{constructor(e){this._ops=[];this._handles=[];this._baseUrl=e}get _operations(){return this._ops}get _handleSlots(){return this._handles}create(e,t){let n=he(this._baseUrl,e),i,o,s=new Promise((a,d)=>{i=a,o=d}),c=this._handles.length;return this._handles.push({resolve:i,reject:o}),this._ops.push({method:"POST",path:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{__brand:"BatchHandle",_promise:s,_index:c}}patch(e,t,n,i){let o=fe(this._baseUrl,e,t),s={"Content-Type":"application/json"};i!=null&&i.ifMatch&&(s["If-Match"]=i.ifMatch);let c,a,d=new Promise((m,S)=>{c=m,a=S}),h=this._handles.length;return this._handles.push({resolve:c,reject:a}),this._ops.push({method:"PATCH",path:o,headers:s,body:JSON.stringify(n)}),{__brand:"BatchHandle",_promise:d,_index:h}}delete(e,t,n){let i=fe(this._baseUrl,e,t),o={};n!=null&&n.ifMatch&&(o["If-Match"]=n.ifMatch);let s,c,a=new Promise((h,m)=>{s=h,c=m}),d=this._handles.length;return this._handles.push({resolve:s,reject:c}),this._ops.push({method:"DELETE",path:i,headers:o}),{__brand:"BatchHandle",_promise:a,_index:d}}},P=class{constructor(e){this._parts=[];this._changesets=[];this._client=e}add(e){let t=he(this._client.baseUrl,e.entitySet,e.query),n,i,s={__brand:"BatchHandle",_promise:new Promise((c,a)=>{n=c,i=a}),_index:this._parts.length};return this._parts.push({type:"read",content:{method:"GET",path:t},handle:s}),s}changeset(e){let t=new B(this._client.baseUrl);e(t),this._changesets.push(t),this._parts.push({type:"changeset",content:t})}_serialize(){let e=le("batch"),t=[];for(let n of this._parts)if(t.push(`--${e}`),n.type==="read"){let i=n.content;t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${i.method} ${i.path} HTTP/1.1`)}else if(n.type==="changeset"){let i=n.content,o=le("changeset");t.push("Content-Type: multipart/mixed; boundary="+o),t.push("");for(let s of i._operations){if(t.push(`--${o}`),t.push("Content-Type: application/http"),t.push("Content-Transfer-Encoding: binary"),t.push(""),t.push(`${s.method} ${s.path} HTTP/1.1`),s.headers)for(let[c,a]of Object.entries(s.headers))t.push(`${c}: ${a}`);s.body&&(t.push(`Content-Length: ${Ve(s.body)}`),t.push(""),t.push(s.body))}t.push(`--${o}--`)}return t.push(`--${e}--`),{boundary:e,body:t.join(`\r
2
+ `)}}async send(e={}){var s;let{boundary:t,body:n}=this._serialize(),i=await b(this._client._ctx,`${this._client.baseUrl}/$batch`,u({method:"POST",headers:{"Content-Type":`multipart/mixed; boundary=${t}`},body:n,accept:"none"},e.signal?{signal:e.signal}:{})),o=await i.text();return this._parseResponse(o,(s=i.headers.get("content-type"))!=null?s:"")}_parseResponse(e,t){let n=t.match(/boundary=([^;\s]+)/),i=n==null?void 0:n[1];if(!i)throw new Error("Batch response missing boundary in Content-Type");let o=e.split(`--${i}`),s=[],c=0;for(let a=1;a<o.length-1;a++){let d=o[a].trim();if(!d||d==="--")continue;let h=this._parts[c];if(h){if(h.type==="read"){let m=this._parseHttpPart(d);s.push(m),h.handle&&this._resolveHandle(h.handle,m),c++}else if(h.type==="changeset"){let m=h.content,S=this._parseChangesetResponse(d,m);s.push(...S);let g=S.find(y=>!y.ok);for(let y=0;y<m._handleSlots.length;y++){let w=m._handleSlots[y],U=S[y];g?w.reject(new Error(`Changeset failed: ${g.status}`)):U?w.resolve(U.body):w.resolve(void 0)}c++}}}return{responses:s,ok:s.every(a=>a.ok)}}_parseHttpPart(e){let t=e.indexOf(`\r
3
3
  \r
4
4
  `),n=t>=0?e.slice(t+4):e,i=n.indexOf(`\r
5
5
  \r
6
- `),o=i>=0?n.slice(0,i):n,s=i>=0?n.slice(i+4).trim():"",a=o.match(/^HTTP\/1\.\d (\d+)/),u=a?parseInt(a[1],10):0,d;if(s&&o.toLowerCase().includes("application/json"))try{d=JSON.parse(s)}catch(h){d=s}else s&&(d=s);return{status:u,body:d,headers:new Headers,ok:u>=200&&u<300}}_parseChangesetResponse(e,t){let n=e.match(/boundary=([^\s]+)/),i=n==null?void 0:n[1];if(!i)return[this._parseHttpPart(e)];let o=e.split(`--${i}`),s=[];for(let a=1;a<o.length-1;a++){let u=o[a].trim();!u||u==="--"||s.push(this._parseHttpPart(u))}return s}_resolveHandle(e,t){}};var me={20:"Claris FileMaker 2023",21:"Claris FileMaker 2024",22:"Claris FileMaker 2025",26:"Claris FileMaker 2026",future:"Future / next"},ge="4.01";var _={20:{major:"20",name:"Claris FileMaker 2023",releaseYear:2023,internalVersion:"20.x",status:"supported",odataProtocolVersion:"4.0",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!1,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!1,parameterizedFilters:!1,simplifiedQuerySyntax:!1,nestedQueries:!1,batchPreferenceInheritance:!1,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!1,aiAnnotation:!1,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!1},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},21:{major:"21",name:"Claris FileMaker 2024",releaseYear:2024,internalVersion:"21.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},22:{major:"22",name:"Claris FileMaker 2025",releaseYear:2025,internalVersion:"22.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},26:{major:"26",name:"Claris FileMaker 2026",releaseYear:2026,internalVersion:"26.x",status:"current",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},future:{major:"future",name:"Future / next",releaseYear:null,internalVersion:"unknown",status:"future",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}}};function Q(r,e){var t,n;return(n=(t=_[r])==null?void 0:t.features[e])!=null?n:!1}function ye(r,e){var t,n;return(n=(t=_[r])==null?void 0:t.queryOptions[e])!=null?n:!1}function be(r){let e=["20","21","22","26"];for(let t of e)if(_[t].features[r])return t;return null}function k(r){let e=r.trim().match(/(\d+)\.(\d+)\.(\d+)/);return e?{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10),raw:r.trim()}:null}function z(r){if(!r||typeof r!="string")return null;let e=r.match(/Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["'][^>]*String\s*=\s*["']([^"']+)["']/);if(e){let s=k(e[1]);if(s)return s}let t=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["']/);if(t){let s=k(t[1]);if(s)return s}let n=r.match(/Term\s*=\s*["']ServerVersion["'][^>]*String\s*=\s*["']([^"']+)["']/i);if(n){let s=k(n[1]);if(s&&s.major>=17)return s}let i=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']ServerVersion["']/i);if(i){let s=k(i[1]);if(s&&s.major>=17)return s}let o=r.match(/Term\s*=\s*["'][^"']*Version[^"']*["'][^>]*String\s*=\s*["'][^"']*?(\d{2,}\.\d+\.\d+(?:\.\d+)?)[^"']*?["']/i);if(o){let s=k(o[1]);if(s&&s.major>=17)return s}return null}var L=["NUMERIC","DECIMAL","INT","DATE","TIME","TIMESTAMP","VARCHAR","CHARACTER VARYING","BLOB","VARBINARY","LONGVARBINARY","BINARY VARYING"],Se=["USER","USERNAME","CURRENT_USER","CURRENT_DATE","CURDATE","CURRENT_TIME","CURTIME","CURRENT_TIMESTAMP","CURTIMESTAMP"];function Y(r){let e=r.match(/\((\d+)\)/),t=r.match(/\[(\d+)\]/);return{baseType:r.replace(/\(.*?\)/,"").replace(/\[.*?\]/,"").trim(),length:e?parseInt(e[1],10):void 0,repetitions:t?parseInt(t[1],10):void 0}}function Be(r,e){return r===void 0?e:r==="true"}function Z(r,e){let t=new RegExp(`${e}="([^"]*)"`,"i"),n=r.match(t);return n==null?void 0:n[1]}function q(r){let e={},t=/(\w+)="([^"]*)"/g,n;for(;(n=t.exec(r))!==null;)e[n[1]]=n[2];return e}function T(r,e){let t=[],n=new RegExp(`<([\\w]+:)?${e}\\b[^>]*>`,"gi"),i;for(;(i=n.exec(r))!==null;){let o=i[0];if(/\/>\s*$/.test(o)){t.push(o);continue}let s=i.index,a=new RegExp(`</([\\w]+:)?${e}>`,"gi");a.lastIndex=n.lastIndex;let u=a.exec(r);u&&t.push(r.slice(s,u.index+u[0].length))}return t}function N(r,e){let n=new RegExp(`<(?:[\\w]+:)?${e}\\b[^>]*>`,"i").exec(r);if(!n)return;let i=n.index+n[0].length,o=new RegExp(`</(?:[\\w]+:)?${e}>`,"i");o.lastIndex=i;let s=o.exec(r);if(s)return r.slice(i,s.index)}function Le(r){var i,o;let e=q(r),t=Be(e.Nullable,!0),n={name:(i=e.Name)!=null?i:"",type:(o=e.Type)!=null?o:"",nullable:t};if(e.MaxLength!==void 0){let s=parseInt(e.MaxLength,10);Number.isNaN(s)||(n.maxLength=s)}return n}function Ne(r){var o,s;let e=q(r),t=(o=e.Type)!=null?o:"",n=t.startsWith("Collection("),i=n?t.slice(11,-1):t;return{name:(s=e.Name)!=null?s:"",target:i,collection:n}}function qe(r){let e=[],t=T(r,"PropertyRef");for(let n of t){let i=Z(n,"Name");i&&e.push(i)}return e}function He(r){var a,u;let e=(a=Z(r,"Name"))!=null?a:"",t=[],n=[],i=[],o=(u=N(r,"EntityType"))!=null?u:r,s=T(o,"Key")[0];s&&t.push(...qe(s));for(let d of T(o,"Property"))n.push(Le(d));for(let d of T(o,"NavigationProperty"))i.push(Ne(d));return{name:e,keys:t,properties:n,navigationProperties:i}}function We(r){var t,n;let e=q(r);return{name:(t=e.Name)!=null?t:"",entityType:(n=e.EntityType)!=null?n:""}}function Je(r){var e;return(e=z(r))!=null?e:void 0}function Ge(r){var s,a,u,d;let e=(s=Z(r,"Name"))!=null?s:"",t=q(r),n=t.IsBound==="true"?t.EntityType:void 0,i=[],o=(a=N(r,"Action"))!=null?a:r;for(let h of T(o,"Parameter")){let m=q(h);i.push({name:(u=m.Name)!=null?u:"",type:(d=m.Type)!=null?d:""})}return n!==void 0?{name:e,boundTo:n,parameters:i}:{name:e,parameters:i}}function Qe(r){var e,t,n;try{let i=N(r,"DataServices");if(!i)throw new Error("Missing <edmx:DataServices> in metadata");let o=T(i,"Schema")[0];if(!o)throw new Error("Missing <Schema> in metadata");let s=(e=Z(o,"Namespace"))!=null?e:"",a=(t=N(o,"Schema"))!=null?t:o,u=[];for(let y of T(a,"EntityType"))u.push(He(y));let d=[],h=T(a,"EntityContainer")[0];if(h){let y=(n=N(h,"EntityContainer"))!=null?n:h;for(let w of T(y,"EntitySet"))d.push(We(w))}let m=[];for(let y of T(a,"Action"))m.push(Ge(y));let S=Je(r),g={namespace:s,entityTypes:u,entitySets:d,actions:m,raw:r};return S&&(g.serverVersion=S,g.productVersion=S.raw),g}catch(i){let o=i instanceof Error?i.message:String(i);throw new x(`Failed to parse $metadata: ${o}`,{status:0,odataError:r.slice(0,500)})}}async function ze(r,e,t={}){return(await b(r,`${e}/$metadata`,c({method:"GET",accept:"xml"},t.signal?{signal:t.signal}:{}))).text()}var M=class{constructor(e,t){this._ctx=e;this._baseUrl=t}async fetchXml(e={}){return ze(this._ctx,this._baseUrl,e)}async fetch(e={}){if(!e.refresh&&this._cache)return this._cache;let t=this.fetchXml(e).then(Qe);return this._cache=t,t}};var H=["image/png","image/jpeg","image/gif","image/tiff","application/pdf"];function Ye(r){var e;return((e=r.split(";")[0])!=null?e:"").trim().toLowerCase()}function Ze(r){let e=Ye(r);return H.includes(e)}function ee(r){if(r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71&&r[4]===13&&r[5]===10&&r[6]===26&&r[7]===10)return"image/png";if(r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(r.length>=4&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56)return"image/gif";if(r.length>=4&&(r[0]===73&&r[1]===73&&r[2]===42&&r[3]===0||r[0]===77&&r[1]===77&&r[2]===0&&r[3]===42))return"image/tiff";if(r.length>=4&&r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70)return"application/pdf"}var C=class{constructor(e,t){if(!t)throw new TypeError("ContainerRef: fieldName is required");this._entity=e,this.fieldName=t}url(){return`${this._entity.toURL()}/${p(this.fieldName)}`}_valueUrl(){return`${this.url()}/$value`}async get(e={}){var u;let t=await b(this._entity._client._ctx,this._valueUrl(),c({method:"GET",accept:"none"},e.signal?{signal:e.signal}:{})),n=(u=t.headers.get("content-type"))!=null?u:"",i=t.headers.get("content-disposition"),o=i?Xe(i):void 0,s=await t.blob(),a={blob:s,contentType:n,size:s.size};return o!==void 0&&(a.filename=o),a}async getStream(e={}){let t=await b(this._entity._client._ctx,this._valueUrl(),c({method:"GET",accept:"none"},e.signal?{signal:e.signal}:{}));if(!t.body)throw new TypeError("ContainerRef.getStream: response has no body");return t.body}async upload(e,t={}){var a;let n=(a=e.encoding)!=null?a:"binary",i=await et(e.data),o=e.contentType;if(!o){let u=ee(i);if(!u)throw new TypeError(`ContainerRef.upload: contentType is required and could not be sniffed from the payload. Pass a contentType explicitly (one of ${H.join(", ")}).`);o=u}if(n==="binary"){if(!Ze(o))throw new TypeError(`ContainerRef.upload (binary): contentType "${o}" is not a FileMaker-supported container type. Use one of ${H.join(", ")}, or switch to { encoding: 'base64' }.`);let u={"Content-Type":o};e.filename&&(u["Content-Disposition"]=Ke(e.filename));let d=new ArrayBuffer(i.byteLength);new Uint8Array(d).set(i),await b(this._entity._client._ctx,this.url(),c({method:"PATCH",headers:u,body:d,accept:"none"},t.signal?{signal:t.signal}:{}));return}let s=F({[this.fieldName]:c({data:te(i),contentType:o},e.filename?{filename:e.filename}:{})});await b(this._entity._client._ctx,this._entity.toURL(),c({method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(s),accept:"none"},t.signal?{signal:t.signal}:{}))}async delete(e={}){let t={[this.fieldName]:null};await b(this._entity._client._ctx,this._entity.toURL(),c({method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(t),accept:"none"},e.signal?{signal:e.signal}:{}))}};function F(r,e={}){let t=c({},e);for(let[n,i]of Object.entries(r)){if(!i.contentType)throw new TypeError(`buildContainerJsonBody: "${n}".contentType is required`);t[n]=i.data,t[`${n}@com.filemaker.odata.ContentType`]=i.contentType,i.filename&&(t[`${n}@com.filemaker.odata.Filename`]=i.filename)}return t}function Xe(r){let e=r.match(/filename\*\s*=\s*([^']+)'[^']*'([^;]+)/i);if(e){let n=e[1].trim().toLowerCase(),i=e[2].trim();try{let o=decodeURIComponent(i);return o}catch(o){}}let t=r.match(/filename\s*=\s*("([^"\\]*(?:\\.[^"\\]*)*)"|([^;]+))/i);if(t){let n=t[2];if(n!==void 0)return n.replace(/\\(.)/g,"$1").trim();let i=t[3];if(i!==void 0)return i.trim()}}function Ke(r){let e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,t=/[^\x00-\x7F]/.test(r),n;return e.test(r)?n=`inline; filename=${r}`:n=`inline; filename="${r.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,'\\"')}"`,t?`${n}; filename*=UTF-8''${encodeURIComponent(r)}`:n}async function et(r){if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);let e=await r.arrayBuffer();return new Uint8Array(e)}function te(r){if(typeof Buffer!="undefined")return Buffer.from(r).toString("base64");let e="",t=32768;for(let n=0;n<r.length;n+=t)e+=String.fromCharCode.apply(null,Array.from(r.subarray(n,n+t)));return btoa(e)}function tt(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("ScriptInvoker: key must be a finite number");return String(r)}if(typeof r=="string")return`'${$(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("ScriptInvoker: unsupported key type")}var O=class{constructor(e,t={}){this._client=e,t.entitySet!==void 0&&(this.entitySet=t.entitySet),t.key!==void 0&&(this.key=t.key)}url(e){if(!e)throw new TypeError("ScriptInvoker: script name is required");return this._urlForSegment(`Script.${p(e)}`)}urlById(e){if(!Number.isFinite(e))throw new TypeError("ScriptInvoker: fmsid must be a finite number");return this._urlForSegment(`Script.FMSID:${e}`)}_urlForSegment(e){let t=this._client.baseUrl;if(this.entitySet===void 0)return`${t}/${e}`;let n=p(this.entitySet);return this.key===void 0?`${t}/${n}/${e}`:`${t}/${n}(${tt(this.key)})/${e}`}async run(e,t={}){return this._runAtUrl(this.url(e),t)}async runById(e,t={}){return this._runAtUrl(this.urlById(e),t)}async _runAtUrl(e,t){let n={},i;t.parameter!==void 0&&(n["Content-Type"]="application/json",i=JSON.stringify({scriptParameterValue:t.parameter}));let o="POST",s=await l(this._client._ctx,e,c(V(c({method:o,headers:n},i!==void 0?{body:i}:{}),{accept:"json"}),t.signal?{signal:t.signal}:{}));return rt(s,{url:e,method:o})}};function rt(r,e){let t=nt(r),n=t.scriptResult,i,o;if(n!==null&&typeof n=="object"&&"resultParameter"in n){let a=n;o=a.code!==void 0?String(a.code):"0",i=a.resultParameter!==void 0?String(a.resultParameter):void 0}else o=t.scriptError!==void 0?String(t.scriptError):"0",i=n!==void 0?typeof n=="string"?n:JSON.stringify(n):void 0;if(o!=="0")throw new R(`FileMaker script error ${o}`,V(c({status:200,scriptError:o},i!==void 0?{scriptResult:i}:{}),{odataError:r,request:e}));let s={scriptError:o,raw:r};return i!==void 0&&(s.scriptResult=i),s}function nt(r){if(r===null||typeof r!="object")return{};let e=r;if("scriptError"in e||"scriptResult"in e)return e;for(let t of Object.values(e))if(t&&typeof t=="object"){let n=t;if("scriptError"in n||"scriptResult"in n)return n}return{}}function xe(r,e,t){return new O(r).run(e,t)}function we(r,e,t){return new O(r).runById(e,t)}function Ee(r,e,t,n){return new O(r,{entitySet:e}).run(t,n)}function Te(r,e,t,n,i){return new O(r,{entitySet:e,key:t}).run(n,i)}function it(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("EntityRef: key must be a finite number");return String(r)}if(typeof r=="string")return`'${$(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("EntityRef: unsupported key type")}var v=class{constructor(e,t,n){this._client=e,this.entitySet=t,this.key=n}toURL(){return`${this._client.baseUrl}/${p(this.entitySet)}(${it(this.key)})`}async get(e={}){return await l(this._client._ctx,this.toURL(),c({method:"GET",accept:"json"},e.signal?{signal:e.signal}:{}))}async fieldValue(e,t={}){let n=`${this.toURL()}/${p(e)}`;return(await l(this._client._ctx,n,c({method:"GET",accept:"json"},t.signal?{signal:t.signal}:{}))).value}async patch(e,t={}){let n={"Content-Type":"application/json",Prefer:t.returnRepresentation?"return=representation":"return=minimal"};return t.ifMatch&&(n["If-Match"]=t.ifMatch),await l(this._client._ctx,this.toURL(),c({method:"PATCH",headers:n,body:JSON.stringify(e),accept:"json"},t.signal?{signal:t.signal}:{}))}async delete(e={}){let t={};e.ifMatch&&(t["If-Match"]=e.ifMatch),await b(this._client._ctx,this.toURL(),c({method:"DELETE",headers:t,accept:"none"},e.signal?{signal:e.signal}:{}))}async script(e,t={}){return Te(this._client,this.entitySet,this.key,e,t)}container(e){return new C(this,e)}async patchContainers(e,t={},n={}){let i={"Content-Type":"application/json",Prefer:n.returnRepresentation?"return=representation":"return=minimal"};n.ifMatch&&(i["If-Match"]=n.ifMatch);let o=F(e,t);await b(this._client._ctx,this.toURL(),c({method:"PATCH",headers:i,body:JSON.stringify(o),accept:"none"},n.signal?{signal:n.signal}:{}))}async getRefs(e,t={}){let n=`${this.toURL()}/${p(e)}/$ref`,i=await l(this._client._ctx,n,c({method:"GET",accept:"json"},t.signal?{signal:t.signal}:{}));return i!=null&&i.value?i.value:i!=null&&i["@odata.id"]?[i]:[]}async addRef(e,t,n={}){let i=`${this.toURL()}/${p(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await b(this._client._ctx,i,c({method:"POST",headers:o,body:s,accept:"none"},n.signal?{signal:n.signal}:{}))}async setRef(e,t,n={}){let i=`${this.toURL()}/${p(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await b(this._client._ctx,i,c({method:"PATCH",headers:o,body:s,accept:"none"},n.signal?{signal:n.signal}:{}))}async removeRef(e,t,n={}){let i=`${this.toURL()}/${p(e)}/$ref`,o={};n.ifMatch&&(o["If-Match"]=n.ifMatch),t!==void 0&&(i+=`('${$(this._refId(e,t))}')`),await b(this._client._ctx,i,c({method:"DELETE",headers:o,accept:"none"},n.signal?{signal:n.signal}:{}))}_refId(e,t){let n=e;return typeof t=="number"?`${n}(${t})`:`${n}('${$(t)}')`}};var f=class r{constructor(e){this.expr=e}toString(){return this.expr}and(e){return new r(`(${this.expr}) and (${r.coerce(e)})`)}or(e){return new r(`(${this.expr}) or (${r.coerce(e)})`)}not(){return new r(`not (${this.expr})`)}static coerce(e){return e instanceof r?e.expr:e}},re={eq:(r,e)=>new f(`${r} eq ${E(e)}`),ne:(r,e)=>new f(`${r} ne ${E(e)}`),gt:(r,e)=>new f(`${r} gt ${E(e)}`),ge:(r,e)=>new f(`${r} ge ${E(e)}`),lt:(r,e)=>new f(`${r} lt ${E(e)}`),le:(r,e)=>new f(`${r} le ${E(e)}`),startswith:(r,e)=>new f(`startswith(${r},${E(e)})`),endswith:(r,e)=>new f(`endswith(${r},${E(e)})`),contains:(r,e)=>new f(`contains(${r},${E(e)})`),and:(r,e)=>new f(`(${f.coerce(r)}) and (${f.coerce(e)})`),or:(r,e)=>new f(`(${f.coerce(r)}) or (${f.coerce(e)})`),not:r=>new f(`not (${f.coerce(r)})`),raw:r=>new f(r)};function _e(r){return typeof r=="function"?f.coerce(r(re)):f.coerce(r)}var A=class r{constructor(e,t,n){this._state={};this._baseUrl=e,this._entitySet=t,n&&(this._client=n)}select(...e){var t;return this._state.select=[...(t=this._state.select)!=null?t:[],...e],this}filter(e){let t=_e(e);return this._state.filter=this._state.filter?`(${this._state.filter}) and (${t})`:t,this}or(e){let t=_e(e);return this._state.filter=this._state.filter?`(${this._state.filter}) or (${t})`:t,this}expand(e,t){var i;let n={name:e};if(t){let o=new r("",e);t(o),n.options=o._state}return this._state.expand=[...(i=this._state.expand)!=null?i:[],n],this}orderby(e,t="asc"){var n;return this._state.orderby=[...(n=this._state.orderby)!=null?n:[],{field:e,dir:t}],this}top(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#top: expected non-negative integer, got ${e}`);return this._state.top=e,this}skip(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#skip: expected non-negative integer, got ${e}`);return this._state.skip=e,this}count(e=!0){return this._state.count=e,this}search(e){return this._state.search=e,this}apply(e){return this._state.apply=e,this}aggregate(e){let t=e.map(n=>`${n.field} with ${n.function} as ${n.alias}`);return this._state.apply=`aggregate(${t.join(",")})`,this}groupBy(e,t){let n=e.join(",");if(t&&t.length>0){let i=t.map(o=>`${o.field} with ${o.function} as ${o.alias}`);this._state.apply=`groupby((${n}),aggregate(${i.join(",")}))`}else this._state.apply=`groupby((${n}))`;return this}toURL(){let e=Oe(this._state,{topLevel:!0}),t=`${this._baseUrl}/${p(this._entitySet)}`;return e?`${t}?${e}`:t}byKey(e){if(!this._client)throw new Error("Query#byKey: no client attached (use FMSOData#from)");return new v(this._client,this._entitySet,e)}async create(e,t={}){if(!this._client)throw new Error("Query#create: no client attached (use FMSOData#from)");let n=`${this._baseUrl}/${p(this._entitySet)}`;return await l(this._client._ctx,n,c({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json"},t.signal?{signal:t.signal}:{}))}async createWithContainers(e,t,n={}){if(!this._client)throw new Error("Query#createWithContainers: no client attached (use FMSOData#from)");let i=`${this._baseUrl}/${p(this._entitySet)}`,o=F(t,e);return await l(this._client._ctx,i,c({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),accept:"json"},n.signal?{signal:n.signal}:{}))}async get(e={}){var i;if(!this._client)throw new Error("Query#get: no client attached (use FMSOData#from)");let t=await l(this._client._ctx,this.toURL(),c({method:"GET",accept:"json"},e.signal?{signal:e.signal}:{})),n={value:(i=t==null?void 0:t.value)!=null?i:[]};return t&&typeof t["@odata.count"]=="number"&&(n.count=t["@odata.count"]),t&&typeof t["@odata.nextLink"]=="string"&&(n.nextLink=t["@odata.nextLink"]),n}async script(e,t={}){if(!this._client)throw new Error("Query#script: no client attached (use FMSOData#from)");return Ee(this._client,this._entitySet,e,t)}};function Oe(r,e){let t=[];if(r.select&&r.select.length>0&&t.push(["$select",r.select.join(",")]),r.filter&&t.push(["$filter",r.filter]),r.expand&&r.expand.length>0){let n=r.expand.map(i=>{if(!i.options)return i.name;let o=Oe(i.options,{topLevel:!1});return o?`${i.name}(${o})`:i.name});t.push(["$expand",n.join(",")])}return r.orderby&&r.orderby.length>0&&t.push(["$orderby",r.orderby.map(n=>`${n.field} ${n.dir}`).join(",")]),r.top!==void 0&&t.push(["$top",String(r.top)]),r.skip!==void 0&&t.push(["$skip",String(r.skip)]),r.count&&t.push(["$count","true"]),r.search&&t.push(["$search",r.search]),r.apply&&t.push(["$apply",r.apply]),e.topLevel?pe(t):t.map(([n,i])=>`${n}=${i}`).join(";")}function Re(r){for(let e of r){if(!e.name)throw new TypeError("SchemaEditor: field `name` is required");if(!e.type)throw new TypeError("SchemaEditor: field `type` is required");let{baseType:t}=Y(e.type),n=t.toUpperCase();if(!L.includes(n))throw new TypeError(`SchemaEditor: unsupported field type "${e.type}" (base: "${t}"). Supported: ${L.join(", ")}`)}}var I=class{constructor(e){this._client=e}async createTable(e,t={}){var i;if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!((i=e.fields)!=null&&i.length))throw new TypeError("SchemaEditor: `fields` must be a non-empty array");Re(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables`;return l(this._client._ctx,n,c({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json"},t.signal?{signal:t.signal}:{}))}async addFields(e,t={}){var i;if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!((i=e.fields)!=null&&i.length))throw new TypeError("SchemaEditor: `fields` must be a non-empty array");Re(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables/${p(e.tableName)}`;return l(this._client._ctx,n,c({method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({fields:e.fields}),accept:"json"},t.signal?{signal:t.signal}:{}))}async deleteTable(e,t){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(t.confirm!==!0)throw new TypeError(`SchemaEditor: deleteTable("${e}") requires { confirm: true } \u2014 this operation permanently destroys the table and all its records.`);let n=`${this._client.baseUrl}/FileMaker_Tables/${p(e)}`;await l(this._client._ctx,n,c({method:"DELETE",accept:"json"},t.signal?{signal:t.signal}:{}))}async deleteField(e,t,n){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");if(n.confirm!==!0)throw new TypeError(`SchemaEditor: deleteField("${e}", "${t}") requires { confirm: true } \u2014 this operation permanently destroys the field and all its data.`);let i=`${this._client.baseUrl}/FileMaker_Tables/${p(e)}/${p(t)}`;await l(this._client._ctx,i,c({method:"DELETE",accept:"json"},n.signal?{signal:n.signal}:{}))}async createIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${p(e)}`;return l(this._client._ctx,i,c({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({indexName:t}),accept:"json"},n.signal?{signal:n.signal}:{}))}async deleteIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${p(e)}/${p(t)}`;await l(this._client._ctx,i,c({method:"DELETE",accept:"json"},n.signal?{signal:n.signal}:{}))}};function ot(r){let e={webhook:r.webhook,tableName:r.tableName};return r.endpointHeaders&&(e.endpointHeaders=r.endpointHeaders),r.headers&&!r.endpointHeaders&&(e.endpointHeaders=r.headers),r.queryHeaders&&(e.queryHeaders=r.queryHeaders),r.notifySchemaChanges!==void 0&&(e.notifySchemaChanges=r.notifySchemaChanges),r.select&&(e.select=r.select),r.filter&&(e.filter=r.filter),r.maxFailedAttempts!==void 0&&(e.maxFailedAttempts=r.maxFailedAttempts),e}function st(r){var i,o;if(!r||typeof r!="object")return;let e=r,t=e.webhookResult,n=(o=(i=t==null?void 0:t.webhookID)!=null?i:e.webhookID)!=null?o:e.id;return n!==void 0?String(n):void 0}var j=class{constructor(e){this._client=e}_url(e,t){let n=`${this._client.baseUrl}/Webhook.${e}`;return t!==void 0?`${n}(${p(String(t))})`:n}async create(e,t={}){if(!e.webhook)throw new TypeError("WebhookManager: `webhook` URL is required");if(!e.tableName)throw new TypeError("WebhookManager: `tableName` is required");let n=JSON.stringify(ot(e)),i=await l(this._client._ctx,this._url("Add"),c({method:"POST",headers:{"Content-Type":"application/json"},body:n,accept:"json"},t.signal?{signal:t.signal}:{})),o=st(i);if(o===void 0)throw new Error("WebhookManager: Webhook.Add did not return a webhook id");return{id:o}}async remove(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return l(this._client._ctx,this._url("Delete",e),c({method:"POST",accept:"json"},t.signal?{signal:t.signal}:{}))}async delete(e,t={}){return this.remove(e,t)}async get(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return l(this._client._ctx,this._url("Get",e),c({method:"GET",accept:"json"},t.signal?{signal:t.signal}:{}))}async getAll(e={}){return l(this._client._ctx,this._url("GetAll"),c({method:"GET",accept:"json"},e.signal?{signal:e.signal}:{}))}async invoke(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");let a=t,{rowIDs:n,signal:i}=a,o=oe(a,["rowIDs","signal"]),s=JSON.stringify({rowIDs:n?[...n]:[]});return l(this._client._ctx,this._url("Invoke",e),c(c({method:"POST",headers:{"Content-Type":"application/json"},body:s,accept:"json"},i?{signal:i}:{}),o))}};var W=class{constructor(e){var t;if(!e.host)throw new TypeError("FMSOData: `host` is required");if(!e.database)throw new TypeError("FMSOData: `database` is required");if(e.token===void 0||e.token===null)throw new TypeError("FMSOData: `token` is required");this.host=e.host.replace(/\/+$/,""),this.database=e.database,this.baseUrl=`${this.host}/fmi/odata/v4/${encodeURIComponent(this.database)}`,this.timeoutMs=e.timeoutMs,this._ctx=c({token:e.token,fetch:(t=e.fetch)!=null?t:globalThis.fetch.bind(globalThis),timeoutMs:e.timeoutMs},e.onUnauthorized?{onUnauthorized:e.onUnauthorized}:{})}from(e){if(!e)throw new TypeError("FMSOData#from: entitySet is required");return new A(this.baseUrl,e,this)}async request(e,t={}){return l(this._ctx,this._resolveUrl(e),t)}async rawRequest(e,t={}){return b(this._ctx,this._resolveUrl(e),t)}async script(e,t={}){return xe(this,e,t)}async scriptById(e,t={}){return we(this,e,t)}async metadata(e={}){return this._metadataFetcher||(this._metadataFetcher=new M(this._ctx,this.baseUrl)),this._metadataFetcher.fetch(e)}async metadataXml(e={}){return this._metadataFetcher||(this._metadataFetcher=new M(this._ctx,this.baseUrl)),this._metadataFetcher.fetchXml(e)}async version(){if(this._detectedVersion!==void 0)return this._detectedVersion;try{let e=await this.serverVersion();if(!e)return this._detectedVersion=null,null;let t=String(e.major);return this._detectedVersion=t in _?t:"future",this._detectedVersion}catch(e){return this._detectedVersion=null,null}}async serverVersion(){var e;if(this._detectedServerVersion!==void 0)return this._detectedServerVersion;try{let t=await this.metadata();return this._detectedServerVersion=(e=t.serverVersion)!=null?e:null,this._detectedServerVersion}catch(t){return this._detectedServerVersion=null,null}}async versionInfo(){let e=await this.version();return e?_[e]:null}async hasFeature(e){let t=await this.version();return t?Q(t,e):!1}schema(){return this._schemaEditor||(this._schemaEditor=new I(this)),this._schemaEditor}async createTable(e,t={}){return this.schema().createTable(e,t)}async addFields(e,t={}){return this.schema().addFields(e,t)}async deleteTable(e,t){return this.schema().deleteTable(e,t)}async deleteField(e,t,n){return this.schema().deleteField(e,t,n)}async createIndex(e,t,n={}){return this.schema().createIndex(e,t,n)}async deleteIndex(e,t,n={}){return this.schema().deleteIndex(e,t,n)}webhooks(){return this._webhookManager||(this._webhookManager=new j(this)),this._webhookManager}async createWebhook(e,t={}){return this.webhooks().create(e,t)}async removeWebhook(e,t={}){return this.webhooks().remove(e,t)}async getWebhook(e,t={}){return this.webhooks().get(e,t)}async getAllWebhooks(e={}){return this.webhooks().getAll(e)}async invokeWebhook(e,t={}){return this.webhooks().invoke(e,t)}batch(){return new P(this)}_resolveUrl(e){return/^https?:\/\//i.test(e)?e:e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}};return Ce(at);})();
6
+ `),o=i>=0?n.slice(0,i):n,s=i>=0?n.slice(i+4).trim():"",c=o.match(/^HTTP\/1\.\d (\d+)/),a=c?parseInt(c[1],10):0,d;if(s&&o.toLowerCase().includes("application/json"))try{d=JSON.parse(s)}catch(h){d=s}else s&&(d=s);return{status:a,body:d,headers:new Headers,ok:a>=200&&a<300}}_parseChangesetResponse(e,t){let n=e.match(/boundary=([^\s]+)/),i=n==null?void 0:n[1];if(!i)return[this._parseHttpPart(e)];let o=e.split(`--${i}`),s=[];for(let c=1;c<o.length-1;c++){let a=o[c].trim();!a||a==="--"||s.push(this._parseHttpPart(a))}return s}_resolveHandle(e,t){}};var me={20:"Claris FileMaker 2023",21:"Claris FileMaker 2024",22:"Claris FileMaker 2025",26:"Claris FileMaker 2026",future:"Future / next"},ge="4.01";var O={20:{major:"20",name:"Claris FileMaker 2023",releaseYear:2023,internalVersion:"20.x",status:"supported",odataProtocolVersion:"4.0",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!1,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!1,parameterizedFilters:!1,simplifiedQuerySyntax:!1,nestedQueries:!1,batchPreferenceInheritance:!1,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!1,aiAnnotation:!1,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!1},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},21:{major:"21",name:"Claris FileMaker 2024",releaseYear:2024,internalVersion:"21.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!1,webhookQueryHeaders:!1,applyAggregation:!1,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!1,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!1,$search:!1,$compute:!1}},22:{major:"22",name:"Claris FileMaker 2025",releaseYear:2025,internalVersion:"22.x",status:"supported",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!1,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!1,fmComment:!0,aiAnnotation:!0,computedAnnotation:!1,serverVersionAnnotation:!1,enrichedFMComment:!1,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},26:{major:"26",name:"Claris FileMaker 2026",releaseYear:2026,internalVersion:"26.x",status:"current",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}},future:{major:"future",name:"Future / next",releaseYear:null,internalVersion:"unknown",status:"future",odataProtocolVersion:"4.01",features:{serviceDocument:!0,metadata:!0,databaseListing:!0,tableListing:!0,recordCRUD:!0,recordReferences:!0,crossJoin:!0,batch:!0,scripts:!0,scriptsByFMSID:!0,scriptListing:!0,containerBinaryUpload:!0,containerBase64Upload:!0,containerDownload:!0,schemaModification:!0,webhooks:!0,webhookQueryHeaders:!0,applyAggregation:!0,typeCasting:!0,parameterizedFilters:!0,simplifiedQuerySyntax:!0,nestedQueries:!0,batchPreferenceInheritance:!0,metadataFiltering:!0,immutableIdUrls:!0,fmComment:!0,aiAnnotation:!0,computedAnnotation:!0,serverVersionAnnotation:!0,enrichedFMComment:!0,authBasic:!0,authOAuth:!0},queryOptions:{$filter:!0,$select:!0,$orderby:!0,$top:!0,$skip:!0,$expand:!0,$count:!0,$apply:!0,$search:!1,$compute:!1}}};function Q(r,e){var t,n;return(n=(t=O[r])==null?void 0:t.features[e])!=null?n:!1}function ye(r,e){var t,n;return(n=(t=O[r])==null?void 0:t.queryOptions[e])!=null?n:!1}function be(r){let e=["20","21","22","26"];for(let t of e)if(O[t].features[r])return t;return null}function k(r){let e=r.trim().match(/(\d+)\.(\d+)\.(\d+)/);return e?{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10),raw:r.trim()}:null}function z(r){if(!r||typeof r!="string")return null;let e=r.match(/Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["'][^>]*String\s*=\s*["']([^"']+)["']/);if(e){let s=k(e[1]);if(s)return s}let t=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']Org\.OData\.Core\.V1\.ProductVersion["']/);if(t){let s=k(t[1]);if(s)return s}let n=r.match(/Term\s*=\s*["']ServerVersion["'][^>]*String\s*=\s*["']([^"']+)["']/i);if(n){let s=k(n[1]);if(s&&s.major>=17)return s}let i=r.match(/String\s*=\s*["']([^"']+)["'][^>]*Term\s*=\s*["']ServerVersion["']/i);if(i){let s=k(i[1]);if(s&&s.major>=17)return s}let o=r.match(/Term\s*=\s*["'][^"']*Version[^"']*["'][^>]*String\s*=\s*["'][^"']*?(\d{2,}\.\d+\.\d+(?:\.\d+)?)[^"']*?["']/i);if(o){let s=k(o[1]);if(s&&s.major>=17)return s}return null}var L=["NUMERIC","DECIMAL","INT","DATE","TIME","TIMESTAMP","VARCHAR","CHARACTER VARYING","BLOB","VARBINARY","LONGVARBINARY","BINARY VARYING"],Se=["USER","USERNAME","CURRENT_USER","CURRENT_DATE","CURDATE","CURRENT_TIME","CURTIME","CURRENT_TIMESTAMP","CURTIMESTAMP"];function Y(r){let e=r.match(/\((\d+)\)/),t=r.match(/\[(\d+)\]/);return{baseType:r.replace(/\(.*?\)/,"").replace(/\[.*?\]/,"").trim(),length:e?parseInt(e[1],10):void 0,repetitions:t?parseInt(t[1],10):void 0}}function Be(r,e){return r===void 0?e:r==="true"}function Z(r,e){let t=new RegExp(`${e}="([^"]*)"`,"i"),n=r.match(t);return n==null?void 0:n[1]}function q(r){let e={},t=/(\w+)="([^"]*)"/g,n;for(;(n=t.exec(r))!==null;)e[n[1]]=n[2];return e}function T(r,e){let t=[],n=new RegExp(`<([\\w]+:)?${e}\\b[^>]*>`,"gi"),i;for(;(i=n.exec(r))!==null;){let o=i[0];if(/\/>\s*$/.test(o)){t.push(o);continue}let s=i.index,c=new RegExp(`</([\\w]+:)?${e}>`,"gi");c.lastIndex=n.lastIndex;let a=c.exec(r);a&&t.push(r.slice(s,a.index+a[0].length))}return t}function N(r,e){let n=new RegExp(`<(?:[\\w]+:)?${e}\\b[^>]*>`,"i").exec(r);if(!n)return;let i=n.index+n[0].length,o=new RegExp(`</(?:[\\w]+:)?${e}>`,"i");o.lastIndex=i;let s=o.exec(r);if(s)return r.slice(i,s.index)}function Le(r){var i,o;let e=q(r),t=Be(e.Nullable,!0),n={name:(i=e.Name)!=null?i:"",type:(o=e.Type)!=null?o:"",nullable:t};if(e.MaxLength!==void 0){let s=parseInt(e.MaxLength,10);Number.isNaN(s)||(n.maxLength=s)}return n}function Ne(r){var o,s;let e=q(r),t=(o=e.Type)!=null?o:"",n=t.startsWith("Collection("),i=n?t.slice(11,-1):t;return{name:(s=e.Name)!=null?s:"",target:i,collection:n}}function qe(r){let e=[],t=T(r,"PropertyRef");for(let n of t){let i=Z(n,"Name");i&&e.push(i)}return e}function He(r){var c,a;let e=(c=Z(r,"Name"))!=null?c:"",t=[],n=[],i=[],o=(a=N(r,"EntityType"))!=null?a:r,s=T(o,"Key")[0];s&&t.push(...qe(s));for(let d of T(o,"Property"))n.push(Le(d));for(let d of T(o,"NavigationProperty"))i.push(Ne(d));return{name:e,keys:t,properties:n,navigationProperties:i}}function We(r){var t,n;let e=q(r);return{name:(t=e.Name)!=null?t:"",entityType:(n=e.EntityType)!=null?n:""}}function Je(r){var e;return(e=z(r))!=null?e:void 0}function Ge(r){var s,c,a,d;let e=(s=Z(r,"Name"))!=null?s:"",t=q(r),n=t.IsBound==="true"?t.EntityType:void 0,i=[],o=(c=N(r,"Action"))!=null?c:r;for(let h of T(o,"Parameter")){let m=q(h);i.push({name:(a=m.Name)!=null?a:"",type:(d=m.Type)!=null?d:""})}return n!==void 0?{name:e,boundTo:n,parameters:i}:{name:e,parameters:i}}function Qe(r){var e,t,n;try{let i=N(r,"DataServices");if(!i)throw new Error("Missing <edmx:DataServices> in metadata");let o=T(i,"Schema")[0];if(!o)throw new Error("Missing <Schema> in metadata");let s=(e=Z(o,"Namespace"))!=null?e:"",c=(t=N(o,"Schema"))!=null?t:o,a=[];for(let y of T(c,"EntityType"))a.push(He(y));let d=[],h=T(c,"EntityContainer")[0];if(h){let y=(n=N(h,"EntityContainer"))!=null?n:h;for(let w of T(y,"EntitySet"))d.push(We(w))}let m=[];for(let y of T(c,"Action"))m.push(Ge(y));let S=Je(r),g={namespace:s,entityTypes:a,entitySets:d,actions:m,raw:r};return S&&(g.serverVersion=S,g.productVersion=S.raw),g}catch(i){let o=i instanceof Error?i.message:String(i);throw new x(`Failed to parse $metadata: ${o}`,{status:0,odataError:r.slice(0,500)})}}async function ze(r,e,t={}){return(await b(r,`${e}/$metadata`,u({method:"GET",accept:"xml"},t.signal?{signal:t.signal}:{}))).text()}var M=class{constructor(e,t){this._ctx=e;this._baseUrl=t}async fetchXml(e={}){return ze(this._ctx,this._baseUrl,e)}async fetch(e={}){if(!e.refresh&&this._cache)return this._cache;let t=this.fetchXml(e).then(Qe);return this._cache=t,t}};var H=["image/png","image/jpeg","image/gif","image/tiff","application/pdf"];function Ye(r){var e;return((e=r.split(";")[0])!=null?e:"").trim().toLowerCase()}function Ze(r){let e=Ye(r);return H.includes(e)}function ee(r){if(r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71&&r[4]===13&&r[5]===10&&r[6]===26&&r[7]===10)return"image/png";if(r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(r.length>=4&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56)return"image/gif";if(r.length>=4&&(r[0]===73&&r[1]===73&&r[2]===42&&r[3]===0||r[0]===77&&r[1]===77&&r[2]===0&&r[3]===42))return"image/tiff";if(r.length>=4&&r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70)return"application/pdf"}var C=class{constructor(e,t){if(!t)throw new TypeError("ContainerRef: fieldName is required");this._entity=e,this.fieldName=t}url(){return`${this._entity.toURL()}/${p(this.fieldName)}`}_valueUrl(){return`${this.url()}/$value`}async get(e={}){var a;let t=await b(this._entity._client._ctx,this._valueUrl(),u({method:"GET",accept:"none"},e.signal?{signal:e.signal}:{})),n=(a=t.headers.get("content-type"))!=null?a:"",i=t.headers.get("content-disposition"),o=i?Xe(i):void 0,s=await t.blob(),c={blob:s,contentType:n,size:s.size};return o!==void 0&&(c.filename=o),c}async getStream(e={}){let t=await b(this._entity._client._ctx,this._valueUrl(),u({method:"GET",accept:"none"},e.signal?{signal:e.signal}:{}));if(!t.body)throw new TypeError("ContainerRef.getStream: response has no body");return t.body}async upload(e,t={}){var c;let n=(c=e.encoding)!=null?c:"binary",i=await et(e.data),o=e.contentType;if(!o){let a=ee(i);if(!a)throw new TypeError(`ContainerRef.upload: contentType is required and could not be sniffed from the payload. Pass a contentType explicitly (one of ${H.join(", ")}).`);o=a}if(n==="binary"){if(!Ze(o))throw new TypeError(`ContainerRef.upload (binary): contentType "${o}" is not a FileMaker-supported container type. Use one of ${H.join(", ")}, or switch to { encoding: 'base64' }.`);let a={"Content-Type":o};e.filename&&(a["Content-Disposition"]=Ke(e.filename));let d=new ArrayBuffer(i.byteLength);new Uint8Array(d).set(i),await b(this._entity._client._ctx,this.url(),u({method:"PATCH",headers:a,body:d,accept:"none"},t.signal?{signal:t.signal}:{}));return}let s=F({[this.fieldName]:u({data:te(i),contentType:o},e.filename?{filename:e.filename}:{})});await b(this._entity._client._ctx,this._entity.toURL(),u({method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(s),accept:"none"},t.signal?{signal:t.signal}:{}))}async delete(e={}){let t={[this.fieldName]:null};await b(this._entity._client._ctx,this._entity.toURL(),u({method:"PATCH",headers:{"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify(t),accept:"none"},e.signal?{signal:e.signal}:{}))}};function F(r,e={}){let t=u({},e);for(let[n,i]of Object.entries(r)){if(!i.contentType)throw new TypeError(`buildContainerJsonBody: "${n}".contentType is required`);t[n]=i.data,t[`${n}@com.filemaker.odata.ContentType`]=i.contentType,i.filename&&(t[`${n}@com.filemaker.odata.Filename`]=i.filename)}return t}function Xe(r){let e=r.match(/filename\*\s*=\s*([^']+)'[^']*'([^;]+)/i);if(e){let n=e[1].trim().toLowerCase(),i=e[2].trim();try{let o=decodeURIComponent(i);return o}catch(o){}}let t=r.match(/filename\s*=\s*("([^"\\]*(?:\\.[^"\\]*)*)"|([^;]+))/i);if(t){let n=t[2];if(n!==void 0)return n.replace(/\\(.)/g,"$1").trim();let i=t[3];if(i!==void 0)return i.trim()}}function Ke(r){let e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,t=/[^\x00-\x7F]/.test(r),n;return e.test(r)?n=`inline; filename=${r}`:n=`inline; filename="${r.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,'\\"')}"`,t?`${n}; filename*=UTF-8''${encodeURIComponent(r)}`:n}async function et(r){if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);let e=await r.arrayBuffer();return new Uint8Array(e)}function te(r){if(typeof Buffer!="undefined")return Buffer.from(r).toString("base64");let e="",t=32768;for(let n=0;n<r.length;n+=t)e+=String.fromCharCode.apply(null,Array.from(r.subarray(n,n+t)));return btoa(e)}function tt(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("ScriptInvoker: key must be a finite number");return String(r)}if(typeof r=="string")return`'${R(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("ScriptInvoker: unsupported key type")}var _=class{constructor(e,t={}){this._client=e,t.entitySet!==void 0&&(this.entitySet=t.entitySet),t.key!==void 0&&(this.key=t.key)}url(e){if(!e)throw new TypeError("ScriptInvoker: script name is required");return this._urlForSegment(`Script.${p(e)}`)}urlById(e){if(!Number.isFinite(e))throw new TypeError("ScriptInvoker: fmsid must be a finite number");return this._urlForSegment(`Script.FMSID:${e}`)}_urlForSegment(e){let t=this._client.baseUrl;if(this.entitySet===void 0)return`${t}/${e}`;let n=p(this.entitySet);return this.key===void 0?`${t}/${n}/${e}`:`${t}/${n}(${tt(this.key)})/${e}`}async run(e,t={}){return this._runAtUrl(this.url(e),t)}async runById(e,t={}){return this._runAtUrl(this.urlById(e),t)}async _runAtUrl(e,t){let n={},i;t.parameter!==void 0&&(n["Content-Type"]="application/json",i=JSON.stringify({scriptParameterValue:t.parameter}));let o="POST",s=await l(this._client._ctx,e,u(V(u({method:o,headers:n},i!==void 0?{body:i}:{}),{accept:"json"}),t.signal?{signal:t.signal}:{}));return rt(s,{url:e,method:o})}};function rt(r,e){let t=nt(r),n=t.scriptResult,i,o,s;if(n!==null&&typeof n=="object"&&("code"in n||"resultParameter"in n)){let a=n;o=a.code!==void 0?String(a.code):"0",i=a.resultParameter!==void 0?typeof a.resultParameter=="string"?a.resultParameter:JSON.stringify(a.resultParameter):void 0,typeof a.message=="string"&&(s=a.message)}else o=t.scriptError!==void 0?String(t.scriptError):"0",i=n!==void 0?typeof n=="string"?n:JSON.stringify(n):void 0;if(o!=="0")throw new $(s?`FileMaker script error ${o}: ${s}`:`FileMaker script error ${o}`,V(u({status:200,scriptError:o},i!==void 0?{scriptResult:i}:{}),{odataError:r,request:e}));let c={scriptError:o,raw:r};return i!==void 0&&(c.scriptResult=i),c}function nt(r){if(r===null||typeof r!="object")return{};let e=r;if("scriptError"in e||"scriptResult"in e)return e;for(let t of Object.values(e))if(t&&typeof t=="object"){let n=t;if("scriptError"in n||"scriptResult"in n)return n}return{}}function xe(r,e,t){return new _(r).run(e,t)}function we(r,e,t){return new _(r).runById(e,t)}function Ee(r,e,t,n){return new _(r,{entitySet:e}).run(t,n)}function Te(r,e,t,n,i){return new _(r,{entitySet:e,key:t}).run(n,i)}function it(r){if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError("EntityRef: key must be a finite number");return String(r)}if(typeof r=="string")return`'${R(r)}'`;if(typeof r=="boolean")return r?"true":"false";throw new TypeError("EntityRef: unsupported key type")}var v=class{constructor(e,t,n){this._client=e,this.entitySet=t,this.key=n}toURL(){return`${this._client.baseUrl}/${p(this.entitySet)}(${it(this.key)})`}async get(e={}){return await l(this._client._ctx,this.toURL(),u({method:"GET",accept:"json"},e.signal?{signal:e.signal}:{}))}async fieldValue(e,t={}){let n=`${this.toURL()}/${p(e)}`;return(await l(this._client._ctx,n,u({method:"GET",accept:"json"},t.signal?{signal:t.signal}:{}))).value}async patch(e,t={}){let n={"Content-Type":"application/json",Prefer:t.returnRepresentation?"return=representation":"return=minimal"};return t.ifMatch&&(n["If-Match"]=t.ifMatch),await l(this._client._ctx,this.toURL(),u({method:"PATCH",headers:n,body:JSON.stringify(e),accept:"json"},t.signal?{signal:t.signal}:{}))}async delete(e={}){let t={};e.ifMatch&&(t["If-Match"]=e.ifMatch),await b(this._client._ctx,this.toURL(),u({method:"DELETE",headers:t,accept:"none"},e.signal?{signal:e.signal}:{}))}async script(e,t={}){return Te(this._client,this.entitySet,this.key,e,t)}container(e){return new C(this,e)}async patchContainers(e,t={},n={}){let i={"Content-Type":"application/json",Prefer:n.returnRepresentation?"return=representation":"return=minimal"};n.ifMatch&&(i["If-Match"]=n.ifMatch);let o=F(e,t);await b(this._client._ctx,this.toURL(),u({method:"PATCH",headers:i,body:JSON.stringify(o),accept:"none"},n.signal?{signal:n.signal}:{}))}async getRefs(e,t={}){let n=`${this.toURL()}/${p(e)}/$ref`,i=await l(this._client._ctx,n,u({method:"GET",accept:"json"},t.signal?{signal:t.signal}:{}));return i!=null&&i.value?i.value:i!=null&&i["@odata.id"]?[i]:[]}async addRef(e,t,n={}){let i=`${this.toURL()}/${p(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await b(this._client._ctx,i,u({method:"POST",headers:o,body:s,accept:"none"},n.signal?{signal:n.signal}:{}))}async setRef(e,t,n={}){let i=`${this.toURL()}/${p(e)}/$ref`,o={"Content-Type":"application/json"};n.ifMatch&&(o["If-Match"]=n.ifMatch);let s=JSON.stringify({"@odata.id":this._refId(e,t)});await b(this._client._ctx,i,u({method:"PATCH",headers:o,body:s,accept:"none"},n.signal?{signal:n.signal}:{}))}async removeRef(e,t,n={}){let i=`${this.toURL()}/${p(e)}/$ref`,o={};n.ifMatch&&(o["If-Match"]=n.ifMatch),t!==void 0&&(i+=`('${R(this._refId(e,t))}')`),await b(this._client._ctx,i,u({method:"DELETE",headers:o,accept:"none"},n.signal?{signal:n.signal}:{}))}_refId(e,t){let n=e;return typeof t=="number"?`${n}(${t})`:`${n}('${R(t)}')`}};var f=class r{constructor(e){this.expr=e}toString(){return this.expr}and(e){return new r(`(${this.expr}) and (${r.coerce(e)})`)}or(e){return new r(`(${this.expr}) or (${r.coerce(e)})`)}not(){return new r(`not (${this.expr})`)}static coerce(e){return e instanceof r?e.expr:e}},re={eq:(r,e)=>new f(`${r} eq ${E(e)}`),ne:(r,e)=>new f(`${r} ne ${E(e)}`),gt:(r,e)=>new f(`${r} gt ${E(e)}`),ge:(r,e)=>new f(`${r} ge ${E(e)}`),lt:(r,e)=>new f(`${r} lt ${E(e)}`),le:(r,e)=>new f(`${r} le ${E(e)}`),startswith:(r,e)=>new f(`startswith(${r},${E(e)})`),endswith:(r,e)=>new f(`endswith(${r},${E(e)})`),contains:(r,e)=>new f(`contains(${r},${E(e)})`),and:(r,e)=>new f(`(${f.coerce(r)}) and (${f.coerce(e)})`),or:(r,e)=>new f(`(${f.coerce(r)}) or (${f.coerce(e)})`),not:r=>new f(`not (${f.coerce(r)})`),raw:r=>new f(r)};function Oe(r){return typeof r=="function"?f.coerce(r(re)):f.coerce(r)}var A=class r{constructor(e,t,n){this._state={};this._baseUrl=e,this._entitySet=t,n&&(this._client=n)}select(...e){var t;return this._state.select=[...(t=this._state.select)!=null?t:[],...e],this}filter(e){let t=Oe(e);return this._state.filter=this._state.filter?`(${this._state.filter}) and (${t})`:t,this}or(e){let t=Oe(e);return this._state.filter=this._state.filter?`(${this._state.filter}) or (${t})`:t,this}expand(e,t){var i;let n={name:e};if(t){let o=new r("",e);t(o),n.options=o._state}return this._state.expand=[...(i=this._state.expand)!=null?i:[],n],this}orderby(e,t="asc"){var n;return this._state.orderby=[...(n=this._state.orderby)!=null?n:[],{field:e,dir:t}],this}top(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#top: expected non-negative integer, got ${e}`);return this._state.top=e,this}skip(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Query#skip: expected non-negative integer, got ${e}`);return this._state.skip=e,this}count(e=!0){return this._state.count=e,this}search(e){return this._state.search=e,this}apply(e){return this._state.apply=e,this}aggregate(e){let t=e.map(n=>`${n.field} with ${n.function} as ${n.alias}`);return this._state.apply=`aggregate(${t.join(",")})`,this}groupBy(e,t){let n=e.join(",");if(t&&t.length>0){let i=t.map(o=>`${o.field} with ${o.function} as ${o.alias}`);this._state.apply=`groupby((${n}),aggregate(${i.join(",")}))`}else this._state.apply=`groupby((${n}))`;return this}toURL(){let e=_e(this._state,{topLevel:!0}),t=`${this._baseUrl}/${p(this._entitySet)}`;return e?`${t}?${e}`:t}byKey(e){if(!this._client)throw new Error("Query#byKey: no client attached (use FMSOData#from)");return new v(this._client,this._entitySet,e)}async create(e,t={}){if(!this._client)throw new Error("Query#create: no client attached (use FMSOData#from)");let n=`${this._baseUrl}/${p(this._entitySet)}`;return await l(this._client._ctx,n,u({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json"},t.signal?{signal:t.signal}:{}))}async createWithContainers(e,t,n={}){if(!this._client)throw new Error("Query#createWithContainers: no client attached (use FMSOData#from)");let i=`${this._baseUrl}/${p(this._entitySet)}`,o=F(t,e);return await l(this._client._ctx,i,u({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),accept:"json"},n.signal?{signal:n.signal}:{}))}async get(e={}){var i;if(!this._client)throw new Error("Query#get: no client attached (use FMSOData#from)");let t=await l(this._client._ctx,this.toURL(),u({method:"GET",accept:"json"},e.signal?{signal:e.signal}:{})),n={value:(i=t==null?void 0:t.value)!=null?i:[]};return t&&typeof t["@odata.count"]=="number"&&(n.count=t["@odata.count"]),t&&typeof t["@odata.nextLink"]=="string"&&(n.nextLink=t["@odata.nextLink"]),n}async script(e,t={}){if(!this._client)throw new Error("Query#script: no client attached (use FMSOData#from)");return Ee(this._client,this._entitySet,e,t)}};function _e(r,e){let t=[];if(r.select&&r.select.length>0&&t.push(["$select",r.select.join(",")]),r.filter&&t.push(["$filter",r.filter]),r.expand&&r.expand.length>0){let n=r.expand.map(i=>{if(!i.options)return i.name;let o=_e(i.options,{topLevel:!1});return o?`${i.name}(${o})`:i.name});t.push(["$expand",n.join(",")])}return r.orderby&&r.orderby.length>0&&t.push(["$orderby",r.orderby.map(n=>`${n.field} ${n.dir}`).join(",")]),r.top!==void 0&&t.push(["$top",String(r.top)]),r.skip!==void 0&&t.push(["$skip",String(r.skip)]),r.count&&t.push(["$count","true"]),r.search&&t.push(["$search",r.search]),r.apply&&t.push(["$apply",r.apply]),e.topLevel?pe(t):t.map(([n,i])=>`${n}=${i}`).join(";")}function $e(r){for(let e of r){if(!e.name)throw new TypeError("SchemaEditor: field `name` is required");if(!e.type)throw new TypeError("SchemaEditor: field `type` is required");let{baseType:t}=Y(e.type),n=t.toUpperCase();if(!L.includes(n))throw new TypeError(`SchemaEditor: unsupported field type "${e.type}" (base: "${t}"). Supported: ${L.join(", ")}`)}}var I=class{constructor(e){this._client=e}async createTable(e,t={}){var i;if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!((i=e.fields)!=null&&i.length))throw new TypeError("SchemaEditor: `fields` must be a non-empty array");$e(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables`;return l(this._client._ctx,n,u({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),accept:"json"},t.signal?{signal:t.signal}:{}))}async addFields(e,t={}){var i;if(!e.tableName)throw new TypeError("SchemaEditor: `tableName` is required");if(!((i=e.fields)!=null&&i.length))throw new TypeError("SchemaEditor: `fields` must be a non-empty array");$e(e.fields);let n=`${this._client.baseUrl}/FileMaker_Tables/${p(e.tableName)}`;return l(this._client._ctx,n,u({method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({fields:e.fields}),accept:"json"},t.signal?{signal:t.signal}:{}))}async deleteTable(e,t){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(t.confirm!==!0)throw new TypeError(`SchemaEditor: deleteTable("${e}") requires { confirm: true } \u2014 this operation permanently destroys the table and all its records.`);let n=`${this._client.baseUrl}/FileMaker_Tables/${p(e)}`;await l(this._client._ctx,n,u({method:"DELETE",accept:"json"},t.signal?{signal:t.signal}:{}))}async deleteField(e,t,n){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");if(n.confirm!==!0)throw new TypeError(`SchemaEditor: deleteField("${e}", "${t}") requires { confirm: true } \u2014 this operation permanently destroys the field and all its data.`);let i=`${this._client.baseUrl}/FileMaker_Tables/${p(e)}/${p(t)}`;await l(this._client._ctx,i,u({method:"DELETE",accept:"json"},n.signal?{signal:n.signal}:{}))}async createIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${p(e)}`;return l(this._client._ctx,i,u({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({indexName:t}),accept:"json"},n.signal?{signal:n.signal}:{}))}async deleteIndex(e,t,n={}){if(!e)throw new TypeError("SchemaEditor: `tableName` is required");if(!t)throw new TypeError("SchemaEditor: `fieldName` is required");let i=`${this._client.baseUrl}/FileMaker_Indexes/${p(e)}/${p(t)}`;await l(this._client._ctx,i,u({method:"DELETE",accept:"json"},n.signal?{signal:n.signal}:{}))}};function ot(r){let e={webhook:r.webhook,tableName:r.tableName};return r.endpointHeaders&&(e.endpointHeaders=r.endpointHeaders),r.headers&&!r.endpointHeaders&&(e.endpointHeaders=r.headers),r.queryHeaders&&(e.queryHeaders=r.queryHeaders),r.notifySchemaChanges!==void 0&&(e.notifySchemaChanges=r.notifySchemaChanges),r.select&&(e.select=r.select),r.filter&&(e.filter=r.filter),r.maxFailedAttempts!==void 0&&(e.maxFailedAttempts=r.maxFailedAttempts),e}function st(r){var i,o;if(!r||typeof r!="object")return;let e=r,t=e.webhookResult,n=(o=(i=t==null?void 0:t.webhookID)!=null?i:e.webhookID)!=null?o:e.id;return n!==void 0?String(n):void 0}var j=class{constructor(e){this._client=e}_url(e,t){let n=`${this._client.baseUrl}/Webhook.${e}`;return t!==void 0?`${n}(${p(String(t))})`:n}async create(e,t={}){if(!e.webhook)throw new TypeError("WebhookManager: `webhook` URL is required");if(!e.tableName)throw new TypeError("WebhookManager: `tableName` is required");let n=JSON.stringify(ot(e)),i=await l(this._client._ctx,this._url("Add"),u({method:"POST",headers:{"Content-Type":"application/json"},body:n,accept:"json"},t.signal?{signal:t.signal}:{})),o=st(i);if(o===void 0)throw new Error("WebhookManager: Webhook.Add did not return a webhook id");return{id:o}}async remove(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return l(this._client._ctx,this._url("Delete",e),u({method:"POST",accept:"json"},t.signal?{signal:t.signal}:{}))}async delete(e,t={}){return this.remove(e,t)}async get(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");return l(this._client._ctx,this._url("Get",e),u({method:"GET",accept:"json"},t.signal?{signal:t.signal}:{}))}async getAll(e={}){return l(this._client._ctx,this._url("GetAll"),u({method:"GET",accept:"json"},e.signal?{signal:e.signal}:{}))}async invoke(e,t={}){if(e===""||e===void 0)throw new TypeError("WebhookManager: webhook `id` is required");let c=t,{rowIDs:n,signal:i}=c,o=oe(c,["rowIDs","signal"]),s=JSON.stringify({rowIDs:n?[...n]:[]});return l(this._client._ctx,this._url("Invoke",e),u(u({method:"POST",headers:{"Content-Type":"application/json"},body:s,accept:"json"},i?{signal:i}:{}),o))}};var W=class{constructor(e){var t;if(!e.host)throw new TypeError("FMSOData: `host` is required");if(!e.database)throw new TypeError("FMSOData: `database` is required");if(e.token===void 0||e.token===null)throw new TypeError("FMSOData: `token` is required");this.host=e.host.replace(/\/+$/,""),this.database=e.database,this.baseUrl=`${this.host}/fmi/odata/v4/${encodeURIComponent(this.database)}`,this.timeoutMs=e.timeoutMs,this._ctx=u({token:e.token,fetch:(t=e.fetch)!=null?t:globalThis.fetch.bind(globalThis),timeoutMs:e.timeoutMs},e.onUnauthorized?{onUnauthorized:e.onUnauthorized}:{})}from(e){if(!e)throw new TypeError("FMSOData#from: entitySet is required");return new A(this.baseUrl,e,this)}async request(e,t={}){return l(this._ctx,this._resolveUrl(e),t)}async rawRequest(e,t={}){return b(this._ctx,this._resolveUrl(e),t)}async script(e,t={}){return xe(this,e,t)}async scriptById(e,t={}){return we(this,e,t)}async metadata(e={}){return this._metadataFetcher||(this._metadataFetcher=new M(this._ctx,this.baseUrl)),this._metadataFetcher.fetch(e)}async metadataXml(e={}){return this._metadataFetcher||(this._metadataFetcher=new M(this._ctx,this.baseUrl)),this._metadataFetcher.fetchXml(e)}async version(){if(this._detectedVersion!==void 0)return this._detectedVersion;try{let e=await this.serverVersion();if(!e)return this._detectedVersion=null,null;let t=String(e.major);return this._detectedVersion=t in O?t:"future",this._detectedVersion}catch(e){return this._detectedVersion=null,null}}async serverVersion(){var e;if(this._detectedServerVersion!==void 0)return this._detectedServerVersion;try{let t=await this.metadata();return this._detectedServerVersion=(e=t.serverVersion)!=null?e:null,this._detectedServerVersion}catch(t){return this._detectedServerVersion=null,null}}async versionInfo(){let e=await this.version();return e?O[e]:null}async hasFeature(e){let t=await this.version();return t?Q(t,e):!1}schema(){return this._schemaEditor||(this._schemaEditor=new I(this)),this._schemaEditor}async createTable(e,t={}){return this.schema().createTable(e,t)}async addFields(e,t={}){return this.schema().addFields(e,t)}async deleteTable(e,t){return this.schema().deleteTable(e,t)}async deleteField(e,t,n){return this.schema().deleteField(e,t,n)}async createIndex(e,t,n={}){return this.schema().createIndex(e,t,n)}async deleteIndex(e,t,n={}){return this.schema().deleteIndex(e,t,n)}webhooks(){return this._webhookManager||(this._webhookManager=new j(this)),this._webhookManager}async createWebhook(e,t={}){return this.webhooks().create(e,t)}async removeWebhook(e,t={}){return this.webhooks().remove(e,t)}async getWebhook(e,t={}){return this.webhooks().get(e,t)}async getAllWebhooks(e={}){return this.webhooks().getAll(e)}async invokeWebhook(e,t={}){return this.webhooks().invoke(e,t)}batch(){return new P(this)}_resolveUrl(e){return/^https?:\/\//i.test(e)?e:e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}};return Ce(at);})();
package/dist/scripts.d.ts CHANGED
@@ -15,9 +15,12 @@
15
15
  * POST /<db>/<EntitySet>/Script.FMSID:<id> // entity-set context
16
16
  * POST /<db>/<EntitySet>(<key>)/Script.FMSID:<id> // single-record context
17
17
  *
18
- * The optional parameter is sent as `{ "scriptParameterValue": "<string>" }`. The
19
- * response envelope is `{ "scriptResult": "...", "scriptError": "0" }`; a
20
- * non-zero `scriptError` becomes an `FMScriptError`.
18
+ * The optional parameter is sent as `{ "scriptParameterValue": ... }` (string,
19
+ * number or JSON object). The response envelope depends on the FMS version:
20
+ * older servers reply `{ "scriptResult": "...", "scriptError": "0" }`, while
21
+ * FMS v26+ nests the result as
22
+ * `{ "scriptResult": { "code": 0, "resultParameter": "...", "message": "..." } }`.
23
+ * A non-zero error code becomes an `FMScriptError`.
21
24
  *
22
25
  * @see https://github.com/fsans/fms-odata-spec/blob/main/docs/06-scripts.md
23
26
  */
@@ -36,10 +39,11 @@ export type ScriptIdentifier = {
36
39
  export interface ScriptOptions extends RequestOptions {
37
40
  /**
38
41
  * Optional script parameter. Serialized to the FMS `scriptParameterValue`
39
- * field in the request body. If omitted, the body is empty and the script
40
- * runs with no parameter (FileMaker's `Get(ScriptParameter)` returns empty).
42
+ * field in the request body. FMS accepts a string, a number or a JSON
43
+ * object. If omitted, the body is empty and the script runs with no
44
+ * parameter (FileMaker's `Get(ScriptParameter)` returns empty).
41
45
  */
42
- parameter?: string;
46
+ parameter?: string | number | object;
43
47
  }
44
48
  /**
45
49
  * Result envelope returned by a successful script invocation. A non-zero
@@ -1 +1 @@
1
- {"version":3,"file":"scripts.d.ts","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAG3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAChD,OAAO,EAGL,KAAK,YAAY,EAClB,MAAM,UAAU,CAAA;AAEjB,4DAA4D;AAC5D,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAA;AAEjC,+CAA+C;AAC/C,MAAM,WAAW,aAAc,SAAQ,cAAc;IACnD;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,8DAA8D;IAC9D,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,0EAA0E;IAC1E,WAAW,EAAE,MAAM,CAAA;IACnB,sEAAsE;IACtE,GAAG,EAAE,OAAO,CAAA;CACb;AAeD,0DAA0D;AAC1D,MAAM,WAAW,WAAW;IAC1B,sDAAsD;IACtD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,2EAA2E;IAC3E,GAAG,CAAC,EAAE,YAAY,CAAA;CACnB;AAED;;;;GAIG;AACH,qBAAa,aAAa;IACxB,gBAAgB,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAA;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAA;IACtC,QAAQ,CAAC,GAAG,EAAE,YAAY,GAAG,SAAS,CAAA;gBAE1B,MAAM,EAAE,QAAQ,EAAE,KAAK,GAAE,WAAgB;IAMrD,gEAAgE;IAChE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAKzB,kEAAkE;IAClE,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAK9B,wDAAwD;IACxD,OAAO,CAAC,cAAc;IAYtB,0EAA0E;IACpE,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,YAAY,CAAC;IAIxE;;;;;;;;;OASG;IACG,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,YAAY,CAAC;IAI7E,0DAA0D;YAC5C,SAAS;CAmBxB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,OAAO,EACZ,OAAO,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACvC,YAAY,CA2Cd;AAuBD,2EAA2E;AAC3E,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,QAAQ,EAChB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB;AAED,kEAAkE;AAClE,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,QAAQ,EAChB,KAAK,EAAE,MAAM,EACb,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB;AAED,gBAAgB;AAChB,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,QAAQ,EAChB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB;AAED,gBAAgB;AAChB,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,QAAQ,EAChB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,YAAY,EACjB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB"}
1
+ {"version":3,"file":"scripts.d.ts","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAG3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAChD,OAAO,EAGL,KAAK,YAAY,EAClB,MAAM,UAAU,CAAA;AAEjB,4DAA4D;AAC5D,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAA;AAEjC,+CAA+C;AAC/C,MAAM,WAAW,aAAc,SAAQ,cAAc;IACnD;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAA;CACrC;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,8DAA8D;IAC9D,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,0EAA0E;IAC1E,WAAW,EAAE,MAAM,CAAA;IACnB,sEAAsE;IACtE,GAAG,EAAE,OAAO,CAAA;CACb;AAeD,0DAA0D;AAC1D,MAAM,WAAW,WAAW;IAC1B,sDAAsD;IACtD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,2EAA2E;IAC3E,GAAG,CAAC,EAAE,YAAY,CAAA;CACnB;AAED;;;;GAIG;AACH,qBAAa,aAAa;IACxB,gBAAgB,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAA;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAA;IACtC,QAAQ,CAAC,GAAG,EAAE,YAAY,GAAG,SAAS,CAAA;gBAE1B,MAAM,EAAE,QAAQ,EAAE,KAAK,GAAE,WAAgB;IAMrD,gEAAgE;IAChE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAKzB,kEAAkE;IAClE,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAK9B,wDAAwD;IACxD,OAAO,CAAC,cAAc;IAYtB,0EAA0E;IACpE,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,YAAY,CAAC;IAIxE;;;;;;;;;OASG;IACG,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,YAAY,CAAC;IAI7E,0DAA0D;YAC5C,SAAS;CAmBxB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,OAAO,EACZ,OAAO,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACvC,YAAY,CAwDd;AAuBD,2EAA2E;AAC3E,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,QAAQ,EAChB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB;AAED,kEAAkE;AAClE,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,QAAQ,EAChB,KAAK,EAAE,MAAM,EACb,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB;AAED,gBAAgB;AAChB,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,QAAQ,EAChB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB;AAED,gBAAgB;AAChB,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,QAAQ,EAChB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,YAAY,EACjB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,aAAa,GACnB,OAAO,CAAC,YAAY,CAAC,CAEvB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fms-odata-js",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Zero-runtime-dependency TypeScript client for FileMaker Server OData v4 (Web Viewer, browser, Node).",
5
5
  "type": "module",
6
6
  "main": "./dist/fms-odata.esm.js",
package/src/scripts.ts CHANGED
@@ -15,9 +15,12 @@
15
15
  * POST /<db>/<EntitySet>/Script.FMSID:<id> // entity-set context
16
16
  * POST /<db>/<EntitySet>(<key>)/Script.FMSID:<id> // single-record context
17
17
  *
18
- * The optional parameter is sent as `{ "scriptParameterValue": "<string>" }`. The
19
- * response envelope is `{ "scriptResult": "...", "scriptError": "0" }`; a
20
- * non-zero `scriptError` becomes an `FMScriptError`.
18
+ * The optional parameter is sent as `{ "scriptParameterValue": ... }` (string,
19
+ * number or JSON object). The response envelope depends on the FMS version:
20
+ * older servers reply `{ "scriptResult": "...", "scriptError": "0" }`, while
21
+ * FMS v26+ nests the result as
22
+ * `{ "scriptResult": { "code": 0, "resultParameter": "...", "message": "..." } }`.
23
+ * A non-zero error code becomes an `FMScriptError`.
21
24
  *
22
25
  * @see https://github.com/fsans/fms-odata-spec/blob/main/docs/06-scripts.md
23
26
  */
@@ -41,10 +44,11 @@ export type ScriptIdentifier =
41
44
  export interface ScriptOptions extends RequestOptions {
42
45
  /**
43
46
  * Optional script parameter. Serialized to the FMS `scriptParameterValue`
44
- * field in the request body. If omitted, the body is empty and the script
45
- * runs with no parameter (FileMaker's `Get(ScriptParameter)` returns empty).
47
+ * field in the request body. FMS accepts a string, a number or a JSON
48
+ * object. If omitted, the body is empty and the script runs with no
49
+ * parameter (FileMaker's `Get(ScriptParameter)` returns empty).
46
50
  */
47
- parameter?: string
51
+ parameter?: string | number | object
48
52
  }
49
53
 
50
54
  /**
@@ -183,12 +187,23 @@ export function parseScriptEnvelope(
183
187
  const rawResult = envelope.scriptResult
184
188
  let scriptResult: string | undefined
185
189
  let scriptError: string
190
+ let fmsMessage: string | undefined
186
191
 
187
- if (rawResult !== null && typeof rawResult === 'object' && 'resultParameter' in rawResult) {
188
- // Nested envelope (FMS v26+): code + resultParameter inside scriptResult
189
- const nested = rawResult as { code?: unknown; resultParameter?: unknown }
192
+ if (
193
+ rawResult !== null &&
194
+ typeof rawResult === 'object' &&
195
+ ('code' in rawResult || 'resultParameter' in rawResult)
196
+ ) {
197
+ // Nested envelope (FMS v26+): code + resultParameter (+ message) inside scriptResult
198
+ const nested = rawResult as { code?: unknown; resultParameter?: unknown; message?: unknown }
190
199
  scriptError = nested.code !== undefined ? String(nested.code) : '0'
191
- scriptResult = nested.resultParameter !== undefined ? String(nested.resultParameter) : undefined
200
+ scriptResult =
201
+ nested.resultParameter !== undefined
202
+ ? typeof nested.resultParameter === 'string'
203
+ ? nested.resultParameter
204
+ : JSON.stringify(nested.resultParameter)
205
+ : undefined
206
+ if (typeof nested.message === 'string') fmsMessage = nested.message
192
207
  } else {
193
208
  // Flat envelope (older FMS): scriptResult is a string, scriptError is a sibling
194
209
  scriptError = envelope.scriptError !== undefined ? String(envelope.scriptError) : '0'
@@ -202,7 +217,9 @@ export function parseScriptEnvelope(
202
217
 
203
218
  if (scriptError !== '0') {
204
219
  throw new FMScriptError(
205
- `FileMaker script error ${scriptError}`,
220
+ fmsMessage
221
+ ? `FileMaker script error ${scriptError}: ${fmsMessage}`
222
+ : `FileMaker script error ${scriptError}`,
206
223
  {
207
224
  status: 200,
208
225
  scriptError,