@gramlot/gramlot 0.3.20 → 0.3.26

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.
Files changed (172) hide show
  1. package/dist/components/chat/__init__.py +13 -0
  2. package/dist/components/chat/assets/collection.js +9 -0
  3. package/dist/components/chat/assets/index.js +3 -0
  4. package/dist/components/chat/commands.json +7 -0
  5. package/dist/components/chat/grammar.json +48 -0
  6. package/dist/components/editors/__init__.py +2 -2
  7. package/dist/components/editors/assets/collection.js +26 -120912
  8. package/dist/components/editors/assets/index.js +2 -1
  9. package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
  10. package/dist/components/editors/assets/modules/chunk-AU4HFPIY.js +1 -0
  11. package/dist/components/editors/assets/modules/chunk-YSGSC7KM.js +1 -0
  12. package/dist/components/editors/assets/modules/code-mirror-engine-RWQTR5G5.js +92 -0
  13. package/dist/components/editors/assets/modules/jodit-engine-MTSA4GZ3.js +1853 -0
  14. package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
  15. package/dist/components/editors/assets/modules/prose-mirror-engine-GMZPJPNN.js +24 -0
  16. package/dist/components/grid/__init__.py +14 -0
  17. package/dist/components/grid/assets/collection.js +262 -0
  18. package/dist/components/grid/assets/index.js +3 -0
  19. package/dist/components/grid/commands.json +7 -0
  20. package/dist/components/grid/grammar.json +770 -0
  21. package/dist/components/grouplets/__init__.py +13 -0
  22. package/dist/components/grouplets/assets/collection.js +185 -0
  23. package/dist/components/grouplets/assets/index.js +3 -0
  24. package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
  25. package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -0
  26. package/dist/components/grouplets/commands.json +7 -0
  27. package/dist/components/grouplets/grammar.json +355 -0
  28. package/dist/components/inputs/__init__.py +1 -1
  29. package/dist/components/inputs/assets/collection.js +65 -24511
  30. package/dist/components/inputs/assets/index.js +2 -1
  31. package/dist/components/inputs/grammar.json +278 -6
  32. package/dist/components/layout/__init__.py +1 -1
  33. package/dist/components/layout/assets/collection.js +68 -26732
  34. package/dist/components/layout/assets/index.js +2 -1
  35. package/dist/components/layout/grammar.json +39 -0
  36. package/dist/components/selection_trial/__init__.py +13 -0
  37. package/dist/components/selection_trial/assets/collection.js +4 -0
  38. package/dist/components/selection_trial/assets/index.js +3 -0
  39. package/dist/components/selection_trial/commands.json +7 -0
  40. package/dist/components/selection_trial/grammar.json +587 -0
  41. package/dist/components/tree/__init__.py +1 -1
  42. package/dist/components/tree/assets/collection.js +27 -24612
  43. package/dist/components/tree/assets/index.js +2 -1
  44. package/dist/components/tree/grammar.json +341 -1
  45. package/dist/components/typst/__init__.py +2 -2
  46. package/dist/components/typst/assets/collection.js +12 -4
  47. package/dist/components/typst/assets/index.js +2 -1
  48. package/dist/components/typst/assets/modules/chunk-BLMUM44K.js +1 -0
  49. package/dist/components/typst/assets/modules/typst-client-JHC6UVYG.js +4 -0
  50. package/dist/components/uploads/__init__.py +13 -0
  51. package/dist/components/uploads/assets/collection.js +67 -0
  52. package/dist/components/uploads/assets/index.js +3 -0
  53. package/dist/components/uploads/commands.json +7 -0
  54. package/dist/components/uploads/grammar.json +789 -0
  55. package/dist/gramlot-markdown.js +16 -0
  56. package/dist/gramlot.js +6861 -1395
  57. package/dist/gramlot.min.js +1595 -46
  58. package/dist/runtime-notices.json +28 -0
  59. package/package.json +10 -3
  60. package/src/binding/grid-struct.js +63 -0
  61. package/src/binding/installation.js +5 -2
  62. package/src/binding/providers.js +4 -1
  63. package/src/binding/remote-resolver.js +1 -8
  64. package/src/binding/runtime.js +90 -6
  65. package/src/binding/validation-context.js +40 -0
  66. package/src/browser-camera-provider.d.ts +8 -0
  67. package/src/browser-camera-provider.js +104 -0
  68. package/src/builder/gramlot-builder.d.ts +5 -0
  69. package/src/builder/gramlot-builder.js +16 -0
  70. package/src/builder/source.js +34 -0
  71. package/src/chat.d.ts +12 -0
  72. package/src/chat.js +198 -0
  73. package/src/collection-artifact.js +1 -1
  74. package/src/components/attachment-manager.js +160 -0
  75. package/src/components/bases.js +19 -6
  76. package/src/components/border-container.js +86 -8
  77. package/src/components/buttons.js +11 -1
  78. package/src/components/chat.js +28 -0
  79. package/src/components/choice-editor.js +106 -38
  80. package/src/components/database-choices.js +133 -9
  81. package/src/components/editing-status-styles.js +26 -0
  82. package/src/components/editing-status.js +115 -0
  83. package/src/components/field-state.js +42 -54
  84. package/src/components/grid-cell-editor.js +181 -0
  85. package/src/components/grid-grammar.json +258 -0
  86. package/src/components/grid-header-interaction.js +196 -0
  87. package/src/components/grid-row-interaction.js +184 -0
  88. package/src/components/grid-row-layout.js +96 -0
  89. package/src/components/grid-rows.js +28 -0
  90. package/src/components/grid-search-box.js +142 -0
  91. package/src/components/grid-search-styles.js +42 -0
  92. package/src/components/grid-search.js +37 -0
  93. package/src/components/grid-structure.js +85 -0
  94. package/src/components/grid-styles.js +201 -0
  95. package/src/components/grid.js +666 -0
  96. package/src/components/grouplet-card.js +445 -0
  97. package/src/components/grouplets.js +17 -0
  98. package/src/components/html-preview.js +17 -4
  99. package/src/components/image-crop-dialog.js +272 -0
  100. package/src/components/image-crop.js +79 -0
  101. package/src/components/image-uploader.js +252 -0
  102. package/src/components/inputs.js +2 -1
  103. package/src/components/jodit-engine.js +1 -1
  104. package/src/components/markdown-document.js +2 -2
  105. package/src/components/menus.js +1 -0
  106. package/src/components/registry.js +4 -3
  107. package/src/components/screen-capture.js +43 -0
  108. package/src/components/selected-container.js +6 -2
  109. package/src/components/tray-pane.js +32 -4
  110. package/src/components/tree.js +416 -17
  111. package/src/components/typed-editor.js +23 -11
  112. package/src/components/upload-engine.js +156 -0
  113. package/src/components/uploader.js +208 -0
  114. package/src/components/uploads.js +7 -0
  115. package/src/editing-session.d.ts +25 -0
  116. package/src/editing-session.js +396 -0
  117. package/src/experiments/selection-transfer.js +78 -0
  118. package/src/experiments/selection-trial.js +64 -0
  119. package/src/experiments/window-selection.js +124 -0
  120. package/src/format.js +22 -7
  121. package/src/gramlot.d.ts +2 -0
  122. package/src/gramlot.js +2 -1
  123. package/src/handlers/device-handler.d.ts +2 -1
  124. package/src/handlers/rpc-handler.d.ts +3 -3
  125. package/src/index-page-styles.js +2 -1
  126. package/src/index.d.ts +16 -1
  127. package/src/index.js +16 -1
  128. package/src/inout.d.ts +2 -0
  129. package/src/inout.js +6 -0
  130. package/src/markdown-loader.d.ts +1 -0
  131. package/src/markdown-loader.js +4 -0
  132. package/src/markdown.d.ts +1 -0
  133. package/src/markdown.js +2 -0
  134. package/src/media-frame.js +9 -0
  135. package/src/renderer/attributes.js +7 -1
  136. package/src/renderer/gramlot-renderer.d.ts +2 -0
  137. package/src/renderer/gramlot-renderer.js +39 -3
  138. package/src/server/assets.d.ts +1 -1
  139. package/src/server/assets.js +1 -1
  140. package/src/server/gramlot-server.d.ts +10 -1
  141. package/src/server/gramlot-server.js +96 -8
  142. package/src/server/index.d.ts +2 -0
  143. package/src/server/index.js +2 -0
  144. package/src/server/page-base.js +17 -4
  145. package/src/server/page.d.ts +13 -1
  146. package/src/server/page.js +6 -0
  147. package/src/server/source-import.d.ts +2 -0
  148. package/src/server/source-import.js +31 -0
  149. package/src/server/upload.d.ts +20 -0
  150. package/src/server/upload.js +142 -0
  151. package/src/server/visual-editor.d.ts +11 -0
  152. package/src/server/visual-editor.js +149 -0
  153. package/src/source-picker.d.ts +9 -0
  154. package/src/source-picker.js +57 -0
  155. package/src/stores/bag-collection-store.js +51 -0
  156. package/src/stores/bag-collection-view.js +127 -0
  157. package/src/stores/collection-filter.js +77 -0
  158. package/src/tree-store.d.ts +24 -0
  159. package/src/tree-store.js +193 -0
  160. package/src/validation-run.js +50 -0
  161. package/src/view/button.js +8 -5
  162. package/src/view/controls.js +31 -32
  163. package/src/view/grouplet-card.js +54 -0
  164. package/src/view/html.js +29 -4
  165. package/src/view/labelbox.js +7 -3
  166. package/src/visual-editor-icons.js +10 -0
  167. package/src/visual-editor.d.ts +56 -0
  168. package/src/visual-editor.js +844 -0
  169. package/themes/gramlot-base/theme.css +127 -0
  170. package/themes/gramlot-compact/theme.css +8 -0
  171. package/themes/joanna/theme.css +8 -0
  172. package/themes/mimi/theme.css +8 -0
