package core import ( "context" "encoding/binary" "errors" "math" "unicode/utf8" ) // InitialBlock is literal text. Level zero is a paragraph, 1..6 a heading. type InitialBlock struct { Text string Level uint8 } // InitialUpdate builds a fresh document in the real core and returns its wire // update. Its handle is never exposed or reused, even after a trap or timeout. func (r *Runtime) InitialUpdate(ctx context.Context, guid string, clientID uint64, blocks []InitialBlock) ([]byte, error) { if clientID > math.MaxUint32 { return nil, errors.New("core: initial client id limit") } if len(blocks) > 200 { return nil, errors.New("core: initial block limit") } raw := make([]byte, 0) total := 0 for _, block := range blocks { total += len(block.Text) if block.Level > 6 || !utf8.ValidString(block.Text) || total > 128<<10 { return nil, errors.New("core: invalid initial block") } raw = append(raw, block.Level) raw = binary.BigEndian.AppendUint32(raw, uint32(len(block.Text))) raw = append(raw, block.Text...) } h, err := r.NewDoc(ctx, guid, clientID) if err != nil { return nil, err } defer h.Close(ctx) ptr, err := allocIn(ctx, r.callTimeout, h.mod, uint64(len(raw))) if err != nil { return nil, err } defer freeIn(ctx, r.callTimeout, h.mod, ptr, uint64(len(raw))) if !h.mod.Memory().Write(uint32(ptr), raw) { return nil, errors.New("core: initial memory write") } result, err := callGuest(ctx, r.callTimeout, h.mod.ExportedFunction("docs_core_initialize"), h.handle, ptr, uint64(len(raw))) if err != nil { return nil, err } if len(result) != 1 || int32(result[0]) != 0 { return nil, errors.New("core: initial content refused") } // No retry through Handle.read: its recovery log is intentionally empty. // Read directly and discard the whole handle on any uncertain outcome. out, err := readOn(ctx, r.callTimeout, h.mod, h.handle, "snapshot") if err != nil { return nil, err } if len(out) > 1<<20 { return nil, errors.New("core: initial output limit") } return []byte(out), nil }