Skip to content

Commit d9fe5d6

Browse files
Add namespace bindings to Xml.elements (#11406)
Co-authored-by: Effect Bot <tech-ops@effectful.co>
1 parent ec88772 commit d9fe5d6

3 files changed

Lines changed: 258 additions & 22 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
Preserve inherited namespace bindings on elements collected by `Xml.elements` after decoding with `namespaces: "strict"`. Add `Xml.attribute` to read attributes by namespace URI and local name, and `Xml.resolveQName` to resolve qualified names in values; both require strict decoding.

‎packages/effect/src/encoding/Xml.ts‎

Lines changed: 215 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import * as Cause from "../Cause.ts"
2222
import * as Channel from "../Channel.ts"
2323
import * as Data from "../Data.ts"
2424
import * as Effect from "../Effect.ts"
25+
import * as Option from "../Option.ts"
2526
import * as Predicate from "../Predicate.ts"
2627
import * as Pull from "../Pull.ts"
2728
import { isWellFormed } from "../String.ts"
@@ -278,7 +279,8 @@ export type Event =
278279
* instructions are dropped.
279280
*
280281
* When the events were decoded with `namespaces: "strict"`, `namespace` and
281-
* `localName` give the element's resolved name. Otherwise they are absent.
282+
* `localName` give the element's resolved name, and `namespaces` the bindings
283+
* in scope at it. Otherwise they are absent.
282284
*
283285
* @stability experimental
284286
* @category models
@@ -299,10 +301,51 @@ export interface Element {
299301
* @since 4.1.5
300302
*/
301303
readonly localName?: string | undefined
304+
/**
305+
* Namespace bindings in scope at the element, with `namespaces: "strict"`.
306+
*
307+
* @since 4.2.1
308+
*/
309+
readonly namespaces?: Namespaces | undefined
302310
readonly attributes: Readonly<Record<string, string>>
303311
readonly children: ReadonlyArray<Element | string>
304312
}
305313

314+
/**
315+
* Namespace bindings in scope at a collected element.
316+
*
317+
* **Details**
318+
*
319+
* `declarations` maps prefixes to namespace URIs; `parent` links to inherited
320+
* bindings, including those from outside the collected tree. Elements without
321+
* declarations share their parent's bindings. Lookups use the nearest declaration.
322+
* The key `""` denotes the default namespace; an empty URI clears it.
323+
* The `xml` prefix is always bound and is not listed.
324+
*
325+
* @see {@link resolveQName} for resolving a qualified name in a value
326+
* @see {@link attribute} for reading an attribute by namespace
327+
*
328+
* @stability experimental
329+
* @category models
330+
* @since 4.2.1
331+
*/
332+
export interface Namespaces {
333+
readonly declarations: Readonly<Record<string, string>>
334+
readonly parent: Namespaces | undefined
335+
}
336+
337+
/**
338+
* Name returned by `resolveQName`, with `namespace: ""` when no namespace applies.
339+
*
340+
* @stability experimental
341+
* @category models
342+
* @since 4.2.1
343+
*/
344+
export interface QName {
345+
readonly namespace: string
346+
readonly localName: string
347+
}
348+
306349
/**
307350
* Options for the XML decoders.
308351
*
@@ -358,8 +401,9 @@ export interface DecodeOptions {
358401
*
359402
* `maxElementSize` is the maximum size of one collected element, counted as
360403
* the UTF-16 code units of its names, attribute names and values, and text.
361-
* `namespace` and `localName` are not counted. Defaults to 16 MiB; `Infinity`
362-
* disables the limit. Invalid options throw when the channel is created.
404+
* `namespace`, `localName` and `namespaces` are not counted. Defaults to
405+
* 16 MiB; `Infinity` disables the limit. Invalid options throw when the
406+
* channel is created.
363407
*
364408
* @stability experimental
365409
* @category configuration
@@ -499,6 +543,9 @@ export const decode = <IE = never, Done = unknown>(options?: DecodeOptions): Cha
499543
* paths start at the root, an element nested in a matched element is part of
500544
* its tree and is not emitted separately.
501545
*
546+
* With events decoded using `namespaces: "strict"`, each element's `namespaces`
547+
* includes bindings inherited from ancestors outside the collected tree.
548+
*
502549
* **Gotchas**
503550
*
504551
* - A path that does not start at the root element matches nothing.
@@ -569,6 +616,118 @@ export const elements = <IE = never, Done = unknown>(
569616
return makeChannel<Event, Element, IE, Done>(() => new Collector(segments, maxElementSize))
570617
}
571618

619+
/**
620+
* Returns an attribute's value by namespace URI and local name, or `Option.none()`
621+
* if absent.
622+
*
623+
* **Details**
624+
*
625+
* Matches prefixed attributes by their bound namespace URI. Unprefixed
626+
* attributes use `namespace: ""`, regardless of the default namespace.
627+
* Use `http://www.w3.org/2000/xmlns/` to read the element's own namespace
628+
* declarations, with local name `xmlns` for the default declaration.
629+
*
630+
* **Gotchas**
631+
*
632+
* - Requires an element collected from events decoded with `namespaces: "strict"`.
633+
* Throws if the element has no `namespaces`.
634+
*
635+
* **Example** (Reading `xsi:type`)
636+
*
637+
* ```ts import.meta.vitest
638+
* import { Effect, Option, Stream } from "effect"
639+
* import { Xml } from "effect/encoding"
640+
*
641+
* const xsi = "http://www.w3.org/2001/XMLSchema-instance"
642+
* const xml = `<r xmlns:i="${xsi}"><a i:type="Order"/></r>`
643+
*
644+
* const [a] = await Effect.runPromise(
645+
* Stream.make(xml).pipe(
646+
* Stream.pipeThroughChannel(Xml.decodeString({ namespaces: "strict" })),
647+
* Stream.pipeThroughChannel(Xml.elements(["r", "a"])),
648+
* Stream.runCollect
649+
* )
650+
* )
651+
* Xml.attribute(a, xsi, "type") // => Option.some("Order")
652+
* ```
653+
*
654+
* @see {@link resolveQName} for resolving a qualified name in a value
655+
*
656+
* @stability experimental
657+
* @category accessors
658+
* @since 4.2.1
659+
*/
660+
export const attribute = (element: Element, namespace: string, localName: string): Option.Option<string> => {
661+
const namespaces = namespacesOf(element)
662+
const attributes = element.attributes
663+
if (namespace === xmlnsNamespace) {
664+
const name = localName === "xmlns" ? localName : `xmlns:${localName}`
665+
return Object.hasOwn(attributes, name) ? Option.some(attributes[name]) : Option.none()
666+
}
667+
if (namespace === "") {
668+
// The xmlns attribute belongs to the xmlns namespace
669+
return localName !== "xmlns" && !localName.includes(":") && Object.hasOwn(attributes, localName)
670+
? Option.some(attributes[localName])
671+
: Option.none()
672+
}
673+
for (const name in attributes) {
674+
if (!Object.hasOwn(attributes, name)) continue
675+
const colon = name.length - localName.length - 1
676+
if (colon > 0 && name.charCodeAt(colon) === COLON && name.endsWith(localName)) {
677+
const prefix = name.slice(0, colon)
678+
if (lookupNamespace(namespaces, prefix) === namespace) return Option.some(attributes[name])
679+
}
680+
}
681+
return Option.none()
682+
}
683+
684+
/**
685+
* Resolves a qualified name in a value, such as `tns:Order`, using an element's
686+
* namespace bindings. Returns `Option.none()` for an invalid name or undeclared prefix.
687+
*
688+
* **Details**
689+
*
690+
* Ignores leading and trailing XML whitespace. An unprefixed value uses the
691+
* default namespace, unlike an unprefixed attribute name.
692+
*
693+
* **Gotchas**
694+
*
695+
* - Requires an element collected from events decoded with `namespaces: "strict"`.
696+
* Throws if the element has no `namespaces`.
697+
*
698+
* @see {@link attribute} for reading an attribute by namespace
699+
*
700+
* @stability experimental
701+
* @category accessors
702+
* @since 4.2.1
703+
*/
704+
export const resolveQName = (element: Element, value: string): Option.Option<QName> => {
705+
const namespaces = namespacesOf(element)
706+
let end = value.length
707+
while (end > 0 && isSpace(value.charCodeAt(end - 1))) end--
708+
const name = value.slice(skipSpace(value, 0, end), end)
709+
const colon = isName(name) ? qnameColon(name) : -2
710+
if (colon === -2) return Option.none()
711+
if (colon === -1) return Option.some({ namespace: lookupNamespace(namespaces, "") ?? "", localName: name })
712+
const namespace = lookupNamespace(namespaces, name.slice(0, colon))
713+
return namespace === undefined ? Option.none() : Option.some({ namespace, localName: name.slice(colon + 1) })
714+
}
715+
716+
const namespacesOf = (element: Element): Namespaces => {
717+
if (element.namespaces === undefined) {
718+
throw new Error(`Xml: element <${element.name}> has no namespaces: decode with namespaces: "strict"`)
719+
}
720+
return element.namespaces
721+
}
722+
723+
const lookupNamespace = (namespaces: Namespaces, prefix: string): string | undefined => {
724+
if (prefix === "xml") return xmlNamespace
725+
for (let scope: Namespaces | undefined = namespaces; scope !== undefined; scope = scope.parent) {
726+
if (Object.hasOwn(scope.declarations, prefix)) return scope.declarations[prefix]
727+
}
728+
return undefined
729+
}
730+
572731
/**
573732
* Creates a channel that writes events as XML text.
574733
*
@@ -674,6 +833,8 @@ export const encode = <IE = never, Done = unknown>(): Channel.Channel<
674833
* A collected subtree does not carry `xmlns` declarations inherited from its
675834
* ancestors. When writing it elsewhere, supply the same bindings on the subtree
676835
* or in its new enclosing scope, including any inherited default namespace.
836+
* With `namespaces: "strict"`, those bindings are in the element's
837+
* `namespaces`.
677838
*
678839
* **Example** (Writing an element)
679840
*
@@ -834,6 +995,7 @@ const AMPERSAND = 38
834995
const SQUOTE = 39
835996
const DASH = 45
836997
const SLASH = 47
998+
const COLON = 58
837999
const LT = 60
8381000
const EQUALS = 61
8391001
const GT = 62
@@ -898,6 +1060,16 @@ const scanName = (s: string, i: number, end: number): number => {
8981060
// Name characters exclude every invalid character but unpaired surrogates
8991061
const isName = (s: string): boolean => s.length > 0 && scanName(s, 0, s.length) === s.length && isWellFormed(s)
9001062

1063+
// Returns the index of the colon in a name, -1 when it has none, or -2 when it
1064+
// is not a qualified name
1065+
const qnameColon = (name: string): number => {
1066+
const colon = name.indexOf(":")
1067+
return colon !== -1 && (colon === 0 || colon === name.length - 1 || name.indexOf(":", colon + 1) !== -1 ||
1068+
!isNameStartCode(name.charCodeAt(colon + 1))) ?
1069+
-2 :
1070+
colon
1071+
}
1072+
9011073
const skipSpace = (s: string, i: number, end: number): number => {
9021074
while (i < end && isSpace(s.charCodeAt(i))) i++
9031075
return i
@@ -1737,15 +1909,9 @@ class Parser {
17371909
return scope
17381910
}
17391911

1740-
// Returns the index of the colon in a qualified name, or -1 when it has none
17411912
private qnameColon(kind: "element" | "attribute", name: string, i: number): number {
1742-
const colon = name.indexOf(":")
1743-
if (
1744-
colon !== -1 && (colon === 0 || colon === name.length - 1 || name.indexOf(":", colon + 1) !== -1 ||
1745-
!isNameStartCode(name.charCodeAt(colon + 1)))
1746-
) {
1747-
throw this.syntax(`${kind} name ${name} is not a qualified name`, i)
1748-
}
1913+
const colon = qnameColon(name)
1914+
if (colon === -2) throw this.syntax(`${kind} name ${name} is not a qualified name`, i)
17491915
return colon
17501916
}
17511917

@@ -2154,9 +2320,29 @@ class Utf8Input implements Machine<Uint8Array, Event> {
21542320
}
21552321

21562322
interface MutableElement extends Element {
2323+
namespaces?: Namespaces | undefined
21572324
readonly children: Array<MutableElement | string>
21582325
}
21592326

2327+
const noNamespaces: Namespaces = Object.freeze({ declarations: emptyAttributes, parent: undefined })
2328+
2329+
// Declarations are copied, as they can outlive the chunk of their tag
2330+
const declare = (
2331+
parent: Namespaces | undefined,
2332+
attributes: Readonly<Record<string, string>>
2333+
): Namespaces | undefined => {
2334+
let declarations: Record<string, string> | undefined
2335+
for (const name in attributes) {
2336+
if (!Object.hasOwn(attributes, name)) continue
2337+
const prefix = name === "xmlns" ? "" : name.startsWith("xmlns:") ? name.slice(6) : undefined
2338+
// Omit the reserved xml and xmlns prefixes
2339+
if (prefix === undefined || prefix === "xml" || prefix === "xmlns") continue
2340+
declarations ??= new Attributes()
2341+
declarations[copyString(prefix)] = copyString(attributes[name])
2342+
}
2343+
return declarations === undefined ? parent : { declarations, parent }
2344+
}
2345+
21602346
// `string` is "*" or a literal name; `namespace: undefined` matches any namespace
21612347
type Segment = string | { readonly namespace: string | undefined; readonly localName: string }
21622348

@@ -2179,11 +2365,12 @@ const matches = (segment: Segment, event: StartElement): boolean =>
21792365

21802366
class Collector implements Machine<Event, Element> {
21812367
out: Array<Element> = []
2182-
private depth = 0
21832368
// Number of open elements, from the root, that match the path
21842369
private matched = 0
21852370
// The element being collected and its open descendants
21862371
private readonly stack: Array<MutableElement> = []
2372+
// One scope entry per open element; also tracks depth through skipped subtrees
2373+
private readonly scopes: Array<Namespaces | undefined> = []
21872374
private size = 0
21882375
private readonly path: ReadonlyArray<Segment>
21892376
private readonly maxElementSize: number
@@ -2203,16 +2390,25 @@ class Collector implements Machine<Event, Element> {
22032390
`start tag <${event.name}> without localName for a path in Clark notation: decode with namespaces: "strict"`
22042391
)
22052392
}
2206-
const depth = this.depth++
2207-
if (this.stack.length === 0) {
2208-
if (this.matched !== depth || !matches(this.path[depth], event)) return
2393+
const depth = this.scopes.length
2394+
const parent = this.scopes[depth - 1]
2395+
const collecting = this.stack.length > 0
2396+
if (!collecting && (this.matched !== depth || !matches(this.path[depth], event))) {
2397+
// Skip declarations for subtrees outside the selected path
2398+
this.scopes.push(parent)
2399+
return
2400+
}
2401+
const scope = event.localName === undefined ? parent : declare(parent, event.attributes)
2402+
this.scopes.push(scope)
2403+
if (!collecting) {
22092404
if (++this.matched < this.path.length) return
22102405
this.size = 0
22112406
}
22122407
const element = withResolvedName<MutableElement>(
22132408
{ name: event.name, attributes: event.attributes, children: [] },
22142409
event
22152410
)
2411+
if (event.localName !== undefined) element.namespaces = scope ?? noNamespaces
22162412
if (this.stack.length > 0) this.stack[this.stack.length - 1].children.push(element)
22172413
this.stack.push(element)
22182414
let size = event.name.length
@@ -2221,13 +2417,13 @@ class Collector implements Machine<Event, Element> {
22212417
return
22222418
}
22232419
case "EndElement": {
2224-
if (this.depth === 0) throw invalidEvent(`end tag </${event.name}> without a start tag`)
2420+
if (this.scopes.length === 0) throw invalidEvent(`end tag </${event.name}> without a start tag`)
22252421
if (this.stack.length > 0) {
22262422
const element = this.stack.pop()!
22272423
if (this.stack.length === 0) this.out.push(element)
22282424
}
2229-
if (this.matched === this.depth) this.matched--
2230-
this.depth--
2425+
if (this.matched === this.scopes.length) this.matched--
2426+
this.scopes.pop()
22312427
return
22322428
}
22332429
case "Text": {
@@ -2243,7 +2439,7 @@ class Collector implements Machine<Event, Element> {
22432439
}
22442440

22452441
end(): void {
2246-
if (this.depth > 0) throw invalidEvent("events ended inside an element")
2442+
if (this.scopes.length > 0) throw invalidEvent("events ended inside an element")
22472443
}
22482444

22492445
private grow(size: number): void {

0 commit comments

Comments
 (0)