@@ -10,6 +10,7 @@ import {HtmlElement} from '../view/html.js';
10
10
  import {ControlAdapter, RadioControl, RadioGroups, SelectControl} from '../view/controls.js';
11
11
  import {ButtonBinding} from '../view/button.js';
12
12
  import {MenuBinding} from '../view/menu.js';
13
+ import {GroupletCardActions} from '../view/grouplet-card.js';
13
14
  import {NativeEventBinding} from '../view/events.js';
14
15
  import {References} from '../references.js';
15
16
  import {randomId} from '../random-id.js';
@@ -29,6 +30,8 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
29
30
  static renderType = 'object';
30
31
  // Nodes inside buildNode: events on them are ignored on arrival (P4, R04).
31
32
  #constructing = new Set();
33
+ // Explicitly unmounted views keep Source bindings, but Source updates cannot remount them.
34
+ #unmounted = new WeakSet();
32
35
  // The attributes of each node after runtimeValues and the `==` evaluation, binding attributes included.
33
36
  #resolvedAttributes = new WeakMap();
34
37
  // The resolved projection that `project` hands to the rebuild of a control whose shape changed.
@@ -47,7 +50,8 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
47
50
  this._binding = binding;
48
51
  this.source = source;
49
52
  this.destination = destination;
50
- this.html = new HtmlElement({metadataAttributes: ['__ref'],
53
+ this.html = new HtmlElement({uploadContext: () => ({gramlot: binding.gramlot, window: destination.ownerDocument.defaultView}), metadataAttributes: ['__ref'],
54
+ format: (value, options) => binding.gramlot.format(value, options),
51
55
  reportError: (node, error, title) => { if (this.records.has(node)) binding.reportError(error, title); },
52
56
  callLogic: (node, name, keywords) => {
53
57
  const {group, method} = binding.gramlot.src.logicRegistry.resolve(name, node);
@@ -137,7 +141,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
137
141
  */
138
142
  render(node, opts = {}) {
139
143
  if (!(node instanceof GramlotBuilderBagNode)) throw new TypeError('Source children must be GramlotBuilderBagNodes');
140
- if (node._getMeta('data_element')) return null;
144
+ if (node._getMeta('data_element') || this.#unmounted.has(node)) return null;
141
145
  if (!this.binding.bindingFor(node) && this.#queued(node)) return null;
142
146
  if (node.nodeTag) this.html.validate(node, node._getMeta('subbuilder') ? node.parentBag._builder : node.builder);
143
147
  else if (!(node.value instanceof SourceBag)) throw new TypeError('Source fragments must contain child SourceBags');
@@ -228,6 +232,11 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
228
232
  record.menu.attach();
229
233
  record.cleanup.push(() => record.menu.detach());
230
234
  }
235
+ if (node.nodeTag === 'groupletCard') {
236
+ const actions = new GroupletCardActions(record.binding, record.element);
237
+ actions.attach();
238
+ record.cleanup.push(() => actions.detach());
239
+ }
231
240
  this.#connectEvents(record);
232
241
  this.references?.register(node, record.element);
233
242
  for (const element of children) {
@@ -262,6 +271,21 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
262
271
  this.#validateBlock(block, replacingNode ? replacingNode.nodeTag : null);
263
272
  requireInstallable(block);
264
273
  this.references?.validate(block, excluded);
274
+ const nodeIds = new Set();
275
+ const validateNodeIds = bag => {
276
+ for (const node of bag.getNodes()) {
277
+ const nodeId = node.getAttr('nodeId');
278
+ if (nodeId != null) {
279
+ const mounted = this.binding.nodeIds.get(nodeId);
280
+ if (nodeIds.has(nodeId) || (mounted && mounted !== node && !excluded.has(mounted))) {
281
+ throw new Error(`Duplicate nodeId '${nodeId}'`);
282
+ }
283
+ nodeIds.add(nodeId);
284
+ }
285
+ if (node.value instanceof SourceBag) validateNodeIds(node.value);
286
+ }
287
+ };
288
+ validateNodeIds(block);
265
289
  return block;
266
290
  }
267
291
 
@@ -370,6 +394,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
370
394
  if (!errors.length) throw error;
371
395
  errors.push(error);
372
396
  }
397
+ this.binding.refreshSourceTrees();
373
398
  if (errors.length) throw errors.length === 1 ? errors[0] : new AggregateError(errors, 'Source cleanup failed');
374
399
  }
375
400
  } catch (error) {
@@ -428,6 +453,16 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
428
453
  walk(event.node);
429
454
  }
430
455
 
456
+ /** Release only the view; Source bindings and their semantic resources stay active. */
457
+ unmountView(node) {
458
+ this.#unmounted.add(node);
459
+ this.remove(node);
460
+ }
461
+ /** Rebuild an explicitly unmounted view from its current Source and Data. */
462
+ mountView(node) {
463
+ this.#unmounted.delete(node);
464
+ this.insert(node);
465
+ }
431
466
  /**
432
467
  * Build an inserted node, then report the build to the BindingRuntime (§5.1 step 7). A node that
433
468
  * left the Source meanwhile (an `_init` that removed its own branch, P4) is not built, nor a node
@@ -436,6 +471,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
436
471
  */
437
472
  insert(node) {
438
473
  if (!this.attached(node) || this.records.has(node)) return;
474
+ for (let current = node; current; current = current.parentNode) if (this.#unmounted.has(current)) return;
439
475
  if (node._getMeta('data_element')) {
440
476
  // A `dataController` or `dataRpc` inserted in a button may give it a mechanism, or an ambiguous one (S12).
441
477
  this.records.get(node.parentBag?.parentNode)?.button?.refresh();
@@ -571,7 +607,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
571
607
  (value, options) => this._binding.gramlot.format(value, options));
572
608
  }
573
609
  attrs = this.componentAttributes(node, attrs);
574
- this.html.update(record, node, attrs, branch ? attrs._text : text, resolved.visible ?? null);
610
+ this.html.update(record, node, attrs, branch ? attrs._text : text, resolved.visible ?? null, change);
575
611
  if (replaceControl && Control) {
576
612
  record.control = new Control(record.binding, record);
577
613
  record.control.attach();
@@ -9,4 +9,4 @@ export function gramlotDev(): 'YES' | 'DEBUG' | null;
9
9
  /** URL of a packaged browser asset in `dist`: a `file:` URL from npm (read with `fs.readFile`), an `https:`
10
10
  * URL from JSR (read with `fetch`). Without a name, the runtime to serve at the runtime URL: `gramlot.js`
11
11
  * when `GRAMLOT_DEV=DEBUG`, `gramlot.min.js` otherwise. Another name throws a `TypeError`. */
12
- export function runtimeAsset(name?: 'gramlot.js' | 'gramlot.min.js' | 'runtime-notices.json' | null): URL;
12
+ export function runtimeAsset(name?: 'gramlot.js' | 'gramlot.min.js' | 'gramlot-markdown.js' | 'runtime-notices.json' | null): URL;
@@ -18,7 +18,7 @@ export function gramlotDev() {
18
18
  return value;
19
19
  }
20
20
 
21
- const RUNTIME_ASSETS = ['gramlot.js', 'gramlot.min.js', 'runtime-notices.json'];
21
+ const RUNTIME_ASSETS = ['gramlot.js', 'gramlot.min.js', 'gramlot-markdown.js', 'runtime-notices.json'];
22
22
 
23
23
  /** URL of a packaged browser asset in dist: a file: URL from npm (read with fs.readFile).
24
24
  * Without a name, the runtime to serve at the runtime URL: gramlot.js when
@@ -1,3 +1,4 @@
1
+ import type {UploadTransfer} from './upload.js';
1
2
  /**
2
3
  * The neutral server: registers pages and builds their Sources, with no HTTP engine.
3
4
  *
@@ -73,6 +74,8 @@ export interface GramlotServerOptions {
73
74
  maxPages?: number;
74
75
  /** Application collections: generated Builder grammar and root-relative browser module URL. */
75
76
  collections?: PreparedCollection[];
77
+ /** Enable upload control only when the adapter provides a binary transport. */
78
+ uploadsEnabled?: boolean;
76
79
  /** The base theme of every page, a folder of the core themes, or false for none; default `gramlot-base`. */
77
80
  cssTheme?: string | false;
78
81
  }
@@ -109,6 +112,8 @@ export interface OpenedPage {
109
112
  export class GramlotServer {
110
113
  /** URL of the runtime bundle. */
111
114
  runtimeUrl: string;
115
+ /** Shared optional Markdown module, alongside the runtime. */
116
+ readonly markdownUrl: string;
112
117
  /** URL of the request envelopes. */
113
118
  rpcUrl: string;
114
119
  /** URL of the page close endpoint. */
@@ -126,6 +131,8 @@ export class GramlotServer {
126
131
  /** Create a server. */
127
132
  /** Resolve class-local declarations and their named dependencies, base first. */
128
133
  pageCollections(PageClass: typeof Page): PreparedCollection[];
134
+ /** Environment-local Page class; the imported class remains unchanged. */
135
+ environmentPage(PageClass: typeof Page): typeof Page;
129
136
  collectionGraph(collections: PreparedCollection[]): PreparedCollection[];
130
137
  loadCollections(builder: GramlotBuilder, collections: PreparedCollection[]): void;
131
138
  constructor(options?: GramlotServerOptions);
@@ -156,8 +163,10 @@ export class GramlotServer {
156
163
  openPage(path: string, options?: {owner?: unknown; prefix?: string}): Promise<OpenedPage>;
157
164
  /** The text of a request body: UTF-8, a leading byte order mark removed; other bytes throw `InvalidRequest`. */
158
165
  decodeBody(data: ArrayBuffer | ArrayBufferView): string;
159
- /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX); throws only `InvalidRequest`. `identity` is the identity of this call, read only by `evaluateAuth`. */
166
+ /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX); throws only `InvalidRequest`. `identity` is the trusted identity of this call, supplied to the fresh Page and `evaluateAuth`. */
160
167
  call(text: string, options?: {owner?: unknown; identity?: unknown}): Promise<string>;
168
+ /** Admit a one-use upload after owner and operation authorization checks. */
169
+ admitUpload(options: {pageId: string; transferId: string; authorization: string; owner?: unknown; identity?: unknown}): UploadTransfer;
161
170
  /** Close the page named by the close message `text` (`{"pageId": string}` as JSON) when `owner` owns it; throws `InvalidRequest`. */
162
171
  close(text: string, options?: {owner?: unknown}): void;
163
172
  /** Forget a registered page when `owner` owns it. */
@@ -10,7 +10,8 @@ import {fromTytx, toTytx} from '@genrojs/tytx';
10
10
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
11
11
  import {NAME_SYNTAX} from '../builder/name-syntax.js';
12
12
  import {gramlotDev} from './assets.js';
13
- import {ENDPOINT_METHOD, Page, SOURCE_METHOD, resolveDeclared} from './page.js';
13
+ import {ENDPOINT_METHOD, Page, SOURCE_METHOD, UPLOAD_METHOD, resolveDeclared} from './page.js';
14
+ import {UploadRegistry, UploadTarget} from './upload.js';
14
15
  import {InvalidResourceName, SEGMENT, loadOrder} from './resources.js';
15
16
 
16
17
  export class PageExpired extends Error { name = 'PageExpired'; }
@@ -68,8 +69,8 @@ function parseRequest(text) {
68
69
  for (const field of ['id', 'pageId', 'contentType', 'name']) {
69
70
  if (typeof request[field] !== 'string') throw new InvalidRequest(`Request ${field} must be a string`);
70
71
  }
71
- if (!['source', 'data'].includes(request.contentType)) {
72
- throw new InvalidRequest('Request contentType must be source or data');
72
+ if (!['source', 'data', 'upload'].includes(request.contentType)) {
73
+ throw new InvalidRequest('Request contentType must be source, data or upload');
73
74
  }
74
75
  if (!isMapping(request.params)) throw new InvalidRequest('Request params must be a mapping');
75
76
  return request;
@@ -105,8 +106,10 @@ const prefixed = (prefix, url) => url.startsWith('/') && !url.startsWith('//') ?
105
106
  * owner move the expiry to now plus `pageTtl` (GC-230 §010).
106
107
  */
107
108
  export class GramlotServer {
109
+ get markdownUrl() { return this.runtimeUrl.replace(/[^/]+$/, 'gramlot-markdown.js'); }
110
+
108
111
  constructor({runtimeUrl = '/assets/gramlot.js', rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close',
109
- rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = [],
112
+ rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = [], uploadsEnabled = false,
110
113
  cssTheme = 'gramlot-base'} = {}) {
111
114
  if (cssTheme !== false && !isThemeName(cssTheme)) {
112
115
  throw new TypeError(`The base theme must be a theme name or false, not ${JSON.stringify(cssTheme)}`);
@@ -118,8 +121,10 @@ export class GramlotServer {
118
121
  }
119
122
  Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages, cssTheme});
120
123
  this.pages = new Map();
124
+ this.uploads = uploadsEnabled ? new UploadRegistry() : null;
121
125
  this.collections = [...collections];
122
126
  this.preparedGrammars = new WeakMap();
127
+ this.environmentPages = new WeakMap();
123
128
  }
124
129
 
125
130
  /** The Page class of path, or PageNotFound. */
@@ -132,6 +137,16 @@ export class GramlotServer {
132
137
  return this.collectionGraph([...this.collections, ...classes.flatMap(cls => Object.hasOwn(cls, 'gramlots') ? cls.gramlots : [])]);
133
138
  }
134
139
 
140
+ /** Bind this environment without modifying a module shared by other hosts. */
141
+ environmentPage(PageClass) {
142
+ if (!this.collections.length) return PageClass;
143
+ if (!this.environmentPages.has(PageClass)) {
144
+ const gramlots = this.pageCollections(PageClass);
145
+ this.environmentPages.set(PageClass, class extends PageClass {static gramlots = gramlots;});
146
+ }
147
+ return this.environmentPages.get(PageClass);
148
+ }
149
+
135
150
  /** Resolve named dependencies among prepared records; reject ambiguous identities. */
136
151
  collectionGraph(collections) {
137
152
  const byName = new Map(), visiting = new Set(), done = new Set(), ordered = [];
@@ -224,7 +239,10 @@ export class GramlotServer {
224
239
 
225
240
  prune() {
226
241
  const now = performance.now();
227
- for (const [id, record] of this.pages) if (record.expires <= now) this.pages.delete(id);
242
+ for (const [id, record] of this.pages) if (record.expires <= now) {
243
+ this.pages.delete(id);
244
+ void this.uploads?.closePage(id, record.owner);
245
+ }
228
246
  }
229
247
 
230
248
  /** Describe the root application without registering a page session. */
@@ -264,10 +282,11 @@ export class GramlotServer {
264
282
  * position. */
265
283
  async registerPage(path, {owner = null} = {}) {
266
284
  if (path.endsWith('/index.html')) path = path.slice(0, -'index.html'.length);
267
- const PageClass = await this.resolvePage(path);
285
+ let PageClass = await this.resolvePage(path);
268
286
  if (typeof PageClass !== 'function' || !(PageClass.prototype instanceof Page)) {
269
287
  throw new TypeError('Page modules must export a subclass of Page');
270
288
  }
289
+ PageClass = this.environmentPage(PageClass);
271
290
  const selected = this.pageCollections(PageClass);
272
291
  const resolved = await this.resolveResources(path, PageClass);
273
292
  const resources = loadOrder({...resolved, css: [...this.themeCss(PageClass), ...selected.flatMap(collection=>collection.css ?? []), ...resolved.css]});
@@ -317,6 +336,7 @@ export class GramlotServer {
317
336
  head.script(scriptJson({imports: {'@gramlot/gramlot/page': prefixed(prefix, this.runtimeUrl),
318
337
  '@gramlot/gramlot': prefixed(prefix, this.runtimeUrl),
319
338
  '@gramlot/gramlot/components':prefixed(prefix,this.runtimeUrl),
339
+ '@gramlot/gramlot/markdown':prefixed(prefix,this.markdownUrl),
320
340
  ...Object.fromEntries((resources.collections ?? []).map(({name,url})=>[`@gramlot/collections/${encodeURIComponent(name)}`,prefixed(prefix,url)]))}}),
321
341
  {type: 'importmap', nonce});
322
342
  const body = root.body();
@@ -345,7 +365,7 @@ export class GramlotServer {
345
365
  /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX).
346
366
  * Throws only InvalidRequest; every other failure is an outcome in the response,
347
367
  * a value that TYTX cannot serialise included. `identity` is the identity of this call (for
348
- * example the avatar of a login), read only by evaluateAuth; the server keeps nothing of it. */
368
+ * example the avatar of a login), supplied by the host to the fresh Page and evaluateAuth; the server keeps nothing of it between calls. */
349
369
  async call(text, {owner = null, identity = null} = {}) {
350
370
  const request = parseRequest(text);
351
371
  const response = {id: request.id, contentType: request.contentType};
@@ -383,6 +403,8 @@ export class GramlotServer {
383
403
  record.expires = this.#expiry();
384
404
  const page = new record.PageClass();
385
405
  page.pageId = pageId;
406
+ Object.defineProperty(page, 'requestIdentity', {value:identity, writable:false});
407
+ if (contentType === 'upload') return this.#uploadControl(page, pageId, owner, identity, name, params);
386
408
  const source = contentType === 'source';
387
409
  let instance = page;
388
410
  let callable = page.main;
@@ -411,6 +433,68 @@ export class GramlotServer {
411
433
  return builder.toTytx();
412
434
  }
413
435
 
436
+ #uploadOperation(page, operation, owner, identity) {
437
+ const declared = this.nameSyntax.matches(operation) ? resolveDeclared(page, operation, UPLOAD_METHOD) : null;
438
+ if (!declared) throw new EndpointNotFound(`Unknown upload operation: ${operation}`);
439
+ const refused = this.#authOutcome(declared.method[UPLOAD_METHOD].auth, owner, identity);
440
+ if (refused) throw new (refused === 'not_authenticated' ? NotAuthenticated : NotAuthorized)(`Access refused: ${operation}`);
441
+ return declared;
442
+ }
443
+
444
+ async #uploadControl(page, pageId, owner, identity, name, params) {
445
+ if (!this.uploads) throw new EndpointNotFound('Upload is unavailable');
446
+ await this.uploads.expire();
447
+ this.prune();
448
+ if (this.pages.get(pageId)?.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
449
+ if (name === 'prepare') {
450
+ if (Object.keys(params).sort().join(',') !== 'metadata,operation') throw new TypeError('Invalid upload preparation');
451
+ const {operation, metadata} = params;
452
+ if (typeof operation !== 'string' || !isMapping(metadata) ||
453
+ Object.keys(metadata).sort().join(',') !== 'context,fields,mediaType,name,size' ||
454
+ typeof metadata.name !== 'string' || typeof metadata.mediaType !== 'string' ||
455
+ !Number.isSafeInteger(metadata.size) || metadata.size < 0 || !isMapping(metadata.fields) || !isMapping(metadata.context)) {
456
+ throw new TypeError('Invalid upload metadata');
457
+ }
458
+ const {instance, method} = this.#uploadOperation(page, operation, owner, identity);
459
+ const target = await method.call(instance, metadata);
460
+ let registered = false;
461
+ try {
462
+ this.prune();
463
+ if (this.pages.get(pageId)?.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
464
+ this.#uploadOperation(page, operation, owner, identity);
465
+ const grant = await this.uploads.prepare({pageId, owner, operation, target, size:metadata.size});
466
+ registered = true;
467
+ this.prune();
468
+ if (this.pages.get(pageId)?.owner !== owner) {
469
+ await this.uploads.closePage(pageId, owner);
470
+ throw new PageExpired('Unknown, expired or unowned page');
471
+ }
472
+ return grant;
473
+ } catch (error) {
474
+ if (target instanceof UploadTarget && !registered) await target.abort();
475
+ throw error;
476
+ }
477
+ }
478
+ if (!['status','cancel'].includes(name) || Object.keys(params).join(',') !== 'transferId') throw new TypeError('Invalid upload control');
479
+ const record = this.uploads.record(params.transferId, pageId, owner);
480
+ this.#uploadOperation(page, record.operation, owner, identity);
481
+ return name === 'status' ? record.transfer.status() : record.transfer.abort();
482
+ }
483
+
484
+ /** Admit a single binary upload; adapters provide the current request identity. */
485
+ admitUpload({pageId, owner = null, identity = null, transferId, authorization}) {
486
+ this.prune();
487
+ if (!this.uploads) throw new EndpointNotFound('Upload is unavailable');
488
+ const record = this.pages.get(pageId);
489
+ if (!record || record.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
490
+ const page = new record.PageClass();
491
+ page.pageId = pageId;
492
+ Object.defineProperty(page, 'requestIdentity', {value:identity, writable:false});
493
+ const upload = this.uploads.record(transferId, pageId, owner);
494
+ this.#uploadOperation(page, upload.operation, owner, identity);
495
+ return this.uploads.admit(transferId, pageId, owner, authorization);
496
+ }
497
+
414
498
  /** Close the page named by the close message `text`, `{"pageId": string}` as JSON, when `owner`
415
499
  * owns it (GC-230 §125); an unknown or unowned page is left as it is. A text that is not JSON, or
416
500
  * whose pageId is not a string, is an InvalidRequest. */
@@ -428,11 +512,15 @@ export class GramlotServer {
428
512
  }
429
513
 
430
514
  closePage(pageId, {owner = null} = {}) {
431
- if (this.pages.get(pageId)?.owner === owner) this.pages.delete(pageId);
515
+ if (this.pages.get(pageId)?.owner === owner) {
516
+ this.pages.delete(pageId);
517
+ void this.uploads?.closePage(pageId, owner);
518
+ }
432
519
  }
433
520
 
434
521
  /** Forget every registered page; adapters call it on shutdown. */
435
522
  closeAll() {
523
+ for (const [pageId, record] of this.pages) void this.uploads?.closePage(pageId, record.owner);
436
524
  this.pages = new Map();
437
525
  }
438
526
 
@@ -17,3 +17,5 @@ export {InvalidResourceName, parseRequires} from './resources.js';
17
17
  export type {Resources} from './resources.js';
18
18
  export {NAME_SYNTAX, NameSyntax} from '../builder/name-syntax.js';
19
19
  export type {NameSyntaxDescriptor} from '../builder/name-syntax.js';
20
+
21
+ export {UploadTarget} from './upload.js';
@@ -15,3 +15,5 @@ export {gramlotDev, runtimeAsset} from './assets.js';
15
15
  export {checkProtocol} from './conformance.js';
16
16
  export {InvalidResourceName, parseRequires} from './resources.js';
17
17
  export {NAME_SYNTAX, NameSyntax} from '../builder/name-syntax.js';
18
+
19
+ export {UploadTarget} from './upload.js';
@@ -12,7 +12,8 @@ import {NAME_SYNTAX} from '../builder/name-syntax.js';
12
12
  * `__gramlot_source__` and `__gramlot_endpoint__` attributes. */
13
13
  export const SOURCE_METHOD = Symbol('gramlot.source');
14
14
  export const ENDPOINT_METHOD = Symbol('gramlot.endpoint');
15
- const MARKERS = new Map([[SOURCE_METHOD, 'registerSource'], [ENDPOINT_METHOD, 'registerEndpoint']]);
15
+ export const UPLOAD_METHOD = Symbol('gramlot.upload');
16
+ const MARKERS = new Map([[SOURCE_METHOD, 'registerSource'], [ENDPOINT_METHOD, 'registerEndpoint'], [UPLOAD_METHOD, 'registerUpload']]);
16
17
 
17
18
  // The name of a declared method, one segment of NAME_SYNTAX: an ASCII letter, then ASCII letters, digits and `_`.
18
19
  const DECLARED_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
@@ -34,6 +35,10 @@ export function endpointMethod(page, name) {
34
35
  return declaredMethod(page, name, ENDPOINT_METHOD);
35
36
  }
36
37
 
38
+ export function uploadMethod(page, name) {
39
+ return declaredMethod(page, name, UPLOAD_METHOD);
40
+ }
41
+
37
42
  /**
38
43
  * The method a request names, `{instance, method}`, or null; `method` runs with `this` = `instance`.
39
44
  * `name` is a method of `page` or a path `a.b.c.method` (NAME_SYNTAX) read from `page`: every segment
@@ -62,10 +67,13 @@ function declare(PageClass, methodName, marker, auth) {
62
67
  throw new TypeError(`${register} requires an own method of ${PageClass.name}: ${String(methodName)}`);
63
68
  }
64
69
  if (method[marker]) {
65
- throw new TypeError(`${marker === SOURCE_METHOD ? 'Source method' : 'Endpoint'} already registered: ${methodName}`);
70
+ throw new TypeError(`${marker === SOURCE_METHOD ? 'Source method' : marker === ENDPOINT_METHOD ? 'Endpoint' : 'Upload operation'} already registered: ${methodName}`);
66
71
  }
67
- if (method[SOURCE_METHOD] || method[ENDPOINT_METHOD]) {
68
- throw new TypeError(`${methodName} is declared both as Source method and endpoint`);
72
+ if ([SOURCE_METHOD, ENDPOINT_METHOD, UPLOAD_METHOD].some(existing => method[existing])) {
73
+ const message = marker !== UPLOAD_METHOD && !method[UPLOAD_METHOD]
74
+ ? `${methodName} is declared both as Source method and endpoint`
75
+ : `${methodName} has conflicting declarations`;
76
+ throw new TypeError(message);
69
77
  }
70
78
  method[marker] = {auth};
71
79
  }
@@ -92,6 +100,11 @@ export class Exposed {
92
100
  static registerEndpoint(methodName, {auth = null} = {}) {
93
101
  declare(this, methodName, ENDPOINT_METHOD, auth);
94
102
  }
103
+
104
+ /** Mark an application operation for upload preparation. */
105
+ static registerUpload(methodName, {auth = null} = {}) {
106
+ declare(this, methodName, UPLOAD_METHOD, auth);
107
+ }
95
108
  }
96
109
 
97
110
  /** Server-side page base; unrelated to browser view components. */
@@ -11,17 +11,20 @@ import type {GramlotBuilder} from '../builder/gramlot-builder.js';
11
11
  export const SOURCE_METHOD: unique symbol;
12
12
  /** The marker of an endpoint: `{auth}` on the method. */
13
13
  export const ENDPOINT_METHOD: unique symbol;
14
+ /** The marker of an upload operation. */
15
+ export const UPLOAD_METHOD: unique symbol;
14
16
 
15
17
  /** The registered Source method `name` of `page`, or null. */
16
18
  export function sourceMethod(page: Page, name: string): Function | null;
17
19
  /** The registered endpoint `name` of `page`, or null. */
18
20
  export function endpointMethod(page: Page, name: string): Function | null;
21
+ export function uploadMethod(page: Page, name: string): Function | null;
19
22
  /**
20
23
  * The method a request names, or null; `method` runs with `this` = `instance`. `name` is a method of
21
24
  * `page` or a path `a.b.c.method` read from `page`: every segment is a public attribute whose value is an
22
25
  * `Exposed` instance, and the last one is a method declared with `marker`.
23
26
  */
24
- export function resolveDeclared(page: Page, name: string, marker: typeof SOURCE_METHOD | typeof ENDPOINT_METHOD):
27
+ export function resolveDeclared(page: Page, name: string, marker: typeof SOURCE_METHOD | typeof ENDPOINT_METHOD | typeof UPLOAD_METHOD):
25
28
  {instance: Exposed, method: Function} | null;
26
29
 
27
30
  /**
@@ -41,10 +44,13 @@ export class Exposed {
41
44
  /** Mark the own method `methodName` of this class as an endpoint called with
42
45
  * `contentType: 'data'`, equivalent to the Python `@endpoint`; call it after the class. */
43
46
  static registerEndpoint(methodName: string, options?: {auth?: string | null}): void;
47
+ static registerUpload(methodName: string, options?: {auth?: string | null}): void;
44
48
  }
45
49
 
46
50
  /** Server-side page base; unrelated to browser view components. */
47
51
  export class Page extends Exposed {
52
+ /** Trusted host identity of the current invocation, or null. */
53
+ readonly requestIdentity: unknown;
48
54
  /** The title of the page document. */
49
55
  static title: string;
50
56
  /** Class-local prepared collections; inherited declarations accumulate. */
@@ -85,3 +91,9 @@ export {codeMirrorWithOptions} from '../components/editor-options.js';
85
91
 
86
92
  export {fileSystemTree, FileSystemLogic, FileSystemController, DirectoryResolver} from "../filesystem.js";
87
93
  export {IdeLogic} from "../ide-runtime.js";
94
+
95
+ export {TreeStore, TreeStoreResolver, TreeStoreLogic} from '../tree-store.js';
96
+ export {UploadTarget} from './upload.js';
97
+
98
+ export {VisualEditor} from './visual-editor.js';
99
+ export {SourceImport} from './source-import.js';
@@ -13,3 +13,9 @@ export {codeMirrorWithOptions} from '../components/editor-options.js';
13
13
 
14
14
  export {fileSystemTree, FileSystemLogic, FileSystemController, DirectoryResolver} from "../filesystem.js";
15
15
  export {IdeLogic} from "../ide-runtime.js";
16
+
17
+ export {TreeStore, TreeStoreResolver, TreeStoreLogic} from '../tree-store.js';
18
+ export {UploadTarget} from './upload.js';
19
+
20
+ export {VisualEditor} from './visual-editor.js';
21
+ export {SourceImport} from './source-import.js';
@@ -0,0 +1,2 @@
1
+ import {UploadTarget} from './upload.js';
2
+ export class SourceImport extends UploadTarget { constructor(); }
@@ -0,0 +1,31 @@
1
+ import {fromTytx} from '@genrojs/tytx';
2
+ import {SourceBag} from '@genrojs/builders';
3
+ import {UploadTarget} from './upload.js';
4
+ export class SourceImport extends UploadTarget {
5
+ constructor() {
6
+ super({maxBytes:5 * 1024 * 1024});
7
+ this.decoder = new TextDecoder('utf-8', {fatal:true});
8
+ this.parts = [];
9
+ this.outcome = {state:'pending'};
10
+ }
11
+ write(chunk) { this.parts.push(this.decoder.decode(chunk, {stream:true})); }
12
+ finish() {
13
+ this.parts.push(this.decoder.decode());
14
+ const wire = this.parts.join('');
15
+ this.parts = [];
16
+ const source = fromTytx(wire);
17
+ if (!(source instanceof SourceBag) || source.length !== 1 || source.getNodes()[0].label !== 'pageRoot') {
18
+ throw new TypeError('Expected one pageRoot Source');
19
+ }
20
+ this.outcome = {state:'completed', result:wire};
21
+ return this.outcome;
22
+ }
23
+ abort() {
24
+ if (this.outcome.state !== 'completed') {
25
+ this.parts = [];
26
+ this.outcome = {state:'unsaved'};
27
+ }
28
+ return this.outcome;
29
+ }
30
+ status() { return this.outcome; }
31
+ }
@@ -0,0 +1,20 @@
1
+ /** Application-owned destination for one upload; methods may be asynchronous. */
2
+ export class UploadTarget {
3
+ constructor(options: {maxBytes: number});
4
+ readonly maxBytes: number;
5
+ write(chunk: Uint8Array): void | Promise<void>;
6
+ finish(): UploadOutcome | Promise<UploadOutcome>;
7
+ abort(): UploadOutcome | Promise<UploadOutcome>;
8
+ status(): UploadOutcome | Promise<UploadOutcome>;
9
+ }
10
+ export type UploadOutcome = {state: 'completed'; result: unknown} | {state: 'unsaved' | 'pending' | 'uncertain'};
11
+
12
+ /** Internal serialized transfer returned to a binary adapter. */
13
+ export class UploadTransfer {
14
+ constructor(target: UploadTarget, size: number);
15
+ readonly size: number;
16
+ write(chunk: Uint8Array): Promise<void>;
17
+ finish(): Promise<UploadOutcome>;
18
+ abort(): Promise<UploadOutcome>;
19
+ status(): Promise<UploadOutcome>;
20
+ }