@asymmetric-effort/specifyjs 0.2.100 → 0.2.105
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/dist/esm/chunks/chunk-3J4RXW7E.js +3 -0
- package/dist/esm/chunks/chunk-3J4RXW7E.js.map +7 -0
- package/dist/esm/chunks/chunk-3SXNLMCH.js +3 -0
- package/dist/esm/chunks/chunk-3SXNLMCH.js.map +7 -0
- package/dist/esm/chunks/chunk-A7AAS5ZR.js +3 -0
- package/dist/esm/chunks/chunk-A7AAS5ZR.js.map +7 -0
- package/dist/esm/chunks/chunk-E43OK6IZ.js +3 -0
- package/dist/esm/chunks/chunk-E43OK6IZ.js.map +7 -0
- package/dist/esm/chunks/chunk-LWOMFZ4C.js +3 -0
- package/dist/esm/chunks/chunk-LWOMFZ4C.js.map +7 -0
- package/dist/esm/chunks/chunk-MCXU6QF3.js +3 -0
- package/dist/esm/chunks/chunk-MCXU6QF3.js.map +7 -0
- package/dist/esm/chunks/chunk-ODCBJ22O.js +3 -0
- package/dist/esm/chunks/chunk-ODCBJ22O.js.map +7 -0
- package/dist/esm/chunks/chunk-TVDAY42P.js +3 -0
- package/dist/esm/chunks/chunk-TVDAY42P.js.map +7 -0
- package/dist/esm/chunks/chunk-VAF4KNDP.js +3 -0
- package/dist/esm/chunks/chunk-VAF4KNDP.js.map +7 -0
- package/dist/esm/chunks/chunk-ZDPD2MPQ.js +3 -0
- package/dist/esm/chunks/chunk-ZDPD2MPQ.js.map +7 -0
- package/dist/esm/chunks/metrics-56RIK7JQ.js +3 -0
- package/dist/esm/chunks/metrics-56RIK7JQ.js.map +7 -0
- package/dist/esm/client/index.js +3 -0
- package/dist/esm/components-barrel.js +9 -0
- package/dist/esm/dom/index.js +3 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/jsx-dev-runtime.js +3 -0
- package/dist/esm/jsx-runtime.js +3 -0
- package/dist/esm/server/index.js +3 -0
- package/dist/esm/telemetry/index.js +3 -0
- package/dist/specifyjs-client.esm.js +2 -2
- package/dist/specifyjs-client.esm.js.map +4 -4
- package/dist/specifyjs-components.cjs.js +1 -1
- package/dist/specifyjs-components.cjs.js.map +2 -2
- package/dist/specifyjs-components.esm.js +4 -4
- package/dist/specifyjs-components.esm.js.map +4 -4
- package/dist/specifyjs-dom.esm.js +2 -2
- package/dist/specifyjs-dom.esm.js.map +4 -4
- package/dist/specifyjs-jsx-dev-runtime.esm.js +2 -2
- package/dist/specifyjs-jsx-dev-runtime.esm.js.map +4 -4
- package/dist/specifyjs-jsx-runtime.esm.js +2 -2
- package/dist/specifyjs-jsx-runtime.esm.js.map +4 -4
- package/dist/specifyjs-server.esm.js +2 -2
- package/dist/specifyjs-server.esm.js.map +4 -4
- package/dist/specifyjs-telemetry.esm.js +2 -2
- package/dist/specifyjs-telemetry.esm.js.map +4 -4
- package/dist/specifyjs.esm.js +2 -2
- package/dist/specifyjs.esm.js.map +4 -4
- package/dist/types/components/viz/3d-force-graph/src/ForceGraph3D.d.ts +123 -0
- package/dist/types/components/viz/3d-force-graph/src/index.d.ts +2 -0
- package/package.json +3 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE */
|
|
2
|
-
|
|
3
|
-
//# sourceMappingURL=
|
|
2
|
+
import{a as s}from"./esm/chunks/chunk-LWOMFZ4C.js";import{c as r}from"./esm/chunks/chunk-ODCBJ22O.js";import"./esm/chunks/chunk-3J4RXW7E.js";import"./esm/chunks/chunk-ZDPD2MPQ.js";export{r as Fragment,s as jsxDEV};
|
|
3
|
+
//# sourceMappingURL=jsx-dev-runtime.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": [
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": [],
|
|
4
|
+
"sourcesContent": [],
|
|
5
|
+
"mappings": "",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE */
|
|
2
|
-
|
|
3
|
-
//# sourceMappingURL=
|
|
2
|
+
import{a as b}from"./esm/chunks/chunk-LWOMFZ4C.js";import{c as a}from"./esm/chunks/chunk-ODCBJ22O.js";import"./esm/chunks/chunk-3J4RXW7E.js";import"./esm/chunks/chunk-ZDPD2MPQ.js";export{a as Fragment,b as jsx,b as jsxs};
|
|
3
|
+
//# sourceMappingURL=jsx-runtime.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": [
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": [],
|
|
4
|
+
"sourcesContent": [],
|
|
5
|
+
"mappings": "",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE */
|
|
2
|
-
|
|
3
|
-
//# sourceMappingURL=
|
|
2
|
+
import{a as f}from"./esm/chunks/chunk-E43OK6IZ.js";import{b as d,d as m,f as S,g,j as h,k as y}from"./esm/chunks/chunk-3J4RXW7E.js";import"./esm/chunks/chunk-ZDPD2MPQ.js";var P=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),T={className:"class",htmlFor:"for",httpEquiv:"http-equiv",acceptCharset:"accept-charset",tabIndex:"tabindex",autoFocus:"autofocus",autoComplete:"autocomplete",autoPlay:"autoplay",crossOrigin:"crossorigin",noValidate:"novalidate",formNoValidate:"formnovalidate",readOnly:"readonly",cellPadding:"cellpadding",cellSpacing:"cellspacing",colSpan:"colspan",rowSpan:"rowspan",frameBorder:"frameborder",marginHeight:"marginheight",marginWidth:"marginwidth"},C=new Set(["children","key","ref","dangerouslySetInnerHTML"]),_=/^on[A-Z]/;function l(t){return b("renderToString"),c(t,!0)}function x(t){return b("renderToStaticMarkup"),c(t,!1)}function b(t){typeof process<"u"&&typeof process.env<"u"&&process.env.SPECIFYJS_ALLOW_PRERENDER==="true"||typeof process<"u"&&typeof process.env<"u"&&(process.env.SPECIFYJS_ALLOW_PRERENDER||console.warn(`[SpecifyJS] ${t}() is intended for build-time pre-rendering only, not runtime server-side rendering. Set SPECIFYJS_ALLOW_PRERENDER=true if you are using this in a build script. See: https://github.com/asymmetric-effort/specifyjs/blob/main/docs/api/static-prerendering.md`))}function c(t,o){if(t==null||typeof t=="boolean")return"";if(typeof t=="string")return u(t);if(typeof t=="number")return String(t);if(Array.isArray(t)){let e="",n=[];for(let r=t.length-1;r>=0;r--)n.push(t[r]);for(;n.length>0;){let r=n.pop();if(!(r==null||typeof r=="boolean")){if(typeof r=="string"){e+=u(r);continue}if(typeof r=="number"){e+=String(r);continue}if(Array.isArray(r)){for(let s=r.length-1;s>=0;s--)n.push(r[s]);continue}f(r)&&(e+=E(r,o))}}return e}return f(t)?E(t,o):""}function E(t,o){let{type:i,props:e}=t;if(i===d||i===h||i===y)return c(e.children,o);if(typeof i=="object"&&i!==null){let n=i.$$typeof;if(n===m){let r=i._context,s=r._currentValue;r._currentValue=e.value;let a=c(e.children,o);return r._currentValue=s,a}if(n===S){let r=i.render,s=r(e,t.ref);return c(s,o)}if(n===g){let r=i.type;if(typeof r=="function"){let s=r(e);return c(s,o)}}}if(typeof i=="function"){if(i.prototype?.isSpecComponent){let r=i,a=new r(e).render();return c(a,o)}let n=i(e);return c(n,o)}return typeof i=="string"?k(i,e,o):""}function k(t,o,i){let e=`<${t}`;for(let n in o){if(C.has(n)||_.test(n))continue;let r=o[n];if(r==null||r===!1)continue;let s=T[n]||n.toLowerCase();/^[a-zA-Z_][\w\-:.]*$/.test(s)&&(n==="style"?e+=` style="${w(r)}"`:n==="value"||n==="checked"||n==="selected"?r===!0?e+=` ${s}`:e+=` ${s}="${u(String(r))}"`:r===!0?e+=` ${s}`:e+=` ${s}="${u(String(r))}"`)}if(P.has(t))return e+="/>",e;if(e+=">",o.dangerouslySetInnerHTML){let n=o.dangerouslySetInnerHTML.__html;e+=n}else e+=c(o.children,i);return e+=`</${t}>`,e}function w(t){let o=[];for(let i in t){let e=t[i];if(e==null)continue;let n=i.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`),r=typeof e=="number"&&e!==0&&!O(i)?`${e}px`:String(e);r=r.replace(/expression\s*\(/gi,"").replace(/url\s*\(\s*javascript:/gi,"url("),o.push(`${n}:${r}`)}return o.join(";")}var v=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function O(t){return v.has(t)}function u(t){let o="",i=0;for(let e=0;e<t.length;e++){let n;switch(t.charCodeAt(e)){case 34:n=""";break;case 38:n="&";break;case 39:n="'";break;case 60:n="<";break;case 62:n=">";break}n!==void 0&&(i!==e&&(o+=t.slice(i,e)),o+=n,i=e+1)}return i===0?t:(i<t.length&&(o+=t.slice(i)),o)}function N(t,o){let i=!1;return{pipe(e){if(i)return e.end(),e;let n;try{n=l(t)}catch(a){return o?.onShellError?.(a),o?.onError?.(a),e.end(),e}o?.onShellReady?.();let r=o?.progressiveChunkSize??8192;if(n.length<=r)e.write(n),e.end(),o?.onAllReady?.();else{let p=function(){if(i||a>=n.length){e.end(),o?.onAllReady?.();return}let R=n.slice(a,a+r);a+=r,e.write(R)?setImmediate(p):e.once("drain",p)};var s=p;let a=0;p()}return e},abort(e){i=!0,o?.onError?.(e)}}}async function I(t,o){let i=new TextEncoder,e=o?.progressiveChunkSize??8192;return new ReadableStream({start(n){if(o?.signal?.aborted){n.close();return}let r;try{r=l(t)}catch(a){o?.onError?.(a),n.error(a);return}let s=0;for(;s<r.length;){let a=r.slice(s,s+e);n.enqueue(i.encode(a)),s+=e}n.close()}})}export{N as renderToPipeableStream,I as renderToReadableStream,x as renderToStaticMarkup,l as renderToString};
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["
|
|
4
|
-
"sourcesContent": ["// ============================================================================\n// SpecifyJS Core Types\n// ============================================================================\n// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\n/** Unique symbol to identify SpecifyJS elements */\nexport const SPEC_ELEMENT_TYPE = Symbol.for('spec.element');\nexport const SPEC_FRAGMENT_TYPE = Symbol.for('spec.fragment');\nexport const SPEC_PORTAL_TYPE = Symbol.for('spec.portal');\nexport const SPEC_PROVIDER_TYPE = Symbol.for('spec.provider');\nexport const SPEC_CONSUMER_TYPE = Symbol.for('spec.consumer');\nexport const SPEC_FORWARD_REF_TYPE = Symbol.for('spec.forward_ref');\nexport const SPEC_MEMO_TYPE = Symbol.for('spec.memo');\nexport const SPEC_LAZY_TYPE = Symbol.for('spec.lazy');\nexport const SPEC_SUSPENSE_TYPE = Symbol.for('spec.suspense');\nexport const SPEC_STRICT_MODE_TYPE = Symbol.for('spec.strict_mode');\nexport const SPEC_PROFILER_TYPE = Symbol.for('spec.profiler');\n\n/** A key used for reconciliation */\nexport type Key = string | number | null;\n\n/** A ref can be a callback, an object, or null */\nexport type Ref<T = unknown> = RefCallback<T> | RefObject<T> | null;\nexport type RefCallback<T> = (instance: T | null) => void;\nexport interface RefObject<T> {\n current: T | null;\n}\n\n/** Props are an arbitrary key-value map */\nexport type Props = Record<string, unknown> & {\n children?: SpecNode;\n key?: Key;\n ref?: Ref;\n};\n\n/** Valid child types in a SpecifyJS tree */\nexport type SpecChild = SpecElement | string | number | boolean | null | undefined;\nexport type SpecNode = SpecChild | SpecNode[];\n\n/** A functional component */\nexport type FunctionComponent<P extends Props = Props> = (props: P) => SpecNode;\n\n/** A class component constructor */\nexport interface ClassComponentConstructor<P extends Props = Props, S = unknown> {\n new (props: P): ClassComponentInstance<P, S>;\n getDerivedStateFromProps?(props: P, state: S): Partial<S> | null;\n getDerivedStateFromError?(error: unknown): Partial<S> | null;\n}\n\n/** Instance of a class component */\nexport interface ClassComponentInstance<P extends Props = Props, S = unknown> {\n props: P;\n state: S;\n setState(updater: Partial<S> | ((prevState: S, props: P) => Partial<S> | null)): void;\n forceUpdate(callback?: () => void): void;\n render(): SpecNode;\n componentDidMount?(): void;\n componentDidUpdate?(prevProps: P, prevState: S, snapshot?: unknown): void;\n componentWillUnmount?(): void;\n shouldComponentUpdate?(nextProps: P, nextState: S): boolean;\n getSnapshotBeforeUpdate?(prevProps: P, prevState: S): unknown;\n componentDidCatch?(error: unknown, info: ErrorInfo): void;\n // Internal: set by the reconciler for setState/forceUpdate wiring\n _fiber: unknown;\n _pendingState: Array<Partial<S> | ((prevState: S, props: P) => Partial<S> | null)>;\n _forceUpdate: boolean;\n _enqueueUpdate(callback?: () => void): void;\n}\n\nexport interface ErrorInfo {\n componentStack: string;\n}\n\n/** A component type can be a function, a class, or a special symbol type */\nexport type ComponentType<P extends Props = Props> =\n | FunctionComponent<P>\n | ClassComponentConstructor<P>\n | string\n | symbol;\n\n/** The core element structure \u2014 equivalent to React.Element */\nexport interface SpecElement<P extends Props = Props> {\n $$typeof: typeof SPEC_ELEMENT_TYPE;\n type: ComponentType<P>;\n props: P;\n key: Key;\n ref: Ref;\n}\n\n/** Fiber node types for the reconciler */\nexport const enum FiberTag {\n FunctionComponent = 0,\n ClassComponent = 1,\n HostRoot = 2,\n HostComponent = 3,\n HostText = 4,\n Fragment = 5,\n ContextProvider = 6,\n ContextConsumer = 7,\n ForwardRef = 8,\n MemoComponent = 9,\n LazyComponent = 10,\n SuspenseComponent = 11,\n Profiler = 12,\n Portal = 13,\n}\n\n/** Effect flags for fiber work */\nexport const enum EffectTag {\n NoEffect = 0,\n Placement = 1,\n Update = 2,\n Deletion = 4,\n ChildDeletion = 8,\n Snapshot = 16,\n Passive = 32,\n Layout = 64,\n Ref = 128,\n}\n\n/** Fiber node \u2014 the internal work unit */\nexport interface Fiber<P extends Props = Props> {\n tag: FiberTag;\n type: ComponentType<P> | null;\n key: Key;\n ref: Ref;\n\n stateNode: unknown;\n pendingProps: P;\n memoizedProps: P | null;\n memoizedState: unknown;\n\n return: Fiber | null;\n child: Fiber | null;\n sibling: Fiber | null;\n index: number;\n\n alternate: Fiber | null;\n effectTag: EffectTag;\n\n updateQueue: unknown;\n dependencies: unknown;\n\n lanes: number;\n childLanes: number;\n}\n\n/** Context type */\nexport interface SpecContext<T> {\n $$typeof: symbol;\n Provider: ComponentType;\n Consumer: ComponentType;\n _currentValue: T;\n _defaultValue: T;\n displayName?: string;\n}\n", "// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport { SPEC_ELEMENT_TYPE, type SpecElement } from '../shared/types';\n\n/**\n * Checks if a value is a valid SpecifyJS element.\n * Equivalent to React.isValidElement.\n */\nexport function isValidElement(object: unknown): object is SpecElement {\n return (\n typeof object === 'object' &&\n object !== null &&\n (object as SpecElement).$$typeof === SPEC_ELEMENT_TYPE\n );\n}\n", "// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport {\n type SpecNode,\n type SpecElement,\n type Props,\n type FunctionComponent,\n type ClassComponentInstance,\n SPEC_FRAGMENT_TYPE,\n SPEC_STRICT_MODE_TYPE,\n SPEC_PROFILER_TYPE,\n SPEC_FORWARD_REF_TYPE,\n SPEC_MEMO_TYPE,\n SPEC_PROVIDER_TYPE,\n} from '../shared/types';\nimport { isValidElement } from '../core/is-valid-element';\n\n// Self-closing HTML tags\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\n// Map of prop names to HTML attribute names\nconst PROP_TO_ATTR: Record<string, string> = {\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n acceptCharset: 'accept-charset',\n tabIndex: 'tabindex',\n autoFocus: 'autofocus',\n autoComplete: 'autocomplete',\n autoPlay: 'autoplay',\n crossOrigin: 'crossorigin',\n noValidate: 'novalidate',\n formNoValidate: 'formnovalidate',\n readOnly: 'readonly',\n cellPadding: 'cellpadding',\n cellSpacing: 'cellspacing',\n colSpan: 'colspan',\n rowSpan: 'rowspan',\n frameBorder: 'frameborder',\n marginHeight: 'marginheight',\n marginWidth: 'marginwidth',\n};\n\n// Props that should not be rendered as attributes\nconst RESERVED_PROPS = new Set(['children', 'key', 'ref', 'dangerouslySetInnerHTML']);\n\nconst EVENT_RE = /^on[A-Z]/;\n\n/**\n * Renders a SpecifyJS component tree to an HTML string.\n *\n * **Build-time pre-rendering only.** This function is designed for use\n * during the build process (e.g., static site generation, build scripts)\n * to produce HTML files that are served statically. It must NOT be called\n * in server request handlers, middleware, or any runtime code path that\n * responds to HTTP requests.\n *\n * For dynamic content, use SpecifyJS's client-side rendering with data\n * fetched via HTTPS from API endpoints.\n *\n * @throws {Error} If called in a detected server request context\n */\nexport function renderToString(element: SpecNode): string {\n assertNotInRequestContext('renderToString');\n return renderNode(element, true);\n}\n\n/**\n * Renders a SpecifyJS component tree to static HTML (no hydration markers).\n *\n * **Build-time pre-rendering only.** Use in build scripts to generate\n * static HTML pages. Do NOT use in server request handlers.\n *\n * @throws {Error} If called in a detected server request context\n */\nexport function renderToStaticMarkup(element: SpecNode): string {\n assertNotInRequestContext('renderToStaticMarkup');\n return renderNode(element, false);\n}\n\n/**\n * Guard against misuse in server request handlers.\n * Detects common server frameworks (Express, Koa, Fastify, etc.)\n * by checking for telltale global state.\n */\n/* v8 ignore next 22 -- environment detection only triggers in Node.js production */\nfunction assertNotInRequestContext(fnName: string): void {\n if (\n typeof process !== 'undefined' &&\n typeof process.env !== 'undefined' &&\n process.env.SPECIFYJS_ALLOW_PRERENDER === 'true'\n ) {\n return;\n }\n\n if (\n typeof process !== 'undefined' &&\n typeof process.env !== 'undefined' &&\n (process.env.NODE_ENV === 'production' || process.env.PORT)\n ) {\n if (!process.env.SPECIFYJS_ALLOW_PRERENDER) {\n console.warn(\n `[SpecifyJS] ${fnName}() is intended for build-time pre-rendering only, ` +\n `not runtime server-side rendering. Set SPECIFYJS_ALLOW_PRERENDER=true ` +\n `if you are using this in a build script. See: ` +\n `https://github.com/asymmetric-effort/specifyjs/blob/main/docs/api/static-prerendering.md`,\n );\n }\n }\n}\n\nfunction renderNode(node: SpecNode, includeDataAttrs: boolean): string {\n // Null, undefined, boolean \u2192 empty\n if (node == null || typeof node === 'boolean') {\n return '';\n }\n\n // String or number \u2192 escape and return\n if (typeof node === 'string') {\n return escapeHtml(node);\n }\n if (typeof node === 'number') {\n return String(node);\n }\n\n // Array \u2192 render each child (iterative, no recursion for flat arrays)\n if (Array.isArray(node)) {\n let result = '';\n const stack: SpecNode[] = [];\n for (let i = node.length - 1; i >= 0; i--) stack.push(node[i] as SpecNode);\n while (stack.length > 0) {\n const child = stack.pop()!;\n if (child == null || typeof child === 'boolean') continue;\n if (typeof child === 'string') {\n result += escapeHtml(child);\n continue;\n }\n if (typeof child === 'number') {\n result += String(child);\n continue;\n }\n if (Array.isArray(child)) {\n for (let i = child.length - 1; i >= 0; i--) stack.push(child[i] as SpecNode);\n continue;\n }\n if (isValidElement(child)) result += renderElement(child as SpecElement, includeDataAttrs);\n }\n return result;\n }\n\n // Must be an element\n if (!isValidElement(node)) {\n return '';\n }\n\n const element = node as SpecElement;\n return renderElement(element, includeDataAttrs);\n}\n\nfunction renderElement(element: SpecElement, includeDataAttrs: boolean): string {\n const { type, props } = element;\n\n // Fragment, StrictMode, Profiler \u2192 render children only\n if (\n type === SPEC_FRAGMENT_TYPE ||\n type === SPEC_STRICT_MODE_TYPE ||\n type === SPEC_PROFILER_TYPE\n ) {\n return renderNode(props.children, includeDataAttrs);\n }\n\n // Context Provider \u2192 set value and render children\n if (typeof type === 'object' && type !== null) {\n const $$typeof = (type as { $$typeof?: symbol }).$$typeof;\n\n if ($$typeof === SPEC_PROVIDER_TYPE) {\n const context = (type as { _context: { _currentValue: unknown } })._context;\n const prevValue = context._currentValue;\n context._currentValue = props.value;\n const result = renderNode(props.children, includeDataAttrs);\n context._currentValue = prevValue;\n return result;\n }\n\n if ($$typeof === SPEC_FORWARD_REF_TYPE) {\n const render = (type as { render: (props: Props, ref: unknown) => SpecNode }).render;\n const children = render(props, element.ref);\n return renderNode(children, includeDataAttrs);\n }\n\n if ($$typeof === SPEC_MEMO_TYPE) {\n const innerType = (type as { type: FunctionComponent }).type;\n if (typeof innerType === 'function') {\n const children = innerType(props);\n return renderNode(children, includeDataAttrs);\n }\n }\n }\n\n // Function component\n if (typeof type === 'function') {\n if ((type.prototype as Record<string, unknown>)?.isSpecComponent) {\n // Class component\n const Constructor = type as new (props: Props) => ClassComponentInstance;\n const instance = new Constructor(props);\n const children = instance.render();\n return renderNode(children, includeDataAttrs);\n }\n\n // Functional component\n const children = (type as FunctionComponent)(props);\n return renderNode(children, includeDataAttrs);\n }\n\n // Host element (string tag)\n if (typeof type === 'string') {\n return renderHostElement(type, props, includeDataAttrs);\n }\n\n return '';\n}\n\nfunction renderHostElement(tag: string, props: Props, includeDataAttrs: boolean): string {\n let html = `<${tag}`;\n\n // Render attributes\n for (const key in props) {\n if (RESERVED_PROPS.has(key) || EVENT_RE.test(key)) continue;\n\n const value = props[key];\n if (value == null || value === false) continue;\n\n const attrName = PROP_TO_ATTR[key] || key.toLowerCase();\n\n // C-1: Validate attribute names to prevent XSS via attribute name injection\n if (!/^[a-zA-Z_][\\w\\-:.]*$/.test(attrName)) continue;\n\n if (key === 'style') {\n html += ` style=\"${renderStyle(value as Record<string, string | number>)}\"`;\n } else if (key === 'value' || key === 'checked' || key === 'selected') {\n if (value === true) {\n html += ` ${attrName}`;\n } else {\n html += ` ${attrName}=\"${escapeHtml(String(value))}\"`;\n }\n } else if (value === true) {\n html += ` ${attrName}`;\n } else {\n html += ` ${attrName}=\"${escapeHtml(String(value))}\"`;\n }\n }\n\n if (includeDataAttrs) {\n // Mark the root element for hydration\n }\n\n // Self-closing tags\n if (VOID_ELEMENTS.has(tag)) {\n html += '/>';\n return html;\n }\n\n html += '>';\n\n // dangerouslySetInnerHTML\n if (props.dangerouslySetInnerHTML) {\n const innerHtml = (props.dangerouslySetInnerHTML as { __html: string }).__html;\n html += innerHtml;\n } else {\n // Render children\n html += renderNode(props.children, includeDataAttrs);\n }\n\n html += `</${tag}>`;\n return html;\n}\n\nfunction renderStyle(style: Record<string, string | number>): string {\n const parts: string[] = [];\n for (const prop in style) {\n const value = style[prop];\n if (value == null) continue;\n\n // Convert camelCase to kebab-case\n const cssProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n let cssValue =\n typeof value === 'number' && value !== 0 && !isUnitlessProp(prop)\n ? `${value}px`\n : String(value);\n\n // L-6: Sanitize CSS values \u2014 strip dangerous patterns\n cssValue = cssValue\n .replace(/expression\\s*\\(/gi, '')\n .replace(/url\\s*\\(\\s*javascript:/gi, 'url(');\n\n parts.push(`${cssProp}:${cssValue}`);\n }\n return parts.join(';');\n}\n\nconst UNITLESS_PROPS = new Set([\n 'animationIterationCount',\n 'aspectRatio',\n 'borderImageOutset',\n 'borderImageSlice',\n 'borderImageWidth',\n 'boxFlex',\n 'boxFlexGroup',\n 'boxOrdinalGroup',\n 'columnCount',\n 'columns',\n 'flex',\n 'flexGrow',\n 'flexPositive',\n 'flexShrink',\n 'flexNegative',\n 'flexOrder',\n 'gridArea',\n 'gridRow',\n 'gridRowEnd',\n 'gridRowSpan',\n 'gridRowStart',\n 'gridColumn',\n 'gridColumnEnd',\n 'gridColumnSpan',\n 'gridColumnStart',\n 'fontWeight',\n 'lineClamp',\n 'lineHeight',\n 'opacity',\n 'order',\n 'orphans',\n 'tabSize',\n 'widows',\n 'zIndex',\n 'zoom',\n 'fillOpacity',\n 'floodOpacity',\n 'stopOpacity',\n 'strokeDasharray',\n 'strokeDashoffset',\n 'strokeMiterlimit',\n 'strokeOpacity',\n 'strokeWidth',\n]);\n\nfunction isUnitlessProp(prop: string): boolean {\n return UNITLESS_PROPS.has(prop);\n}\n\nfunction escapeHtml(str: string): string {\n let result = '';\n let lastIndex = 0;\n\n for (let i = 0; i < str.length; i++) {\n let escaped: string | undefined;\n switch (str.charCodeAt(i)) {\n case 34:\n escaped = '"';\n break; // \"\n case 38:\n escaped = '&';\n break; // &\n case 39:\n escaped = ''';\n break; // '\n case 60:\n escaped = '<';\n break; // <\n case 62:\n escaped = '>';\n break; // >\n }\n if (escaped !== undefined) {\n if (lastIndex !== i) {\n result += str.slice(lastIndex, i);\n }\n result += escaped;\n lastIndex = i + 1;\n }\n }\n\n if (lastIndex === 0) return str;\n if (lastIndex < str.length) {\n result += str.slice(lastIndex);\n }\n return result;\n}\n", "// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport type { SpecNode } from '../shared/types';\nimport type { Writable } from 'stream';\nimport { renderToString } from './render-to-string';\n\nexport interface PipeableStream {\n pipe<T extends Writable>(destination: T): T;\n abort(reason?: unknown): void;\n}\n\nexport interface RenderToPipeableStreamOptions {\n identifierPrefix?: string;\n onShellReady?: () => void;\n onShellError?: (error: unknown) => void;\n onAllReady?: () => void;\n onError?: (error: unknown) => void;\n /**\n * Maximum number of bytes to write per chunk.\n * Smaller values allow the event loop to process other work between chunks.\n * Default: 8192 (8KB)\n */\n progressiveChunkSize?: number;\n}\n\n/**\n * Renders a SpecifyJS component tree to a Node.js pipeable stream.\n *\n * **Build-time pre-rendering only.** Intended for build scripts that\n * generate static HTML files, not for runtime server request handlers.\n * Renders the full HTML string, then writes it in chunks to the writable\n * stream for efficient file I/O during static site generation.\n *\n * For dynamic content, use SpecifyJS's client-side rendering with data\n * fetched via HTTPS from API endpoints.\n */\nexport function renderToPipeableStream(\n element: SpecNode,\n options?: RenderToPipeableStreamOptions,\n): PipeableStream {\n let aborted = false;\n\n return {\n pipe<T extends Writable>(destination: T): T {\n if (aborted) {\n destination.end();\n return destination;\n }\n\n let html: string;\n try {\n html = renderToString(element);\n } catch (error) {\n options?.onShellError?.(error);\n options?.onError?.(error);\n destination.end();\n return destination;\n }\n\n options?.onShellReady?.();\n\n const chunkSize = options?.progressiveChunkSize ?? 8192;\n\n if (html.length <= chunkSize) {\n // Small enough to write in one shot\n destination.write(html);\n destination.end();\n options?.onAllReady?.();\n } else {\n // Write in chunks, yielding between each\n let offset = 0;\n\n function writeNextChunk(): void {\n if (aborted || offset >= html.length) {\n destination.end();\n options?.onAllReady?.();\n return;\n }\n\n const chunk = html.slice(offset, offset + chunkSize);\n offset += chunkSize;\n\n const canContinue = destination.write(chunk);\n if (canContinue) {\n // Yield to event loop before next chunk\n setImmediate(writeNextChunk);\n } else {\n /* v8 ignore next 2 -- backpressure path requires slow consumer */\n destination.once('drain', writeNextChunk);\n }\n }\n\n writeNextChunk();\n }\n\n return destination;\n },\n abort(reason?: unknown): void {\n aborted = true;\n options?.onError?.(reason);\n },\n };\n}\n", "// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport type { SpecNode } from '../shared/types';\nimport { renderToString } from './render-to-string';\n\nexport interface RenderToReadableStreamOptions {\n identifierPrefix?: string;\n signal?: AbortSignal;\n onError?: (error: unknown) => void;\n /**\n * Maximum bytes per chunk for progressive flushing.\n * Default: 8192 (8KB)\n */\n progressiveChunkSize?: number;\n}\n\n/**\n * Renders a SpecifyJS tree to a web ReadableStream.\n * **Build-time pre-rendering only.** Intended for build scripts that\n * generate static HTML files, not for runtime server request handlers.\n * Renders the full HTML, then enqueues it in chunks for efficient\n * file I/O during static site generation.\n */\nexport async function renderToReadableStream(\n element: SpecNode,\n options?: RenderToReadableStreamOptions,\n): Promise<ReadableStream<Uint8Array>> {\n const encoder = new TextEncoder();\n const chunkSize = options?.progressiveChunkSize ?? 8192;\n\n return new ReadableStream({\n start(controller) {\n if (options?.signal?.aborted) {\n controller.close();\n return;\n }\n\n let html: string;\n try {\n html = renderToString(element);\n } catch (error) {\n options?.onError?.(error);\n controller.error(error);\n return;\n }\n\n // Enqueue in chunks for progressive streaming\n let offset = 0;\n while (offset < html.length) {\n const chunk = html.slice(offset, offset + chunkSize);\n controller.enqueue(encoder.encode(chunk));\n offset += chunkSize;\n }\n\n controller.close();\n },\n });\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../../../src/server/render-to-string.ts", "../../../src/server/render-to-pipeable-stream.ts", "../../../src/server/render-to-readable-stream.ts"],
|
|
4
|
+
"sourcesContent": ["// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport {\n type SpecNode,\n type SpecElement,\n type Props,\n type FunctionComponent,\n type ClassComponentInstance,\n SPEC_FRAGMENT_TYPE,\n SPEC_STRICT_MODE_TYPE,\n SPEC_PROFILER_TYPE,\n SPEC_FORWARD_REF_TYPE,\n SPEC_MEMO_TYPE,\n SPEC_PROVIDER_TYPE,\n} from '../shared/types';\nimport { isValidElement } from '../core/is-valid-element';\n\n// Self-closing HTML tags\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\n// Map of prop names to HTML attribute names\nconst PROP_TO_ATTR: Record<string, string> = {\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n acceptCharset: 'accept-charset',\n tabIndex: 'tabindex',\n autoFocus: 'autofocus',\n autoComplete: 'autocomplete',\n autoPlay: 'autoplay',\n crossOrigin: 'crossorigin',\n noValidate: 'novalidate',\n formNoValidate: 'formnovalidate',\n readOnly: 'readonly',\n cellPadding: 'cellpadding',\n cellSpacing: 'cellspacing',\n colSpan: 'colspan',\n rowSpan: 'rowspan',\n frameBorder: 'frameborder',\n marginHeight: 'marginheight',\n marginWidth: 'marginwidth',\n};\n\n// Props that should not be rendered as attributes\nconst RESERVED_PROPS = new Set(['children', 'key', 'ref', 'dangerouslySetInnerHTML']);\n\nconst EVENT_RE = /^on[A-Z]/;\n\n/**\n * Renders a SpecifyJS component tree to an HTML string.\n *\n * **Build-time pre-rendering only.** This function is designed for use\n * during the build process (e.g., static site generation, build scripts)\n * to produce HTML files that are served statically. It must NOT be called\n * in server request handlers, middleware, or any runtime code path that\n * responds to HTTP requests.\n *\n * For dynamic content, use SpecifyJS's client-side rendering with data\n * fetched via HTTPS from API endpoints.\n *\n * @throws {Error} If called in a detected server request context\n */\nexport function renderToString(element: SpecNode): string {\n assertNotInRequestContext('renderToString');\n return renderNode(element, true);\n}\n\n/**\n * Renders a SpecifyJS component tree to static HTML (no hydration markers).\n *\n * **Build-time pre-rendering only.** Use in build scripts to generate\n * static HTML pages. Do NOT use in server request handlers.\n *\n * @throws {Error} If called in a detected server request context\n */\nexport function renderToStaticMarkup(element: SpecNode): string {\n assertNotInRequestContext('renderToStaticMarkup');\n return renderNode(element, false);\n}\n\n/**\n * Guard against misuse in server request handlers.\n * Detects common server frameworks (Express, Koa, Fastify, etc.)\n * by checking for telltale global state.\n */\n/* v8 ignore next 22 -- environment detection only triggers in Node.js production */\nfunction assertNotInRequestContext(fnName: string): void {\n if (\n typeof process !== 'undefined' &&\n typeof process.env !== 'undefined' &&\n process.env.SPECIFYJS_ALLOW_PRERENDER === 'true'\n ) {\n return;\n }\n\n if (\n typeof process !== 'undefined' &&\n typeof process.env !== 'undefined' &&\n (process.env.NODE_ENV === 'production' || process.env.PORT)\n ) {\n if (!process.env.SPECIFYJS_ALLOW_PRERENDER) {\n console.warn(\n `[SpecifyJS] ${fnName}() is intended for build-time pre-rendering only, ` +\n `not runtime server-side rendering. Set SPECIFYJS_ALLOW_PRERENDER=true ` +\n `if you are using this in a build script. See: ` +\n `https://github.com/asymmetric-effort/specifyjs/blob/main/docs/api/static-prerendering.md`,\n );\n }\n }\n}\n\nfunction renderNode(node: SpecNode, includeDataAttrs: boolean): string {\n // Null, undefined, boolean \u2192 empty\n if (node == null || typeof node === 'boolean') {\n return '';\n }\n\n // String or number \u2192 escape and return\n if (typeof node === 'string') {\n return escapeHtml(node);\n }\n if (typeof node === 'number') {\n return String(node);\n }\n\n // Array \u2192 render each child (iterative, no recursion for flat arrays)\n if (Array.isArray(node)) {\n let result = '';\n const stack: SpecNode[] = [];\n for (let i = node.length - 1; i >= 0; i--) stack.push(node[i] as SpecNode);\n while (stack.length > 0) {\n const child = stack.pop()!;\n if (child == null || typeof child === 'boolean') continue;\n if (typeof child === 'string') {\n result += escapeHtml(child);\n continue;\n }\n if (typeof child === 'number') {\n result += String(child);\n continue;\n }\n if (Array.isArray(child)) {\n for (let i = child.length - 1; i >= 0; i--) stack.push(child[i] as SpecNode);\n continue;\n }\n if (isValidElement(child)) result += renderElement(child as SpecElement, includeDataAttrs);\n }\n return result;\n }\n\n // Must be an element\n if (!isValidElement(node)) {\n return '';\n }\n\n const element = node as SpecElement;\n return renderElement(element, includeDataAttrs);\n}\n\nfunction renderElement(element: SpecElement, includeDataAttrs: boolean): string {\n const { type, props } = element;\n\n // Fragment, StrictMode, Profiler \u2192 render children only\n if (\n type === SPEC_FRAGMENT_TYPE ||\n type === SPEC_STRICT_MODE_TYPE ||\n type === SPEC_PROFILER_TYPE\n ) {\n return renderNode(props.children, includeDataAttrs);\n }\n\n // Context Provider \u2192 set value and render children\n if (typeof type === 'object' && type !== null) {\n const $$typeof = (type as { $$typeof?: symbol }).$$typeof;\n\n if ($$typeof === SPEC_PROVIDER_TYPE) {\n const context = (type as { _context: { _currentValue: unknown } })._context;\n const prevValue = context._currentValue;\n context._currentValue = props.value;\n const result = renderNode(props.children, includeDataAttrs);\n context._currentValue = prevValue;\n return result;\n }\n\n if ($$typeof === SPEC_FORWARD_REF_TYPE) {\n const render = (type as { render: (props: Props, ref: unknown) => SpecNode }).render;\n const children = render(props, element.ref);\n return renderNode(children, includeDataAttrs);\n }\n\n if ($$typeof === SPEC_MEMO_TYPE) {\n const innerType = (type as { type: FunctionComponent }).type;\n if (typeof innerType === 'function') {\n const children = innerType(props);\n return renderNode(children, includeDataAttrs);\n }\n }\n }\n\n // Function component\n if (typeof type === 'function') {\n if ((type.prototype as Record<string, unknown>)?.isSpecComponent) {\n // Class component\n const Constructor = type as new (props: Props) => ClassComponentInstance;\n const instance = new Constructor(props);\n const children = instance.render();\n return renderNode(children, includeDataAttrs);\n }\n\n // Functional component\n const children = (type as FunctionComponent)(props);\n return renderNode(children, includeDataAttrs);\n }\n\n // Host element (string tag)\n if (typeof type === 'string') {\n return renderHostElement(type, props, includeDataAttrs);\n }\n\n return '';\n}\n\nfunction renderHostElement(tag: string, props: Props, includeDataAttrs: boolean): string {\n let html = `<${tag}`;\n\n // Render attributes\n for (const key in props) {\n if (RESERVED_PROPS.has(key) || EVENT_RE.test(key)) continue;\n\n const value = props[key];\n if (value == null || value === false) continue;\n\n const attrName = PROP_TO_ATTR[key] || key.toLowerCase();\n\n // C-1: Validate attribute names to prevent XSS via attribute name injection\n if (!/^[a-zA-Z_][\\w\\-:.]*$/.test(attrName)) continue;\n\n if (key === 'style') {\n html += ` style=\"${renderStyle(value as Record<string, string | number>)}\"`;\n } else if (key === 'value' || key === 'checked' || key === 'selected') {\n if (value === true) {\n html += ` ${attrName}`;\n } else {\n html += ` ${attrName}=\"${escapeHtml(String(value))}\"`;\n }\n } else if (value === true) {\n html += ` ${attrName}`;\n } else {\n html += ` ${attrName}=\"${escapeHtml(String(value))}\"`;\n }\n }\n\n if (includeDataAttrs) {\n // Mark the root element for hydration\n }\n\n // Self-closing tags\n if (VOID_ELEMENTS.has(tag)) {\n html += '/>';\n return html;\n }\n\n html += '>';\n\n // dangerouslySetInnerHTML\n if (props.dangerouslySetInnerHTML) {\n const innerHtml = (props.dangerouslySetInnerHTML as { __html: string }).__html;\n html += innerHtml;\n } else {\n // Render children\n html += renderNode(props.children, includeDataAttrs);\n }\n\n html += `</${tag}>`;\n return html;\n}\n\nfunction renderStyle(style: Record<string, string | number>): string {\n const parts: string[] = [];\n for (const prop in style) {\n const value = style[prop];\n if (value == null) continue;\n\n // Convert camelCase to kebab-case\n const cssProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n let cssValue =\n typeof value === 'number' && value !== 0 && !isUnitlessProp(prop)\n ? `${value}px`\n : String(value);\n\n // L-6: Sanitize CSS values \u2014 strip dangerous patterns\n cssValue = cssValue\n .replace(/expression\\s*\\(/gi, '')\n .replace(/url\\s*\\(\\s*javascript:/gi, 'url(');\n\n parts.push(`${cssProp}:${cssValue}`);\n }\n return parts.join(';');\n}\n\nconst UNITLESS_PROPS = new Set([\n 'animationIterationCount',\n 'aspectRatio',\n 'borderImageOutset',\n 'borderImageSlice',\n 'borderImageWidth',\n 'boxFlex',\n 'boxFlexGroup',\n 'boxOrdinalGroup',\n 'columnCount',\n 'columns',\n 'flex',\n 'flexGrow',\n 'flexPositive',\n 'flexShrink',\n 'flexNegative',\n 'flexOrder',\n 'gridArea',\n 'gridRow',\n 'gridRowEnd',\n 'gridRowSpan',\n 'gridRowStart',\n 'gridColumn',\n 'gridColumnEnd',\n 'gridColumnSpan',\n 'gridColumnStart',\n 'fontWeight',\n 'lineClamp',\n 'lineHeight',\n 'opacity',\n 'order',\n 'orphans',\n 'tabSize',\n 'widows',\n 'zIndex',\n 'zoom',\n 'fillOpacity',\n 'floodOpacity',\n 'stopOpacity',\n 'strokeDasharray',\n 'strokeDashoffset',\n 'strokeMiterlimit',\n 'strokeOpacity',\n 'strokeWidth',\n]);\n\nfunction isUnitlessProp(prop: string): boolean {\n return UNITLESS_PROPS.has(prop);\n}\n\nfunction escapeHtml(str: string): string {\n let result = '';\n let lastIndex = 0;\n\n for (let i = 0; i < str.length; i++) {\n let escaped: string | undefined;\n switch (str.charCodeAt(i)) {\n case 34:\n escaped = '"';\n break; // \"\n case 38:\n escaped = '&';\n break; // &\n case 39:\n escaped = ''';\n break; // '\n case 60:\n escaped = '<';\n break; // <\n case 62:\n escaped = '>';\n break; // >\n }\n if (escaped !== undefined) {\n if (lastIndex !== i) {\n result += str.slice(lastIndex, i);\n }\n result += escaped;\n lastIndex = i + 1;\n }\n }\n\n if (lastIndex === 0) return str;\n if (lastIndex < str.length) {\n result += str.slice(lastIndex);\n }\n return result;\n}\n", "// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport type { SpecNode } from '../shared/types';\nimport type { Writable } from 'stream';\nimport { renderToString } from './render-to-string';\n\nexport interface PipeableStream {\n pipe<T extends Writable>(destination: T): T;\n abort(reason?: unknown): void;\n}\n\nexport interface RenderToPipeableStreamOptions {\n identifierPrefix?: string;\n onShellReady?: () => void;\n onShellError?: (error: unknown) => void;\n onAllReady?: () => void;\n onError?: (error: unknown) => void;\n /**\n * Maximum number of bytes to write per chunk.\n * Smaller values allow the event loop to process other work between chunks.\n * Default: 8192 (8KB)\n */\n progressiveChunkSize?: number;\n}\n\n/**\n * Renders a SpecifyJS component tree to a Node.js pipeable stream.\n *\n * **Build-time pre-rendering only.** Intended for build scripts that\n * generate static HTML files, not for runtime server request handlers.\n * Renders the full HTML string, then writes it in chunks to the writable\n * stream for efficient file I/O during static site generation.\n *\n * For dynamic content, use SpecifyJS's client-side rendering with data\n * fetched via HTTPS from API endpoints.\n */\nexport function renderToPipeableStream(\n element: SpecNode,\n options?: RenderToPipeableStreamOptions,\n): PipeableStream {\n let aborted = false;\n\n return {\n pipe<T extends Writable>(destination: T): T {\n if (aborted) {\n destination.end();\n return destination;\n }\n\n let html: string;\n try {\n html = renderToString(element);\n } catch (error) {\n options?.onShellError?.(error);\n options?.onError?.(error);\n destination.end();\n return destination;\n }\n\n options?.onShellReady?.();\n\n const chunkSize = options?.progressiveChunkSize ?? 8192;\n\n if (html.length <= chunkSize) {\n // Small enough to write in one shot\n destination.write(html);\n destination.end();\n options?.onAllReady?.();\n } else {\n // Write in chunks, yielding between each\n let offset = 0;\n\n function writeNextChunk(): void {\n if (aborted || offset >= html.length) {\n destination.end();\n options?.onAllReady?.();\n return;\n }\n\n const chunk = html.slice(offset, offset + chunkSize);\n offset += chunkSize;\n\n const canContinue = destination.write(chunk);\n if (canContinue) {\n // Yield to event loop before next chunk\n setImmediate(writeNextChunk);\n } else {\n /* v8 ignore next 2 -- backpressure path requires slow consumer */\n destination.once('drain', writeNextChunk);\n }\n }\n\n writeNextChunk();\n }\n\n return destination;\n },\n abort(reason?: unknown): void {\n aborted = true;\n options?.onError?.(reason);\n },\n };\n}\n", "// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport type { SpecNode } from '../shared/types';\nimport { renderToString } from './render-to-string';\n\nexport interface RenderToReadableStreamOptions {\n identifierPrefix?: string;\n signal?: AbortSignal;\n onError?: (error: unknown) => void;\n /**\n * Maximum bytes per chunk for progressive flushing.\n * Default: 8192 (8KB)\n */\n progressiveChunkSize?: number;\n}\n\n/**\n * Renders a SpecifyJS tree to a web ReadableStream.\n * **Build-time pre-rendering only.** Intended for build scripts that\n * generate static HTML files, not for runtime server request handlers.\n * Renders the full HTML, then enqueues it in chunks for efficient\n * file I/O during static site generation.\n */\nexport async function renderToReadableStream(\n element: SpecNode,\n options?: RenderToReadableStreamOptions,\n): Promise<ReadableStream<Uint8Array>> {\n const encoder = new TextEncoder();\n const chunkSize = options?.progressiveChunkSize ?? 8192;\n\n return new ReadableStream({\n start(controller) {\n if (options?.signal?.aborted) {\n controller.close();\n return;\n }\n\n let html: string;\n try {\n html = renderToString(element);\n } catch (error) {\n options?.onError?.(error);\n controller.error(error);\n return;\n }\n\n // Enqueue in chunks for progressive streaming\n let offset = 0;\n while (offset < html.length) {\n const chunk = html.slice(offset, offset + chunkSize);\n controller.enqueue(encoder.encode(chunk));\n offset += chunkSize;\n }\n\n controller.close();\n },\n });\n}\n"],
|
|
5
|
+
"mappings": ";kKAmBA,IAAMA,EAAgB,IAAI,IAAI,CAC5B,OACA,OACA,KACA,MACA,QACA,KACA,MACA,QACA,OACA,OACA,QACA,SACA,QACA,KACF,CAAC,EAGKC,EAAuC,CAC3C,UAAW,QACX,QAAS,MACT,UAAW,aACX,cAAe,iBACf,SAAU,WACV,UAAW,YACX,aAAc,eACd,SAAU,WACV,YAAa,cACb,WAAY,aACZ,eAAgB,iBAChB,SAAU,WACV,YAAa,cACb,YAAa,cACb,QAAS,UACT,QAAS,UACT,YAAa,cACb,aAAc,eACd,YAAa,aACf,EAGMC,EAAiB,IAAI,IAAI,CAAC,WAAY,MAAO,MAAO,yBAAyB,CAAC,EAE9EC,EAAW,WAgBV,SAASC,EAAeC,EAA2B,CACxD,OAAAC,EAA0B,gBAAgB,EACnCC,EAAWF,EAAS,EAAI,CACjC,CAUO,SAASG,EAAqBH,EAA2B,CAC9D,OAAAC,EAA0B,sBAAsB,EACzCC,EAAWF,EAAS,EAAK,CAClC,CAQA,SAASC,EAA0BG,EAAsB,CAErD,OAAO,QAAY,KACnB,OAAO,QAAQ,IAAQ,KACvB,QAAQ,IAAI,4BAA8B,QAM1C,OAAO,QAAY,KACnB,OAAO,QAAQ,IAAQ,MAGlB,QAAQ,IAAI,2BACf,QAAQ,KACN,eAAeA,CAAM,gQAIvB,EAGN,CAEA,SAASF,EAAWG,EAAgBC,EAAmC,CAErE,GAAID,GAAQ,MAAQ,OAAOA,GAAS,UAClC,MAAO,GAIT,GAAI,OAAOA,GAAS,SAClB,OAAOE,EAAWF,CAAI,EAExB,GAAI,OAAOA,GAAS,S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AU,GACVD,GAAS,UAAUU,CAAM,CAC3B,CACF,CACF,CC/EA,eAAsBC,EACpBC,EACAC,EACqC,CACrC,IAAMC,EAAU,IAAI,YACdC,EAAYF,GAAS,sBAAwB,KAEnD,OAAO,IAAI,eAAe,CACxB,MAAMG,EAAY,CAChB,GAAIH,GAAS,QAAQ,QAAS,CAC5BG,EAAW,MAAM,EACjB,MACF,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAOC,EAAeN,CAAO,CAC/B,OAASO,EAAO,CACdN,GAAS,UAAUM,CAAK,EACxBH,EAAW,MAAMG,CAAK,EACtB,MACF,CAGA,IAAIC,EAAS,EACb,KAAOA,EAASH,EAAK,QAAQ,CAC3B,IAAMI,EAAQJ,EAAK,MAAMG,EAAQA,EAASL,CAAS,EACnDC,EAAW,QAAQF,EAAQ,OAAOO,CAAK,CAAC,EACxCD,GAAUL,CACZ,CAEAC,EAAW,MAAM,CACnB,CACF,CAAC,CACH",
|
|
6
|
+
"names": ["VOID_ELEMENTS", "PROP_TO_ATTR", "RESERVED_PROPS", "EVENT_RE", "renderToString", "element", "assertNotInRequestContext", "renderNode", "renderToStaticMarkup", "fnName", "node", "includeDataAttrs", "escapeHtml", "result", "stack", "i", "child", "isValidElement", "renderElement", "type", "props", "SPEC_FRAGMENT_TYPE", "SPEC_STRICT_MODE_TYPE", "SPEC_PROFILER_TYPE", "$$typeof", "SPEC_PROVIDER_TYPE", "context", "prevValue", "SPEC_FORWARD_REF_TYPE", "render", "children", "SPEC_MEMO_TYPE", "innerType", "Constructor", "renderHostElement", "tag", "html", "key", "value", "attrName", "renderStyle", "innerHtml", "style", "parts", "prop", "cssProp", "m", "cssValue", "isUnitlessProp", "UNITLESS_PROPS", "str", "lastIndex", "escaped", "renderToPipeableStream", "element", "options", "aborted", "destination", "html", "renderToString", "error", "chunkSize", "writeNextChunk", "offset", "chunk", "reason", "renderToReadableStream", "element", "options", "encoder", "chunkSize", "controller", "html", "renderToString", "error", "offset", "chunk"]
|
|
7
7
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE */
|
|
2
|
-
|
|
3
|
-
//# sourceMappingURL=
|
|
2
|
+
import{a as v,b as x,c as b,d as k}from"./esm/chunks/chunk-3SXNLMCH.js";import"./esm/chunks/chunk-TVDAY42P.js";import{d as l,i as m}from"./esm/chunks/chunk-MCXU6QF3.js";import"./esm/chunks/chunk-ZDPD2MPQ.js";function I(e){let n=new Uint8Array(e);try{crypto.getRandomValues(n)}catch{for(let t=0;t<e;t++)n[t]=Math.floor(Math.random()*256)}return n}function T(e){let n="";for(let t=0;t<e.length;t++)n+=(e[t]??0).toString(16).padStart(2,"0");return n}function g(){return T(I(16))}function y(){return T(I(8))}var w=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function R(e){let n=w.exec(e.trim());if(!n)return null;let t=n[2],a=n[3],s=n[4];return/^0+$/.test(t)||/^0+$/.test(a)?null:{traceId:t,spanId:a,traceFlags:s}}function E(e){return`00-${e.traceId}-${e.spanId}-${e.traceFlags}`}function h(e,n){return{traceId:n?.traceId??g(),spanId:y(),parentSpanId:n?.parentSpanId,name:e,kind:n?.kind??"internal",startTime:performance.now(),status:{code:"unset"},attributes:n?.attributes?{...n.attributes}:{},events:[]}}function c(e){e.endTime=performance.now()}function C(e){let n=e.batchSize??1e3,t=[],a=[];function s(r){a.length>=n&&a.splice(0,Math.floor(n/2)),a.push(r)}let d;e.flushInterval&&e.flushInterval>0&&(d=setInterval(()=>{f.flush()},e.flushInterval),typeof d=="object"&&"unref"in d&&d.unref());let f={config:e,get pendingSpans(){return a},activeSpan(){return t.length>0?t[t.length-1]:void 0},startSpan(r,i){let u=f.activeSpan(),p=h(r,{kind:i?.kind,attributes:i?.attributes,traceId:i?.traceId??u?.traceId,parentSpanId:i?.parentSpanId??u?.spanId});return t.push(p),p},withSpan(r,i){t.includes(r)||t.push(r);let p=()=>{for(let o=t.length-1;o>=0;o--)t[o]===r&&t.splice(o,1)};try{let o=i();return o&&typeof o.then=="function"?o.then(S=>(c(r),s(r),p(),S),S=>{throw r.status={code:"error",message:String(S)},c(r),s(r),p(),S}):(c(r),s(r),p(),o)}catch(o){throw r.status={code:"error",message:String(o)},c(r),s(r),p(),o}},async flush(){if(a.length===0)return;let r=a.splice(0,a.length);if(e.endpoint){let{formatOtlpTraces:i,exportToEndpoint:u}=await import("../chunks/metrics-56RIK7JQ.js"),p=i(r,e.serviceName,e.serviceVersion);await u(e.endpoint,e.headers??{},p)}}};return f}function O(e,n){let t=m(null);l(()=>{let a=e.startSpan(n,{kind:"internal"});return a.events.push({name:"mount",timestamp:performance.now()}),t.current=a,()=>{t.current&&(t.current.events.push({name:"unmount",timestamp:performance.now()}),c(t.current))}},[])}export{v as createMeterProvider,C as createTracer,c as endSpan,k as exportToEndpoint,x as formatOtlpMetrics,b as formatOtlpTraces,E as formatTraceparent,y as generateSpanId,g as generateTraceId,R as parseTraceparent,h as startSpan,O as useTracing};
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["
|
|
4
|
-
"sourcesContent": ["// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\n/**\n * Secure fetch wrapper \u2014 enforces HTTPS-only policy.\n *\n * SpecifyJS prohibits HTTP connections. All network requests must use\n * HTTPS or be relative URLs. This prevents data from being transmitted\n * in plaintext, protecting against eavesdropping and MITM attacks.\n *\n * Exceptions:\n * - Relative URLs (./path, /path) \u2014 resolved by the browser\n * - localhost and 127.0.0.1 \u2014 development only\n */\n\n/**\n * Validate that a URL uses HTTPS or is a relative/localhost URL.\n * Throws if the URL uses plaintext HTTP.\n */\nexport function assertSecureUrl(url: string): void {\n // Block protocol-relative URLs (//evil.com) \u2014 they inherit the page's protocol\n if (url.startsWith('//')) {\n throw new Error(\n `[SpecifyJS] Protocol-relative URL rejected: \"${url}\". ` + `Use an explicit https:// prefix.`,\n );\n }\n\n // Relative URLs are always allowed\n if (url.startsWith('/') || url.startsWith('./') || url.startsWith('../')) {\n return;\n }\n\n // Data URLs are allowed\n if (url.startsWith('data:')) {\n return;\n }\n\n // Parse absolute URLs\n let parsed: URL;\n try {\n parsed = new URL(url, typeof window !== 'undefined' ? window.location.href : undefined);\n } catch {\n /* v8 ignore next 2 -- URL parse failure is environment-specific; jsdom always provides a base */\n return;\n }\n\n // Allow HTTPS\n if (parsed.protocol === 'https:') {\n return;\n }\n\n // Allow localhost/127.0.0.1 for development (any protocol)\n if (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1') {\n return;\n }\n\n // Reject HTTP and other insecure protocols\n throw new Error(\n `[SpecifyJS] Insecure URL rejected: \"${url}\". ` +\n `SpecifyJS enforces HTTPS-only for all network requests. ` +\n `Use https:// or a relative URL. ` +\n `Localhost URLs are allowed for development.`,\n );\n}\n\n/**\n * Secure fetch \u2014 drop-in replacement for window.fetch that enforces HTTPS.\n * Use this instead of fetch() directly to comply with the HTTPS-only policy.\n */\nexport function secureFetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n assertSecureUrl(url);\n return fetch(input, init);\n}\n", "// ============================================================================\n// SpecifyJS Telemetry \u2014 Metrics (OpenTelemetry-compatible)\n// Zero third-party dependencies \u2014 OTEL protocols implemented from scratch.\n// ============================================================================\n// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport type { Span } from './tracing';\nimport { assertSecureUrl } from '../shared/secure-fetch';\n\n// ---------------------------------------------------------------------------\n// Metric data points\n// ---------------------------------------------------------------------------\n\nexport interface DataPoint {\n value: number;\n attributes: Record<string, string | number | boolean>;\n timestamp: number;\n}\n\n// ---------------------------------------------------------------------------\n// Instruments\n// ---------------------------------------------------------------------------\n\nexport interface Counter {\n readonly name: string;\n readonly description: string;\n /** Monotonically increment the counter. */\n add(value: number, attributes?: Record<string, string | number | boolean>): void;\n /** Read-only snapshot of data points. */\n readonly dataPoints: ReadonlyArray<DataPoint>;\n}\n\nexport interface Histogram {\n readonly name: string;\n readonly description: string;\n /** Record a measurement. */\n record(value: number, attributes?: Record<string, string | number | boolean>): void;\n /** Read-only snapshot of data points. */\n readonly dataPoints: ReadonlyArray<DataPoint>;\n}\n\nexport interface Gauge {\n readonly name: string;\n readonly description: string;\n /** Set the current value. */\n set(value: number, attributes?: Record<string, string | number | boolean>): void;\n /** Read-only snapshot of data points. */\n readonly dataPoints: ReadonlyArray<DataPoint>;\n}\n\nexport type Instrument = Counter | Histogram | Gauge;\n\nexport interface InstrumentOptions {\n description?: string;\n unit?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Instrument factories (internal)\n// ---------------------------------------------------------------------------\n\nconst MAX_DATA_POINTS = 10000;\n\nfunction addDataPoint(\n points: DataPoint[],\n value: number,\n attributes?: Record<string, string | number | boolean>,\n): void {\n if (points.length >= MAX_DATA_POINTS) {\n points.splice(0, Math.floor(MAX_DATA_POINTS / 2));\n }\n points.push({\n value,\n attributes: attributes ? { ...attributes } : {},\n timestamp: performance.now(),\n });\n}\n\nfunction createCounter(name: string, opts?: InstrumentOptions): Counter {\n const points: DataPoint[] = [];\n return {\n name,\n description: opts?.description ?? '',\n add(value: number, attributes?: Record<string, string | number | boolean>): void {\n if (value < 0) return; // counters are monotonic\n addDataPoint(points, value, attributes);\n },\n get dataPoints(): ReadonlyArray<DataPoint> {\n return points;\n },\n };\n}\n\nfunction createHistogram(name: string, opts?: InstrumentOptions): Histogram {\n const points: DataPoint[] = [];\n return {\n name,\n description: opts?.description ?? '',\n record(value: number, attributes?: Record<string, string | number | boolean>): void {\n addDataPoint(points, value, attributes);\n },\n get dataPoints(): ReadonlyArray<DataPoint> {\n return points;\n },\n };\n}\n\nfunction createGauge(name: string, opts?: InstrumentOptions): Gauge {\n const points: DataPoint[] = [];\n return {\n name,\n description: opts?.description ?? '',\n set(value: number, attributes?: Record<string, string | number | boolean>): void {\n addDataPoint(points, value, attributes);\n },\n get dataPoints(): ReadonlyArray<DataPoint> {\n return points;\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// MeterProvider\n// ---------------------------------------------------------------------------\n\nexport interface MeterProviderConfig {\n serviceName: string;\n endpoint?: string;\n headers?: Record<string, string>;\n exportInterval?: number;\n}\n\nexport interface MeterProvider {\n counter(name: string, opts?: InstrumentOptions): Counter;\n histogram(name: string, opts?: InstrumentOptions): Histogram;\n gauge(name: string, opts?: InstrumentOptions): Gauge;\n /** Export all instrument data to the configured endpoint. */\n flush(): Promise<void>;\n /** Read-only access to all registered instruments. */\n readonly instruments: ReadonlyArray<Instrument>;\n readonly config: Readonly<MeterProviderConfig>;\n}\n\nexport function createMeterProvider(config: MeterProviderConfig): MeterProvider {\n const instruments: Instrument[] = [];\n\n let exportTimer: ReturnType<typeof setInterval> | undefined;\n /* v8 ignore start -- timer setup requires real interval environment */\n if (config.exportInterval && config.exportInterval > 0) {\n exportTimer = setInterval(() => {\n void provider.flush();\n }, config.exportInterval);\n if (typeof exportTimer === 'object' && 'unref' in exportTimer) {\n (exportTimer as { unref: () => void }).unref();\n }\n }\n /* v8 ignore stop */\n\n const provider: MeterProvider = {\n config,\n\n get instruments(): ReadonlyArray<Instrument> {\n return instruments;\n },\n\n counter(name: string, opts?: InstrumentOptions): Counter {\n const c = createCounter(name, opts);\n instruments.push(c);\n return c;\n },\n\n histogram(name: string, opts?: InstrumentOptions): Histogram {\n const h = createHistogram(name, opts);\n instruments.push(h);\n return h;\n },\n\n gauge(name: string, opts?: InstrumentOptions): Gauge {\n const g = createGauge(name, opts);\n instruments.push(g);\n return g;\n },\n\n async flush(): Promise<void> {\n if (!config.endpoint) return;\n\n const body = formatOtlpMetrics(instruments, config.serviceName);\n await exportToEndpoint(config.endpoint, config.headers ?? {}, body);\n },\n };\n\n return provider;\n}\n\n// ---------------------------------------------------------------------------\n// OTLP JSON export helpers\n// ---------------------------------------------------------------------------\n\n/** Attributes to the OTLP key-value array format. */\nfunction toOtlpAttributes(\n attrs: Record<string, string | number | boolean>,\n): Array<{ key: string; value: { stringValue?: string; intValue?: number; boolValue?: boolean } }> {\n return Object.entries(attrs).map(([key, val]) => {\n if (typeof val === 'string') return { key, value: { stringValue: val } };\n if (typeof val === 'boolean') return { key, value: { boolValue: val } };\n return { key, value: { intValue: val } };\n });\n}\n\n/** Convert a `performance.now()` timestamp to nanoseconds (OTLP convention). */\nfunction toNanos(ms: number): string {\n return String(Math.round(ms * 1_000_000));\n}\n\n/**\n * Build an OTLP-compatible JSON payload for metrics.\n *\n * Structure follows the OTLP/HTTP JSON proto mapping:\n * https://opentelemetry.io/docs/specs/otlp/#otlphttp\n */\nexport function formatOtlpMetrics(\n instruments: ReadonlyArray<Instrument>,\n serviceName?: string,\n): Record<string, unknown> {\n const metrics = instruments.map((inst) => {\n const dataPoints = inst.dataPoints.map((dp) => ({\n attributes: toOtlpAttributes(dp.attributes),\n timeUnixNano: toNanos(dp.timestamp),\n asDouble: dp.value,\n }));\n\n // Determine metric type heuristic: counters have `add`, histograms have\n // `record`, gauges have `set`.\n let metricData: Record<string, unknown>;\n if ('add' in inst) {\n metricData = { sum: { dataPoints, isMonotonic: true, aggregationTemporality: 2 } };\n } else if ('record' in inst) {\n metricData = { histogram: { dataPoints, aggregationTemporality: 2 } };\n } else {\n metricData = { gauge: { dataPoints } };\n }\n\n return {\n name: inst.name,\n description: inst.description,\n ...metricData,\n };\n });\n\n return {\n resourceMetrics: [\n {\n resource: {\n attributes: toOtlpAttributes({\n 'service.name': serviceName ?? 'unknown',\n }),\n },\n scopeMetrics: [\n {\n scope: { name: 'specifyjs-telemetry', version: '1.0.0' },\n metrics,\n },\n ],\n },\n ],\n };\n}\n\n/**\n * Build an OTLP-compatible JSON payload for traces/spans.\n */\nexport function formatOtlpTraces(\n spans: ReadonlyArray<Span>,\n serviceName?: string,\n serviceVersion?: string,\n): Record<string, unknown> {\n const resourceAttrs: Record<string, string> = {\n 'service.name': serviceName ?? 'unknown',\n };\n if (serviceVersion) {\n resourceAttrs['service.version'] = serviceVersion;\n }\n\n const SPAN_KIND_MAP: Record<string, number> = {\n internal: 1,\n server: 2,\n client: 3,\n producer: 4,\n consumer: 5,\n };\n\n const STATUS_CODE_MAP: Record<string, number> = {\n unset: 0,\n ok: 1,\n error: 2,\n };\n\n const otlpSpans = spans.map((s) => ({\n traceId: s.traceId,\n spanId: s.spanId,\n parentSpanId: s.parentSpanId ?? '',\n name: s.name,\n kind: SPAN_KIND_MAP[s.kind] ?? 1,\n startTimeUnixNano: toNanos(s.startTime),\n endTimeUnixNano: s.endTime !== undefined ? toNanos(s.endTime) : '0',\n attributes: toOtlpAttributes(s.attributes),\n status: {\n code: STATUS_CODE_MAP[s.status.code] ?? 0,\n message: s.status.message ?? '',\n },\n events: s.events.map((e) => ({\n name: e.name,\n timeUnixNano: toNanos(e.timestamp),\n attributes: e.attributes ? toOtlpAttributes(e.attributes) : [],\n })),\n }));\n\n return {\n resourceSpans: [\n {\n resource: {\n attributes: toOtlpAttributes(resourceAttrs),\n },\n scopeSpans: [\n {\n scope: { name: 'specifyjs-telemetry', version: '1.0.0' },\n spans: otlpSpans,\n },\n ],\n },\n ],\n };\n}\n\n/**\n * Send a JSON payload to an OTLP-compatible endpoint via `fetch`.\n */\nexport async function exportToEndpoint(\n url: string,\n headers: Record<string, string>,\n body: Record<string, unknown>,\n): Promise<void> {\n try {\n assertSecureUrl(url);\n await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(body),\n });\n } catch {\n // Telemetry export failures are silently ignored so they never break\n // application code.\n }\n}\n", "// ============================================================================\n// SpecifyJS Hooks\n// ============================================================================\n// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport type { SpecContext } from '../shared/types';\n\n// Internal: the currently rendering fiber sets these\ntype Dispatcher = {\n useState: typeof useState;\n useEffect: typeof useEffect;\n useContext: typeof useContext;\n useReducer: typeof useReducer;\n useCallback: typeof useCallback;\n useMemo: typeof useMemo;\n useRef: typeof useRef;\n useImperativeHandle: typeof useImperativeHandle;\n useLayoutEffect: typeof useLayoutEffect;\n useDebugValue: typeof useDebugValue;\n useId: typeof useId;\n useDeferredValue: typeof useDeferredValue;\n useTransition: typeof useTransition;\n useSyncExternalStore: typeof useSyncExternalStore;\n useInsertionEffect: typeof useInsertionEffect;\n};\n\nlet currentDispatcher: Dispatcher | null = null;\n\nexport function __setDispatcher(dispatcher: Dispatcher | null): void {\n currentDispatcher = dispatcher;\n}\n\nexport function __getDispatcher(): Dispatcher | null {\n return currentDispatcher;\n}\n\nfunction resolveDispatcher(): Dispatcher {\n if (currentDispatcher === null) {\n throw new Error(\n 'Invalid hook call. Hooks can only be called inside the body of a function component.',\n );\n }\n return currentDispatcher;\n}\n\nexport function useState<T>(\n initialState: T | (() => T),\n): [T, (action: T | ((prev: T) => T)) => void] {\n return resolveDispatcher().useState(initialState);\n}\n\nexport function useEffect(create: () => void | (() => void), deps?: readonly unknown[]): void {\n return resolveDispatcher().useEffect(create, deps);\n}\n\nexport function useContext<T>(context: SpecContext<T>): T {\n return resolveDispatcher().useContext(context);\n}\n\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialArg: S,\n init?: (arg: S) => S,\n): [S, (action: A) => void] {\n return resolveDispatcher().useReducer(reducer, initialArg, init);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useCallback<T extends (...args: any[]) => any>(\n callback: T,\n deps: readonly unknown[],\n): T {\n return resolveDispatcher().useCallback(callback, deps);\n}\n\nexport function useMemo<T>(factory: () => T, deps: readonly unknown[]): T {\n return resolveDispatcher().useMemo(factory, deps);\n}\n\nexport function useRef<T>(initialValue: T): { current: T };\nexport function useRef<T>(initialValue: T | null): { current: T | null };\nexport function useRef<T>(): { current: T | undefined };\nexport function useRef<T>(initialValue?: T): { current: T | undefined } {\n return resolveDispatcher().useRef(initialValue);\n}\n\nexport function useImperativeHandle<T>(\n ref: { current: T | null } | ((instance: T | null) => void) | null,\n createHandle: () => T,\n deps?: readonly unknown[],\n): void {\n return resolveDispatcher().useImperativeHandle(ref, createHandle, deps);\n}\n\nexport function useLayoutEffect(\n create: () => void | (() => void),\n deps?: readonly unknown[],\n): void {\n return resolveDispatcher().useLayoutEffect(create, deps);\n}\n\nexport function useDebugValue<T>(value: T, format?: (value: T) => unknown): void {\n return resolveDispatcher().useDebugValue(value, format);\n}\n\nexport function useId(): string {\n return resolveDispatcher().useId();\n}\n\nexport function useDeferredValue<T>(value: T): T {\n return resolveDispatcher().useDeferredValue(value);\n}\n\nexport function useTransition(): [boolean, (callback: () => void) => void] {\n return resolveDispatcher().useTransition();\n}\n\nexport function useSyncExternalStore<T>(\n subscribe: (onStoreChange: () => void) => () => void,\n getSnapshot: () => T,\n getServerSnapshot?: () => T,\n): T {\n return resolveDispatcher().useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\nexport function useInsertionEffect(\n create: () => void | (() => void),\n deps?: readonly unknown[],\n): void {\n return resolveDispatcher().useInsertionEffect(create, deps);\n}\n\n// Custom hooks (not dispatcher-based)\nexport { useHead } from './use-head';\nexport type { HeadMeta, HeadHttpEquiv } from './use-head';\n", "// ============================================================================\n// SpecifyJS Telemetry \u2014 Distributed Tracing (OpenTelemetry-compatible)\n// Zero third-party dependencies \u2014 OTEL protocols implemented from scratch.\n// ============================================================================\n// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport { useEffect, useRef } from '../hooks/index';\n\n// ---------------------------------------------------------------------------\n// Trace Context \u2014 W3C Trace Context propagation\n// ---------------------------------------------------------------------------\n\n/** 16-byte (32 hex char) trace identifier. */\nexport type TraceId = string;\n\n/** 8-byte (16 hex char) span identifier. */\nexport type SpanId = string;\n\n/** W3C Trace Context carrier. */\nexport interface TraceContext {\n traceId: TraceId;\n spanId: SpanId;\n traceFlags: string;\n parentSpanId?: SpanId;\n}\n\n// -- ID generation ----------------------------------------------------------\n\nfunction randomBytes(length: number): Uint8Array {\n const buf = new Uint8Array(length);\n try {\n // Works in browsers and Node >=15 (globalThis.crypto)\n crypto.getRandomValues(buf);\n } catch {\n /* v8 ignore next 3 -- fallback for environments without Web Crypto */\n for (let i = 0; i < length; i++) {\n buf[i] = Math.floor(Math.random() * 256);\n }\n }\n return buf;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += (bytes[i] ?? 0).toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/** Generate a 32-hex-char trace ID (16 random bytes). */\nexport function generateTraceId(): TraceId {\n return bytesToHex(randomBytes(16));\n}\n\n/** Generate a 16-hex-char span ID (8 random bytes). */\nexport function generateSpanId(): SpanId {\n return bytesToHex(randomBytes(8));\n}\n\n// -- W3C traceparent parsing / formatting -----------------------------------\n\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\n/**\n * Parse a W3C `traceparent` header.\n *\n * Format: `{version}-{traceId}-{spanId}-{traceFlags}`\n * Returns `null` when the header is invalid.\n */\nexport function parseTraceparent(header: string): TraceContext | null {\n const match = TRACEPARENT_RE.exec(header.trim());\n if (!match) return null;\n\n const traceId = match[2]!;\n const spanId = match[3]!;\n const traceFlags = match[4]!;\n\n // All-zero trace/span IDs are invalid per the spec.\n if (/^0+$/.test(traceId) || /^0+$/.test(spanId)) return null;\n\n return { traceId, spanId, traceFlags };\n}\n\n/**\n * Format a {@link TraceContext} as a W3C `traceparent` header string.\n *\n * Output: `00-{traceId}-{spanId}-{traceFlags}`\n */\nexport function formatTraceparent(ctx: TraceContext): string {\n return `00-${ctx.traceId}-${ctx.spanId}-${ctx.traceFlags}`;\n}\n\n// ---------------------------------------------------------------------------\n// Spans\n// ---------------------------------------------------------------------------\n\nexport type SpanKind = 'internal' | 'server' | 'client' | 'producer' | 'consumer';\n\nexport interface SpanStatus {\n code: 'unset' | 'ok' | 'error';\n message?: string;\n}\n\nexport interface SpanEvent {\n name: string;\n timestamp: number;\n attributes?: Record<string, string | number | boolean>;\n}\n\nexport interface Span {\n traceId: TraceId;\n spanId: SpanId;\n parentSpanId?: SpanId;\n name: string;\n kind: SpanKind;\n startTime: number;\n endTime?: number;\n status: SpanStatus;\n attributes: Record<string, string | number | boolean>;\n events: SpanEvent[];\n}\n\nexport interface StartSpanOptions {\n kind?: SpanKind;\n parentSpanId?: SpanId;\n traceId?: TraceId;\n attributes?: Record<string, string | number | boolean>;\n}\n\n/**\n * Create and start a new span. The span is **not** automatically associated\n * with a tracer \u2014 use {@link Tracer.startSpan} for automatic parent tracking.\n */\nexport function startSpan(name: string, opts?: StartSpanOptions): Span {\n return {\n traceId: opts?.traceId ?? generateTraceId(),\n spanId: generateSpanId(),\n parentSpanId: opts?.parentSpanId,\n name,\n kind: opts?.kind ?? 'internal',\n startTime: performance.now(),\n status: { code: 'unset' },\n attributes: opts?.attributes ? { ...opts.attributes } : {},\n events: [],\n };\n}\n\n/** End a span by recording its end time. */\nexport function endSpan(span: Span): void {\n span.endTime = performance.now();\n}\n\n// ---------------------------------------------------------------------------\n// Tracer\n// ---------------------------------------------------------------------------\n\nexport interface TracerConfig {\n serviceName: string;\n serviceVersion?: string;\n endpoint?: string;\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n}\n\nexport interface Tracer {\n /** Create a span, automatically parented to the current active span. */\n startSpan(name: string, opts?: StartSpanOptions): Span;\n\n /**\n * Execute `fn` with `span` as the active span. The span is automatically\n * ended when `fn` completes (sync or async). The previous active span is\n * restored afterward.\n */\n withSpan<T>(span: Span, fn: () => T): T;\n\n /** Export all pending (buffered) spans to the configured endpoint. */\n flush(): Promise<void>;\n\n /** Access the currently-active span (top of the span stack), or `undefined`. */\n activeSpan(): Span | undefined;\n\n /** Read-only view of the pending span buffer. */\n readonly pendingSpans: ReadonlyArray<Span>;\n\n /** Tracer configuration. */\n readonly config: Readonly<TracerConfig>;\n}\n\nexport function createTracer(config: TracerConfig): Tracer {\n const MAX_BUFFER_SIZE = config.batchSize ?? 1000;\n const spanStack: Span[] = [];\n const buffer: Span[] = [];\n\n function bufferSpan(span: Span): void {\n if (buffer.length >= MAX_BUFFER_SIZE) {\n buffer.splice(0, Math.floor(MAX_BUFFER_SIZE / 2)); // drop oldest half\n }\n buffer.push(span);\n }\n\n // Auto-flush timer (if configured)\n let flushTimer: ReturnType<typeof setInterval> | undefined;\n if (config.flushInterval && config.flushInterval > 0) {\n flushTimer = setInterval(() => {\n void tracer.flush();\n }, config.flushInterval);\n // Allow the process to exit even if the timer is running (Node.js).\n if (typeof flushTimer === 'object' && 'unref' in flushTimer) {\n (flushTimer as { unref: () => void }).unref();\n }\n }\n\n const tracer: Tracer = {\n config,\n\n get pendingSpans(): ReadonlyArray<Span> {\n return buffer;\n },\n\n activeSpan(): Span | undefined {\n return spanStack.length > 0 ? spanStack[spanStack.length - 1] : undefined;\n },\n\n startSpan(name: string, opts?: StartSpanOptions): Span {\n const active = tracer.activeSpan();\n const span = startSpan(name, {\n kind: opts?.kind,\n attributes: opts?.attributes,\n traceId: opts?.traceId ?? active?.traceId,\n parentSpanId: opts?.parentSpanId ?? active?.spanId,\n });\n spanStack.push(span);\n return span;\n },\n\n withSpan<T>(span: Span, fn: () => T): T {\n // Only push if not already on the stack (startSpan may have pushed it).\n const alreadyOnStack = spanStack.includes(span);\n if (!alreadyOnStack) {\n spanStack.push(span);\n }\n\n const removeFromStack = (): void => {\n // Remove ALL occurrences of the span from the stack.\n for (let i = spanStack.length - 1; i >= 0; i--) {\n if (spanStack[i] === span) {\n spanStack.splice(i, 1);\n }\n }\n };\n\n try {\n const result = fn();\n // Handle thenables (Promises) without importing anything.\n if (result && typeof (result as unknown as Promise<unknown>).then === 'function') {\n return (result as unknown as Promise<unknown>).then(\n (value) => {\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n return value;\n },\n (err) => {\n span.status = { code: 'error', message: String(err) };\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n throw err;\n },\n ) as unknown as T;\n }\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n return result;\n } catch (err) {\n span.status = { code: 'error', message: String(err) };\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n throw err;\n }\n },\n\n async flush(): Promise<void> {\n if (buffer.length === 0) return;\n\n const toExport = buffer.splice(0, buffer.length);\n\n if (config.endpoint) {\n // Lazy-import format helper to avoid circular deps at module level.\n const { formatOtlpTraces, exportToEndpoint } = await import('./metrics');\n const body = formatOtlpTraces(toExport, config.serviceName, config.serviceVersion);\n await exportToEndpoint(config.endpoint, config.headers ?? {}, body);\n }\n },\n };\n\n return tracer;\n}\n\n// ---------------------------------------------------------------------------\n// useTracing hook\n// ---------------------------------------------------------------------------\n\n/**\n * Hook that creates a span for the component render lifecycle.\n * Auto-starts on mount, records render duration, ends on unmount.\n */\nexport function useTracing(tracer: Tracer, name: string): void {\n const spanRef = useRef<Span | null>(null);\n\n useEffect(() => {\n // Mount \u2014 start span\n const span = tracer.startSpan(name, { kind: 'internal' });\n span.events.push({ name: 'mount', timestamp: performance.now() });\n spanRef.current = span;\n\n return () => {\n // Unmount \u2014 end span\n if (spanRef.current) {\n spanRef.current.events.push({ name: 'unmount', timestamp: performance.now() });\n endSpan(spanRef.current);\n }\n };\n }, []);\n}\n", "// ============================================================================\n// SpecifyJS Telemetry \u2014 Public API\n// ============================================================================\n// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nexport {\n // Types\n type TraceId,\n type SpanId,\n type TraceContext,\n type SpanKind,\n type SpanStatus,\n type SpanEvent,\n type Span,\n type StartSpanOptions,\n type TracerConfig,\n type Tracer,\n // Functions\n generateTraceId,\n generateSpanId,\n parseTraceparent,\n formatTraceparent,\n startSpan,\n endSpan,\n createTracer,\n useTracing,\n} from './tracing';\n\nexport {\n // Types\n type DataPoint,\n type Counter,\n type Histogram,\n type Gauge,\n type Instrument,\n type InstrumentOptions,\n type MeterProviderConfig,\n type MeterProvider,\n // Functions\n createMeterProvider,\n formatOtlpMetrics,\n formatOtlpTraces,\n exportToEndpoint,\n} from './metrics';\n"],
|
|
5
|
-
"mappings": ";
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../../../src/telemetry/tracing.ts"],
|
|
4
|
+
"sourcesContent": ["// ============================================================================\n// SpecifyJS Telemetry \u2014 Distributed Tracing (OpenTelemetry-compatible)\n// Zero third-party dependencies \u2014 OTEL protocols implemented from scratch.\n// ============================================================================\n// (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE\n// SPDX-License-Identifier: MIT\n\nimport { useEffect, useRef } from '../hooks/index';\n\n// ---------------------------------------------------------------------------\n// Trace Context \u2014 W3C Trace Context propagation\n// ---------------------------------------------------------------------------\n\n/** 16-byte (32 hex char) trace identifier. */\nexport type TraceId = string;\n\n/** 8-byte (16 hex char) span identifier. */\nexport type SpanId = string;\n\n/** W3C Trace Context carrier. */\nexport interface TraceContext {\n traceId: TraceId;\n spanId: SpanId;\n traceFlags: string;\n parentSpanId?: SpanId;\n}\n\n// -- ID generation ----------------------------------------------------------\n\nfunction randomBytes(length: number): Uint8Array {\n const buf = new Uint8Array(length);\n try {\n // Works in browsers and Node >=15 (globalThis.crypto)\n crypto.getRandomValues(buf);\n } catch {\n /* v8 ignore next 3 -- fallback for environments without Web Crypto */\n for (let i = 0; i < length; i++) {\n buf[i] = Math.floor(Math.random() * 256);\n }\n }\n return buf;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += (bytes[i] ?? 0).toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/** Generate a 32-hex-char trace ID (16 random bytes). */\nexport function generateTraceId(): TraceId {\n return bytesToHex(randomBytes(16));\n}\n\n/** Generate a 16-hex-char span ID (8 random bytes). */\nexport function generateSpanId(): SpanId {\n return bytesToHex(randomBytes(8));\n}\n\n// -- W3C traceparent parsing / formatting -----------------------------------\n\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\n/**\n * Parse a W3C `traceparent` header.\n *\n * Format: `{version}-{traceId}-{spanId}-{traceFlags}`\n * Returns `null` when the header is invalid.\n */\nexport function parseTraceparent(header: string): TraceContext | null {\n const match = TRACEPARENT_RE.exec(header.trim());\n if (!match) return null;\n\n const traceId = match[2]!;\n const spanId = match[3]!;\n const traceFlags = match[4]!;\n\n // All-zero trace/span IDs are invalid per the spec.\n if (/^0+$/.test(traceId) || /^0+$/.test(spanId)) return null;\n\n return { traceId, spanId, traceFlags };\n}\n\n/**\n * Format a {@link TraceContext} as a W3C `traceparent` header string.\n *\n * Output: `00-{traceId}-{spanId}-{traceFlags}`\n */\nexport function formatTraceparent(ctx: TraceContext): string {\n return `00-${ctx.traceId}-${ctx.spanId}-${ctx.traceFlags}`;\n}\n\n// ---------------------------------------------------------------------------\n// Spans\n// ---------------------------------------------------------------------------\n\nexport type SpanKind = 'internal' | 'server' | 'client' | 'producer' | 'consumer';\n\nexport interface SpanStatus {\n code: 'unset' | 'ok' | 'error';\n message?: string;\n}\n\nexport interface SpanEvent {\n name: string;\n timestamp: number;\n attributes?: Record<string, string | number | boolean>;\n}\n\nexport interface Span {\n traceId: TraceId;\n spanId: SpanId;\n parentSpanId?: SpanId;\n name: string;\n kind: SpanKind;\n startTime: number;\n endTime?: number;\n status: SpanStatus;\n attributes: Record<string, string | number | boolean>;\n events: SpanEvent[];\n}\n\nexport interface StartSpanOptions {\n kind?: SpanKind;\n parentSpanId?: SpanId;\n traceId?: TraceId;\n attributes?: Record<string, string | number | boolean>;\n}\n\n/**\n * Create and start a new span. The span is **not** automatically associated\n * with a tracer \u2014 use {@link Tracer.startSpan} for automatic parent tracking.\n */\nexport function startSpan(name: string, opts?: StartSpanOptions): Span {\n return {\n traceId: opts?.traceId ?? generateTraceId(),\n spanId: generateSpanId(),\n parentSpanId: opts?.parentSpanId,\n name,\n kind: opts?.kind ?? 'internal',\n startTime: performance.now(),\n status: { code: 'unset' },\n attributes: opts?.attributes ? { ...opts.attributes } : {},\n events: [],\n };\n}\n\n/** End a span by recording its end time. */\nexport function endSpan(span: Span): void {\n span.endTime = performance.now();\n}\n\n// ---------------------------------------------------------------------------\n// Tracer\n// ---------------------------------------------------------------------------\n\nexport interface TracerConfig {\n serviceName: string;\n serviceVersion?: string;\n endpoint?: string;\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n}\n\nexport interface Tracer {\n /** Create a span, automatically parented to the current active span. */\n startSpan(name: string, opts?: StartSpanOptions): Span;\n\n /**\n * Execute `fn` with `span` as the active span. The span is automatically\n * ended when `fn` completes (sync or async). The previous active span is\n * restored afterward.\n */\n withSpan<T>(span: Span, fn: () => T): T;\n\n /** Export all pending (buffered) spans to the configured endpoint. */\n flush(): Promise<void>;\n\n /** Access the currently-active span (top of the span stack), or `undefined`. */\n activeSpan(): Span | undefined;\n\n /** Read-only view of the pending span buffer. */\n readonly pendingSpans: ReadonlyArray<Span>;\n\n /** Tracer configuration. */\n readonly config: Readonly<TracerConfig>;\n}\n\nexport function createTracer(config: TracerConfig): Tracer {\n const MAX_BUFFER_SIZE = config.batchSize ?? 1000;\n const spanStack: Span[] = [];\n const buffer: Span[] = [];\n\n function bufferSpan(span: Span): void {\n if (buffer.length >= MAX_BUFFER_SIZE) {\n buffer.splice(0, Math.floor(MAX_BUFFER_SIZE / 2)); // drop oldest half\n }\n buffer.push(span);\n }\n\n // Auto-flush timer (if configured)\n let flushTimer: ReturnType<typeof setInterval> | undefined;\n if (config.flushInterval && config.flushInterval > 0) {\n flushTimer = setInterval(() => {\n void tracer.flush();\n }, config.flushInterval);\n // Allow the process to exit even if the timer is running (Node.js).\n if (typeof flushTimer === 'object' && 'unref' in flushTimer) {\n (flushTimer as { unref: () => void }).unref();\n }\n }\n\n const tracer: Tracer = {\n config,\n\n get pendingSpans(): ReadonlyArray<Span> {\n return buffer;\n },\n\n activeSpan(): Span | undefined {\n return spanStack.length > 0 ? spanStack[spanStack.length - 1] : undefined;\n },\n\n startSpan(name: string, opts?: StartSpanOptions): Span {\n const active = tracer.activeSpan();\n const span = startSpan(name, {\n kind: opts?.kind,\n attributes: opts?.attributes,\n traceId: opts?.traceId ?? active?.traceId,\n parentSpanId: opts?.parentSpanId ?? active?.spanId,\n });\n spanStack.push(span);\n return span;\n },\n\n withSpan<T>(span: Span, fn: () => T): T {\n // Only push if not already on the stack (startSpan may have pushed it).\n const alreadyOnStack = spanStack.includes(span);\n if (!alreadyOnStack) {\n spanStack.push(span);\n }\n\n const removeFromStack = (): void => {\n // Remove ALL occurrences of the span from the stack.\n for (let i = spanStack.length - 1; i >= 0; i--) {\n if (spanStack[i] === span) {\n spanStack.splice(i, 1);\n }\n }\n };\n\n try {\n const result = fn();\n // Handle thenables (Promises) without importing anything.\n if (result && typeof (result as unknown as Promise<unknown>).then === 'function') {\n return (result as unknown as Promise<unknown>).then(\n (value) => {\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n return value;\n },\n (err) => {\n span.status = { code: 'error', message: String(err) };\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n throw err;\n },\n ) as unknown as T;\n }\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n return result;\n } catch (err) {\n span.status = { code: 'error', message: String(err) };\n endSpan(span);\n bufferSpan(span);\n removeFromStack();\n throw err;\n }\n },\n\n async flush(): Promise<void> {\n if (buffer.length === 0) return;\n\n const toExport = buffer.splice(0, buffer.length);\n\n if (config.endpoint) {\n // Lazy-import format helper to avoid circular deps at module level.\n const { formatOtlpTraces, exportToEndpoint } = await import('./metrics');\n const body = formatOtlpTraces(toExport, config.serviceName, config.serviceVersion);\n await exportToEndpoint(config.endpoint, config.headers ?? {}, body);\n }\n },\n };\n\n return tracer;\n}\n\n// ---------------------------------------------------------------------------\n// useTracing hook\n// ---------------------------------------------------------------------------\n\n/**\n * Hook that creates a span for the component render lifecycle.\n * Auto-starts on mount, records render duration, ends on unmount.\n */\nexport function useTracing(tracer: Tracer, name: string): void {\n const spanRef = useRef<Span | null>(null);\n\n useEffect(() => {\n // Mount \u2014 start span\n const span = tracer.startSpan(name, { kind: 'internal' });\n span.events.push({ name: 'mount', timestamp: performance.now() });\n spanRef.current = span;\n\n return () => {\n // Unmount \u2014 end span\n if (spanRef.current) {\n spanRef.current.events.push({ name: 'unmount', timestamp: performance.now() });\n endSpan(spanRef.current);\n }\n };\n }, []);\n}\n"],
|
|
5
|
+
"mappings": ";oMA6BA,SAASA,EAAYC,EAA4B,CAC/C,IAAMC,EAAM,IAAI,WAAWD,CAAM,EACjC,GAAI,CAEF,OAAO,gBAAgBC,CAAG,CAC5B,MAAQ,CAEN,QAASC,EAAI,EAAGA,EAAIF,EAAQE,IAC1BD,EAAIC,CAAC,EAAI,KAAK,MAAM,KAAK,OAAO,EAAI,GAAG,CAE3C,CACA,OAAOD,CACT,CAEA,SAASE,EAAWC,EAA2B,CAC7C,IAAIC,EAAM,GACV,QAASH,EAAI,EAAGA,EAAIE,EAAM,OAAQF,IAChCG,IAAQD,EAAMF,CAAC,GAAK,GAAG,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,EAErD,OAAOG,CACT,CAGO,SAASC,GAA2B,CACzC,OAAOH,EAAWJ,EAAY,EAAE,CAAC,CACnC,CAGO,SAASQ,GAAyB,CACvC,OAAOJ,EAAWJ,EAAY,CAAC,CAAC,CAClC,CAIA,IAAMS,EAAiB,8DAQhB,SAASC,EAAiBC,EAAqC,CACpE,IAAMC,EAAQH,EAAe,KAAKE,EAAO,KAAK,CAAC,EAC/C,GAAI,CAACC,EAAO,OAAO,KAEnB,IAAMC,EAAUD,EAAM,CAAC,EACjBE,EAASF,EAAM,CAAC,EAChBG,EAAaH,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Me,EAAiBf,EAAO,SAAUA,EAAO,SAAW,CAAC,EAAGgB,CAAI,CACpE,CACF,CACF,EAEA,OAAOV,CACT,CAUO,SAASW,EAAWX,EAAgBX,EAAoB,CAC7D,IAAMuB,EAAUC,EAAoB,IAAI,EAExCC,EAAU,IAAM,CAEd,IAAMtB,EAAOQ,EAAO,UAAUX,EAAM,CAAE,KAAM,UAAW,CAAC,EACxD,OAAAG,EAAK,OAAO,KAAK,CAAE,KAAM,QAAS,UAAW,YAAY,IAAI,CAAE,CAAC,EAChEoB,EAAQ,QAAUpB,EAEX,IAAM,CAEPoB,EAAQ,UACVA,EAAQ,QAAQ,OAAO,KAAK,CAAE,KAAM,UAAW,UAAW,YAAY,IAAI,CAAE,CAAC,EAC7ErB,EAAQqB,EAAQ,OAAO,EAE3B,CACF,EAAG,CAAC,CAAC,CACP",
|
|
6
|
+
"names": ["randomBytes", "length", "buf", "i", "bytesToHex", "bytes", "hex", "generateTraceId", "generateSpanId", "TRACEPARENT_RE", "parseTraceparent", "header", "match", "traceId", "spanId", "traceFlags", "formatTraceparent", "ctx", "startSpan", "name", "opts", "endSpan", "span", "createTracer", "config", "MAX_BUFFER_SIZE", "spanStack", "buffer", "bufferSpan", "flushTimer", "tracer", "active", "fn", "removeFromStack", "result", "value", "err", "toExport", "formatOtlpTraces", "exportToEndpoint", "body", "useTracing", "spanRef", "useRef", "useEffect"]
|
|
7
7
|
}
|
package/dist/specifyjs.esm.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* (c) 2025-2026 Asymmetric Effort, LLC. MIT LICENSE */
|
|
2
|
-
var g=Symbol.for("spec.element"),j=Symbol.for("spec.fragment"),nt=Symbol.for("spec.portal"),H=Symbol.for("spec.provider"),q=Symbol.for("spec.consumer"),B=Symbol.for("spec.forward_ref"),K=Symbol.for("spec.memo"),z=Symbol.for("spec.lazy"),W=Symbol.for("spec.suspense"),G=Symbol.for("spec.strict_mode"),J=Symbol.for("spec.profiler");function m(e,t,...o){let n=null,r=null,a={};if(t!=null){t.key!==void 0&&(n=""+t.key),t.ref!==void 0&&(r=t.ref);for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&s!=="key"&&s!=="ref"&&s!=="__proto__"&&s!=="constructor"&&s!=="prototype"&&(a[s]=t[s])}if(o.length===1?a.children=o[0]:o.length>1&&(a.children=o),typeof e=="function"&&e.defaultProps){let s=e.defaultProps;for(let i of Object.keys(s))i!=="__proto__"&&i!=="constructor"&&a[i]===void 0&&(a[i]=s[i])}return{$$typeof:g,type:e,props:a,key:n,ref:r}}function Ee(e){return(t,...o)=>m(e,t??null,...o)}var ve=j;function k(e){let t={$$typeof:Symbol.for("spec.context"),Provider:null,Consumer:null,_currentValue:e,_defaultValue:e},o={$$typeof:H,_context:t},n={$$typeof:q,_context:t};return t.Provider=o,t.Consumer=n,t}function ke(){return{current:null}}function Re(e){return{$$typeof:B,render:e,displayName:e.displayName||e.name||"ForwardRef"}}function be(e,t){return{$$typeof:K,type:e,compare:t||null,displayName:e.displayName||e.name||"Memo"}}function we(e){let t={_status:"pending",_result:void 0};return{$$typeof:z,_payload:t,_init:()=>{if(t._status==="resolved")return t._result;if(t._status==="rejected")throw t._result;let n=e();throw t._status="pending",n.then(r=>{t._status="resolved",t._result=r.default},r=>{t._status="rejected",t._result=r}),n},displayName:"Lazy"}}function R(e){return typeof e=="object"&&e!==null&&e.$$typeof===g}function Te(e,t,...o){if(!R(e))throw new Error("cloneElement: argument must be a valid SpecifyJS element");let n=e.key,r=e.ref,a={...e.props};if(t!=null){t.key!==void 0&&(n=""+t.key),t.ref!==void 0&&(r=t.ref);for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&s!=="key"&&s!=="ref"&&s!=="__proto__"&&s!=="constructor"&&s!=="prototype"&&(a[s]=t[s])}return o.length===1?a.children=o[0]:o.length>1&&(a.children=o),{$$typeof:g,type:e.type,props:a,key:n,ref:r}}function _(e){let t=[],o=[e];for(;o.length>0;){let n=o.pop();if(Array.isArray(n))for(let r=n.length-1;r>=0;r--)o.push(n[r]);else t.push(n)}return t}function _e(e,t){let o=_(e),n=[];for(let r=0;r<o.length;r++){let a=o[r];a==null||typeof a=="boolean"||n.push(t(a,r))}return n}function Ne(e,t){let o=_(e),n=0;for(let r of o)r==null||typeof r=="boolean"||t(r,n++)}function Le(e){let t=_(e),o=0;for(let n of t)n!=null&&typeof n!="boolean"&&o++;return o}function Fe(e){if(!R(e))throw new Error("Children.only: expected a single SpecifyJS element child");return e}function Ie(e){return _(e).filter(o=>o!=null&&typeof o!="boolean")}var Me={map:_e,forEach:Ne,count:Le,only:Fe,toArray:Ie};var P=class{constructor(t){this._fiber=null;this._pendingState=[];this._forceUpdate=!1;this.props=t,this.state={},this.context=void 0}setState(t,o){this._pendingState.push(t),this._enqueueUpdate(o)}forceUpdate(t){this._forceUpdate=!0,this._enqueueUpdate(t)}render(){return null}_enqueueUpdate(t){}};P.prototype.isSpecComponent=!0;var N=class extends P{shouldComponentUpdate(t,o){return!X(this.props,t)||!X(this.state,o)}};N.prototype.isPureSpecComponent=!0;function X(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;let r=e,a=t;for(let s of o)if(!Object.prototype.hasOwnProperty.call(a,s)||!Object.is(r[s],a[s]))return!1;return!0}var M=class extends P{static getDerivedStateFromError(t){return{hasError:!0,error:t}}constructor(t){super(t),this.state={hasError:!1,error:null}}componentDidCatch(t,o){this.props.onError?.(t,o)}render(){return this.state.hasError?this.props.fallback??null:this.props.children??null}};function Z(e){let t=O(e);t.current=e;let o=JSON.stringify([e.title,e.description,e.keywords,e.author,e.canonical,e.og,e.twitter,e.httpEquiv,e.meta]);C(()=>{let n=t.current,r=[],a=document.title;if(n.title&&(document.title=n.title,r.push(()=>{document.title=a})),n.description&&r.push(S("name","description",n.description)),n.keywords&&r.push(S("name","keywords",n.keywords)),n.author&&r.push(S("name","author",n.author)),n.canonical){let s=document.createElement("link");s.rel="canonical",s.href=n.canonical,document.head.appendChild(s),r.push(()=>s.remove())}if(n.og)for(let[s,i]of Object.entries(n.og))r.push(S("property",`og:${s}`,i));if(n.twitter)for(let[s,i]of Object.entries(n.twitter))r.push(S("name",`twitter:${s}`,i));if(n.httpEquiv){let s={csp:"Content-Security-Policy",referrer:"Referrer-Policy",contentType:"X-Content-Type-Options",frameOptions:"X-Frame-Options",cacheControl:"Cache-Control"};for(let[i,u]of Object.entries(n.httpEquiv)){if(u===void 0)continue;let p=s[i]??i;r.push(Oe(p,u))}}if(n.meta)for(let s of n.meta)s.name?r.push(S("name",s.name,s.content)):s.property&&r.push(S("property",s.property,s.content));return()=>{for(let s of r)s()}},[o])}function Q(e){return e.replace(/["\\]/g,"\\$&")}function S(e,t,o){let n=`meta[${e}="${Q(t)}"]`,r=document.querySelector(n),a=r!==null,s=r?.content;return r||(r=document.createElement("meta"),r.setAttribute(e,t),document.head.appendChild(r)),r.content=o,()=>{a&&s!==void 0?r.content=s:a||r.remove()}}function Oe(e,t){let o=`meta[http-equiv="${Q(e)}"]`,n=document.querySelector(o),r=n!==null,a=n?.content;return n||(n=document.createElement("meta"),n.setAttribute("http-equiv",e),document.head.appendChild(n)),n.content=t,()=>{r&&a!==void 0?n.content=a:r||n.remove()}}var ee=null;function c(){if(ee===null)throw new Error("Invalid hook call. Hooks can only be called inside the body of a function component.");return ee}function E(e){return c().useState(e)}function C(e,t){return c().useEffect(e,t)}function l(e){return c().useContext(e)}function De(e,t,o){return c().useReducer(e,t,o)}function h(e,t){return c().useCallback(e,t)}function b(e,t){return c().useMemo(e,t)}function O(e){return c().useRef(e)}function Ue(e,t,o){return c().useImperativeHandle(e,t,o)}function $e(e,t){return c().useLayoutEffect(e,t)}function Ve(e,t){return c().useDebugValue(e,t)}function Ye(){return c().useId()}function Ae(e){return c().useDeferredValue(e)}function je(){return c().useTransition()}function He(e,t,o){return c().useSyncExternalStore(e,t,o)}function qe(e,t){return c().useInsertionEffect(e,t)}var Be=W;var Ke=G;var ze=J;var d=k({pathname:"/",params:{},navigate:()=>{throw new Error("useNavigate must be used inside a <Router> component.")},basePath:""});function te(){let t=(typeof window<"u"?window.location.hash:"").replace(/^#\/?/,"/");return t===""?"/":t}var ne={pathname:te(),hash:typeof window<"u"?window.location.hash:""},D=new Set;function oe(){ne={pathname:te(),hash:typeof window<"u"?window.location.hash:""};for(let e of D)e()}typeof window<"u"&&window.addEventListener("hashchange",oe);function re(e){return D.add(e),()=>{D.delete(e)}}function L(){return ne}function se(e,t){let o=e.startsWith("#")?e:"#"+e;if(t?.replace){let n=window.location.pathname+window.location.search+o;window.history.replaceState(null,"",n)}else window.location.hash=o;oe()}function ae(e){let[t,o]=E(()=>L().pathname);C(()=>(o(L().pathname),re(()=>{o(L().pathname)})),[]);let n=h((...a)=>{se(a[0],a[1])},[]),r=b(()=>({pathname:t,params:{},navigate:n,basePath:""}),[t,n]);return m(d.Provider,{value:r},e.children)}function ie(e){let t=e.length;for(;t>1&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}function v(e,t,o){let n=o?.exact??!1,r=e==="/"?"/":ie(e),a=t==="/"?"/":ie(t);if(r==="/"){let x=a==="/";return n&&!x?null:{params:{},isExact:x,path:e,url:"/"}}let s=r.split("/").filter(Boolean),i=a.split("/").filter(Boolean),u=s[s.length-1]==="*";if(!u&&n&&i.length!==s.length||!u&&i.length<s.length)return null;let p={},y=[];for(let x=0;x<s.length;x++){let w=s[x];if(w==="*"){let I=i.slice(x).join("/");return p["*"]=I,{params:p,isExact:!0,path:e,url:"/"+i.join("/")}}if(x>=i.length)return null;let T=i[x];if(w.startsWith(":")){let I=w.slice(1);p[I]=decodeURIComponent(T),y.push(T);continue}if(w.toLowerCase()!==T.toLowerCase())return null;y.push(T)}let f="/"+y.join("/"),F=i.length===s.length;return n&&!F?null:{params:p,isExact:F,path:e,url:f}}function pe(e){let t=l(d),o=t.basePath+e.path,n=v(o,t.pathname,{exact:e.exact??!1}),r=b(()=>({pathname:t.pathname,params:{...t.params,...n?n.params:{}},navigate:t.navigate,basePath:n?n.url:t.basePath}),[t.pathname,t.navigate,t.params,t.basePath,n]);if(!n)return null;for(let s of Object.keys(t.params))s in r.params||(r.params[s]=t.params[s]);let a=e.component?m(e.component,{...r.params}):e.children;return m(d.Provider,{value:r},a)}function ue(e){let{to:t,className:o,activeClassName:n,exact:r,children:a,...s}=e,i=l(d),u=v(t,i.pathname,{exact:r??!1})!==null,p=h(((...f)=>{f[0].preventDefault(),i.navigate(t)}),[t,i.navigate]),y=[o,u?n:null].filter(Boolean).join(" ")||void 0;return m("a",{...s,href:"#"+t,onClick:p,className:y},a)}function ce(){return l(d)}function le(){return l(d).params}function fe(){return l(d).navigate}var de=8;function me(){let e=de;return de=e===8?16:8,e}var U=4,$=!1;var ye=[];function Ge(e){let t=U,o=$;U=me(),$=!0;try{e()}finally{U=t,$=o,Je()}}function Je(){let e=ye;ye=[];for(let t of e)t()}var xe=[];function V(){let e=xe;xe=[];for(let t of e)t()}function Xe(e){let t=e();V(),t&&typeof t.then=="function"&&t.then(()=>{V()})}function he(e){if(e.startsWith("//"))throw new Error(`[SpecifyJS] Protocol-relative URL rejected: "${e}". Use an explicit https:// prefix.`);if(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("data:"))return;let t;try{t=new URL(e,typeof window<"u"?window.location.href:void 0)}catch{return}if(t.protocol!=="https:"&&!(t.hostname==="localhost"||t.hostname==="127.0.0.1"))throw new Error(`[SpecifyJS] Insecure URL rejected: "${e}". SpecifyJS enforces HTTPS-only for all network requests. Use https:// or a relative URL. Localhost URLs are allowed for development.`)}function Y(e,t){let o=typeof e=="string"?e:e instanceof URL?e.href:e.url;return he(o),fetch(e,t)}var Pe=new Map;var Ze=!0;function Qe(e){Ze=e}function et(e){let t=e.match(/^s-(\d+)-(\d+)$/);if(!t||!t[1]||!t[2])return null;let o=parseInt(t[1],10),n=parseInt(t[2],10);for(let r of Pe.values())if(r.index===o)return{typeName:r.name,typeIndex:o,instanceId:n};return null}function tt(){return Pe}var A=k({flags:{},isEnabled:()=>!1,setFlag:()=>{},loading:!1});function Se(e){let[t,o]=E(()=>({...e.defaults})),[n,r]=E(!!e.url);C(()=>{if(!e.url)return;let u=!1;return r(!0),Y(e.url).then(p=>{if(!p.ok)throw new Error(`HTTP ${p.status}`);return p.json()}).then(p=>{if(!u&&typeof p=="object"&&p!==null){let y={};for(let f of Object.keys(p))f!=="__proto__"&&f!=="constructor"&&f!=="prototype"&&(y[f]=p[f]===!0);o(f=>({...f,...y}))}u||r(!1)}).catch(()=>{u||r(!1)}),()=>{u=!0}},[e.url]);let a=h(((...u)=>{let p=u[0];return t[p]===!0}),[t]),s=h(((...u)=>{let p=u[0],y=u[1];o(f=>({...f,[p]:y}))}),[]),i={flags:t,isEnabled:a,setFlag:s,loading:n};return m(A.Provider,{value:i},e.children)}function Ce(e){let{isEnabled:t}=l(A);return t(e.flag)?e.children:e.fallback??null}function ge(){return l(A)}export{Me as Children,P as Component,M as ErrorBoundary,Se as FeatureFlagProvider,Ce as FeatureGate,ve as Fragment,ue as Link,ze as Profiler,N as PureComponent,pe as Route,ae as Router,Ke as StrictMode,Be as Suspense,Xe as act,he as assertSecureUrl,Te as cloneElement,k as createContext,m as createElement,Ee as createFactory,ke as createRef,Re as forwardRef,tt as getComponentTypeTable,m as h,R as isValidElement,we as lazy,v as matchPath,be as memo,et as resolveComponentId,Y as secureFetch,Qe as setComponentIdsEnabled,Ge as startTransition,h as useCallback,l as useContext,Ve as useDebugValue,Ae as useDeferredValue,C as useEffect,ge as useFeatureFlags,Z as useHead,Ye as useId,Ue as useImperativeHandle,qe as useInsertionEffect,$e as useLayoutEffect,b as useMemo,fe as useNavigate,le as useParams,De as useReducer,O as useRef,ce as useRouter,E as useState,He as useSyncExternalStore,je as useTransition};
|
|
3
|
-
//# sourceMappingURL=
|
|
2
|
+
import{a as d,b as e,c as f,d as g,e as h,f as j,g as k,h as l,i as m,j as n,k as E,l as F,m as G,n as H,o as I,p as J,q as K,r as L,s as M,t as N,u as P,v as V,w as W,x as X}from"./esm/chunks/chunk-A7AAS5ZR.js";import{e as O,i as S,k as T,l as U}from"./esm/chunks/chunk-VAF4KNDP.js";import{a as i}from"./esm/chunks/chunk-E43OK6IZ.js";import{a,b,c}from"./esm/chunks/chunk-ODCBJ22O.js";import"./esm/chunks/chunk-3J4RXW7E.js";import{a as Q,b as R}from"./esm/chunks/chunk-TVDAY42P.js";import{a as o,c as p,d as q,e as r,f as s,g as t,h as u,i as v,j as w,k as x,l as y,m as z,n as A,o as B,p as C,q as D}from"./esm/chunks/chunk-MCXU6QF3.js";import"./esm/chunks/chunk-ZDPD2MPQ.js";export{k as Children,l as Component,n as ErrorBoundary,V as FeatureFlagProvider,W as FeatureGate,c as Fragment,K as Link,G as Profiler,m as PureComponent,J as Route,H as Router,F as StrictMode,E as Suspense,P as act,Q as assertSecureUrl,j as cloneElement,d as createContext,a as createElement,b as createFactory,e as createRef,f as forwardRef,U as getComponentTypeTable,a as h,i as isValidElement,h as lazy,I as matchPath,g as memo,T as resolveComponentId,R as secureFetch,S as setComponentIdsEnabled,O as startTransition,t as useCallback,r as useContext,y as useDebugValue,A as useDeferredValue,q as useEffect,X as useFeatureFlags,o as useHead,z as useId,w as useImperativeHandle,D as useInsertionEffect,x as useLayoutEffect,u as useMemo,N as useNavigate,M as useParams,s as useReducer,v as useRef,L as useRouter,p as useState,C as useSyncExternalStore,B as useTransition};
|
|
3
|
+
//# sourceMappingURL=index.js.map
|